]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
emacs: No longer define notmuch-hello-mode-map as a function
[notmuch] / emacs / notmuch-hello.el
1 ;;; notmuch-hello.el --- welcome to notmuch, a frontend
2 ;;
3 ;; Copyright © David Edmondson
4 ;;
5 ;; This file is part of Notmuch.
6 ;;
7 ;; Notmuch is free software: you can redistribute it and/or modify it
8 ;; under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11 ;;
12 ;; Notmuch is distributed in the hope that it will be useful, but
13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with Notmuch.  If not, see <https://www.gnu.org/licenses/>.
19 ;;
20 ;; Authors: David Edmondson <dme@dme.org>
21
22 ;;; Code:
23
24 (eval-when-compile (require 'cl-lib))
25
26 (require 'widget)
27 (require 'wid-edit) ; For `widget-forward'.
28
29 (require 'notmuch-lib)
30 (require 'notmuch-mua)
31
32 (declare-function notmuch-search "notmuch"
33                   (&optional query oldest-first target-thread target-line continuation))
34 (declare-function notmuch-poll "notmuch" ())
35 (declare-function notmuch-tree "notmuch-tree"
36                   (&optional query query-context target buffer-name open-target unthreaded))
37 (declare-function notmuch-unthreaded
38                   (&optional query query-context target buffer-name open-target))
39
40
41 (defun notmuch-saved-search-get (saved-search field)
42   "Get FIELD from SAVED-SEARCH.
43
44 If SAVED-SEARCH is a plist, this is just `plist-get', but for
45 backwards compatibility, this also deals with the two other
46 possible formats for SAVED-SEARCH: cons cells (NAME . QUERY) and
47 lists (NAME QUERY COUNT-QUERY)."
48   (cond
49    ((keywordp (car saved-search))
50     (plist-get saved-search field))
51    ;; It is not a plist so it is an old-style entry.
52    ((consp (cdr saved-search))
53     (pcase-let ((`(,name ,query ,count-query) saved-search))
54       (cl-case field
55         (:name name)
56         (:query query)
57         (:count-query count-query)
58         (t nil))))
59    (t
60     (pcase-let ((`(,name . ,query) saved-search))
61       (cl-case field
62         (:name name)
63         (:query query)
64         (t nil))))))
65
66 (defun notmuch-hello-saved-search-to-plist (saved-search)
67   "Return a copy of SAVED-SEARCH in plist form.
68
69 If saved search is a plist then just return a copy. In other
70 cases, for backwards compatibility, convert to plist form and
71 return that."
72   (if (keywordp (car saved-search))
73       (copy-sequence saved-search)
74     (let ((fields (list :name :query :count-query))
75           plist-search)
76       (dolist (field fields plist-search)
77         (let ((string (notmuch-saved-search-get saved-search field)))
78           (when string
79             (setq plist-search (append plist-search (list field string)))))))))
80
81 (defun notmuch-hello--saved-searches-to-plist (symbol)
82   "Extract a saved-search variable into plist form.
83
84 The new style saved search is just a plist, but for backwards
85 compatibility we use this function to extract old style saved
86 searches so they still work in customize."
87   (let ((saved-searches (default-value symbol)))
88     (mapcar #'notmuch-hello-saved-search-to-plist saved-searches)))
89
90 (define-widget 'notmuch-saved-search-plist 'list
91   "A single saved search property list."
92   :tag "Saved Search"
93   :args '((list :inline t
94                 :format "%v"
95                 (group :format "%v" :inline t
96                        (const :format "   Name: " :name)
97                        (string :format "%v"))
98                 (group :format "%v" :inline t
99                        (const :format "  Query: " :query)
100                        (string :format "%v")))
101           (checklist :inline t
102                      :format "%v"
103                      (group :format "%v" :inline t
104                             (const :format "Shortcut key: " :key)
105                             (key-sequence :format "%v"))
106                      (group :format "%v" :inline t
107                             (const :format "Count-Query: " :count-query)
108                             (string :format "%v"))
109                      (group :format "%v" :inline t
110                             (const :format "" :sort-order)
111                             (choice :tag " Sort Order"
112                                     (const :tag "Default" nil)
113                                     (const :tag "Oldest-first" oldest-first)
114                                     (const :tag "Newest-first" newest-first)))
115                      (group :format "%v" :inline t
116                             (const :format "" :search-type)
117                             (choice :tag " Search Type"
118                                     (const :tag "Search mode" nil)
119                                     (const :tag "Tree mode" tree)
120                                     (const :tag "Unthreaded mode" unthreaded))))))
121
122 (defcustom notmuch-saved-searches
123   `((:name "inbox" :query "tag:inbox" :key ,(kbd "i"))
124     (:name "unread" :query "tag:unread" :key ,(kbd "u"))
125     (:name "flagged" :query "tag:flagged" :key ,(kbd "f"))
126     (:name "sent" :query "tag:sent" :key ,(kbd "t"))
127     (:name "drafts" :query "tag:draft" :key ,(kbd "d"))
128     (:name "all mail" :query "*" :key ,(kbd "a")))
129   "A list of saved searches to display.
130
131 The saved search can be given in 3 forms. The preferred way is as
132 a plist. Supported properties are
133
134   :name            Name of the search (required).
135   :query           Search to run (required).
136   :key             Optional shortcut key for `notmuch-jump-search'.
137   :count-query     Optional extra query to generate the count
138                    shown. If not present then the :query property
139                    is used.
140   :sort-order      Specify the sort order to be used for the search.
141                    Possible values are 'oldest-first 'newest-first or
142                    nil. Nil means use the default sort order.
143   :search-type     Specify whether to run the search in search-mode,
144                    tree mode or unthreaded mode. Set to 'tree to specify tree
145                    mode, 'unthreaded to specify unthreaded mode, and set to nil
146                    (or anything except tree and unthreaded) to specify search mode.
147
148 Other accepted forms are a cons cell of the form (NAME . QUERY)
149 or a list of the form (NAME QUERY COUNT-QUERY)."
150   ;; The saved-search format is also used by the all-tags notmuch-hello
151   ;; section. This section generates its own saved-search list in one of
152   ;; the latter two forms.
153   :get 'notmuch-hello--saved-searches-to-plist
154   :type '(repeat notmuch-saved-search-plist)
155   :tag "List of Saved Searches"
156   :group 'notmuch-hello)
157
158 (defcustom notmuch-hello-recent-searches-max 10
159   "The number of recent searches to display."
160   :type 'integer
161   :group 'notmuch-hello)
162
163 (defcustom notmuch-show-empty-saved-searches nil
164   "Should saved searches with no messages be listed?"
165   :type 'boolean
166   :group 'notmuch-hello)
167
168 (defun notmuch-sort-saved-searches (saved-searches)
169   "Generate an alphabetically sorted saved searches list."
170   (sort (copy-sequence saved-searches)
171         (lambda (a b)
172           (string< (notmuch-saved-search-get a :name)
173                    (notmuch-saved-search-get b :name)))))
174
175 (defcustom notmuch-saved-search-sort-function nil
176   "Function used to sort the saved searches for the notmuch-hello view.
177
178 This variable controls how saved searches should be sorted. No
179 sorting (nil) displays the saved searches in the order they are
180 stored in `notmuch-saved-searches'. Sort alphabetically sorts the
181 saved searches in alphabetical order. Custom sort function should
182 be a function or a lambda expression that takes the saved
183 searches list as a parameter, and returns a new saved searches
184 list to be used. For compatibility with the various saved-search
185 formats it should use notmuch-saved-search-get to access the
186 fields of the search."
187   :type '(choice (const :tag "No sorting" nil)
188                  (const :tag "Sort alphabetically" notmuch-sort-saved-searches)
189                  (function :tag "Custom sort function"
190                            :value notmuch-sort-saved-searches))
191   :group 'notmuch-hello)
192
193 (defvar notmuch-hello-indent 4
194   "How much to indent non-headers.")
195
196 (defcustom notmuch-show-logo t
197   "Should the notmuch logo be shown?"
198   :type 'boolean
199   :group 'notmuch-hello)
200
201 (defcustom notmuch-show-all-tags-list nil
202   "Should all tags be shown in the notmuch-hello view?"
203   :type 'boolean
204   :group 'notmuch-hello)
205
206 (defcustom notmuch-hello-tag-list-make-query nil
207   "Function or string to generate queries for the all tags list.
208
209 This variable controls which query results are shown for each tag
210 in the \"all tags\" list. If nil, it will use all messages with
211 that tag. If this is set to a string, it is used as a filter for
212 messages having that tag (equivalent to \"tag:TAG and (THIS-VARIABLE)\").
213 Finally this can be a function that will be called for each tag and
214 should return a filter for that tag, or nil to hide the tag."
215   :type '(choice (const :tag "All messages" nil)
216                  (const :tag "Unread messages" "tag:unread")
217                  (string :tag "Custom filter"
218                          :value "tag:unread")
219                  (function :tag "Custom filter function"))
220   :group 'notmuch-hello)
221
222 (defcustom notmuch-hello-hide-tags nil
223   "List of tags to be hidden in the \"all tags\"-section."
224   :type '(repeat string)
225   :group 'notmuch-hello)
226
227 (defface notmuch-hello-logo-background
228   '((((class color)
229       (background dark))
230      (:background "#5f5f5f"))
231     (((class color)
232       (background light))
233      (:background "white")))
234   "Background colour for the notmuch logo."
235   :group 'notmuch-hello
236   :group 'notmuch-faces)
237
238 (defcustom notmuch-column-control t
239   "Controls the number of columns for saved searches/tags in notmuch view.
240
241 This variable has three potential sets of values:
242
243 - t: automatically calculate the number of columns possible based
244   on the tags to be shown and the window width,
245 - an integer: a lower bound on the number of characters that will
246   be used to display each column,
247 - a float: a fraction of the window width that is the lower bound
248   on the number of characters that should be used for each
249   column.
250
251 So:
252 - if you would like two columns of tags, set this to 0.5.
253 - if you would like a single column of tags, set this to 1.0.
254 - if you would like tags to be 30 characters wide, set this to
255   30.
256 - if you don't want to worry about all of this nonsense, leave
257   this set to `t'."
258   :type '(choice
259           (const :tag "Automatically calculated" t)
260           (integer :tag "Number of characters")
261           (float :tag "Fraction of window"))
262   :group 'notmuch-hello)
263
264 (defcustom notmuch-hello-thousands-separator " "
265   "The string used as a thousands separator.
266
267 Typically \",\" in the US and UK and \".\" or \" \" in Europe.
268 The latter is recommended in the SI/ISO 31-0 standard and by the
269 International Bureau of Weights and Measures."
270   :type 'string
271   :group 'notmuch-hello)
272
273 (defcustom notmuch-hello-mode-hook nil
274   "Functions called after entering `notmuch-hello-mode'."
275   :type 'hook
276   :group 'notmuch-hello
277   :group 'notmuch-hooks)
278
279 (defcustom notmuch-hello-refresh-hook nil
280   "Functions called after updating a `notmuch-hello' buffer."
281   :type 'hook
282   :group 'notmuch-hello
283   :group 'notmuch-hooks)
284
285 (defvar notmuch-hello-url "https://notmuchmail.org"
286   "The `notmuch' web site.")
287
288 (defvar notmuch-hello-custom-section-options
289   '((:filter (string :tag "Filter for each tag"))
290     (:filter-count (string :tag "Different filter to generate message counts"))
291     (:initially-hidden (const :tag "Hide this section on startup" t))
292     (:show-empty-searches (const :tag "Show queries with no matching messages" t))
293     (:hide-if-empty (const :tag "Hide this section if all queries are empty
294 \(and not shown by show-empty-searches)" t)))
295   "Various customization-options for notmuch-hello-tags/query-section.")
296
297 (define-widget 'notmuch-hello-tags-section 'lazy
298   "Customize-type for notmuch-hello tag-list sections."
299   :tag "Customized tag-list section (see docstring for details)"
300   :type
301   `(list :tag ""
302          (const :tag "" notmuch-hello-insert-tags-section)
303          (string :tag "Title for this section")
304          (plist
305           :inline t
306           :options
307           ,(append notmuch-hello-custom-section-options
308                    '((:hide-tags (repeat :tag "Tags that will be hidden"
309                                          string)))))))
310
311 (define-widget 'notmuch-hello-query-section 'lazy
312   "Customize-type for custom saved-search-like sections"
313   :tag "Customized queries section (see docstring for details)"
314   :type
315   `(list :tag ""
316          (const :tag "" notmuch-hello-insert-searches)
317          (string :tag "Title for this section")
318          (repeat :tag "Queries"
319                  (cons (string :tag "Name") (string :tag "Query")))
320          (plist :inline t :options ,notmuch-hello-custom-section-options)))
321
322 (defcustom notmuch-hello-sections
323   (list #'notmuch-hello-insert-header
324         #'notmuch-hello-insert-saved-searches
325         #'notmuch-hello-insert-search
326         #'notmuch-hello-insert-recent-searches
327         #'notmuch-hello-insert-alltags
328         #'notmuch-hello-insert-footer)
329   "Sections for notmuch-hello.
330
331 The list contains functions which are used to construct sections in
332 notmuch-hello buffer.  When notmuch-hello buffer is constructed,
333 these functions are run in the order they appear in this list.  Each
334 function produces a section simply by adding content to the current
335 buffer.  A section should not end with an empty line, because a
336 newline will be inserted after each section by `notmuch-hello'.
337
338 Each function should take no arguments. The return value is
339 ignored.
340
341 For convenience an element can also be a list of the form (FUNC ARG1
342 ARG2 .. ARGN) in which case FUNC will be applied to the rest of the
343 list.
344
345 A \"Customized tag-list section\" item in the customize-interface
346 displays a list of all tags, optionally hiding some of them. It
347 is also possible to filter the list of messages matching each tag
348 by an additional filter query. Similarly, the count of messages
349 displayed next to the buttons can be generated by applying a
350 different filter to the tag query. These filters are also
351 supported for \"Customized queries section\" items."
352   :group 'notmuch-hello
353   :type
354   '(repeat
355     (choice (function-item notmuch-hello-insert-header)
356             (function-item notmuch-hello-insert-saved-searches)
357             (function-item notmuch-hello-insert-search)
358             (function-item notmuch-hello-insert-recent-searches)
359             (function-item notmuch-hello-insert-alltags)
360             (function-item notmuch-hello-insert-footer)
361             (function-item notmuch-hello-insert-inbox)
362             notmuch-hello-tags-section
363             notmuch-hello-query-section
364             (function :tag "Custom section"))))
365
366 (defcustom notmuch-hello-auto-refresh t
367   "Automatically refresh when returning to the notmuch-hello buffer."
368   :group 'notmuch-hello
369   :type 'boolean)
370
371 (defvar notmuch-hello-hidden-sections nil
372   "List of sections titles whose contents are hidden.")
373
374 (defvar notmuch-hello-first-run t
375   "True if `notmuch-hello' is run for the first time, set to nil
376 afterwards.")
377
378 (defun notmuch-hello-nice-number (n)
379   (let (result)
380     (while (> n 0)
381       (push (% n 1000) result)
382       (setq n (/ n 1000)))
383     (setq result (or result '(0)))
384     (apply #'concat
385            (number-to-string (car result))
386            (mapcar (lambda (elem)
387                      (format "%s%03d" notmuch-hello-thousands-separator elem))
388                    (cdr result)))))
389
390 (defun notmuch-hello-trim (search)
391   "Trim whitespace."
392   (if (string-match "^[[:space:]]*\\(.*[^[:space:]]\\)[[:space:]]*$" search)
393       (match-string 1 search)
394     search))
395
396 (defun notmuch-hello-search (&optional search)
397   (unless (null search)
398     (setq search (notmuch-hello-trim search))
399     (let ((history-delete-duplicates t))
400       (add-to-history 'notmuch-search-history search)))
401   (notmuch-search search notmuch-search-oldest-first))
402
403 (defun notmuch-hello-add-saved-search (widget)
404   (interactive)
405   (let ((search (widget-value
406                  (symbol-value
407                   (widget-get widget :notmuch-saved-search-widget))))
408         (name (completing-read "Name for saved search: "
409                                notmuch-saved-searches)))
410     ;; If an existing saved search with this name exists, remove it.
411     (setq notmuch-saved-searches
412           (cl-loop for elem in notmuch-saved-searches
413                    if (not (equal name
414                                   (notmuch-saved-search-get elem :name)))
415                    collect elem))
416     ;; Add the new one.
417     (customize-save-variable 'notmuch-saved-searches
418                              (add-to-list 'notmuch-saved-searches
419                                           (list :name name :query search) t))
420     (message "Saved '%s' as '%s'." search name)
421     (notmuch-hello-update)))
422
423 (defun notmuch-hello-delete-search-from-history (widget)
424   (interactive)
425   (let ((search (widget-value
426                  (symbol-value
427                   (widget-get widget :notmuch-saved-search-widget)))))
428     (setq notmuch-search-history (delete search
429                                          notmuch-search-history))
430     (notmuch-hello-update)))
431
432 (defun notmuch-hello-longest-label (searches-alist)
433   (or (cl-loop for elem in searches-alist
434                maximize (length (notmuch-saved-search-get elem :name)))
435       0))
436
437 (defun notmuch-hello-reflect-generate-row (ncols nrows row list)
438   (let ((len (length list)))
439     (cl-loop for col from 0 to (- ncols 1)
440              collect (let ((offset (+ (* nrows col) row)))
441                        (if (< offset len)
442                            (nth offset list)
443                          ;; Don't forget to insert an empty slot in the
444                          ;; output matrix if there is no corresponding
445                          ;; value in the input matrix.
446                          nil)))))
447
448 (defun notmuch-hello-reflect (list ncols)
449   "Reflect a `ncols' wide matrix represented by `list' along the
450 diagonal."
451   ;; Not very lispy...
452   (let ((nrows (ceiling (length list) ncols)))
453     (cl-loop for row from 0 to (- nrows 1)
454              append (notmuch-hello-reflect-generate-row ncols nrows row list))))
455
456 (defun notmuch-hello-widget-search (widget &rest ignore)
457   (cond
458    ((eq (widget-get widget :notmuch-search-type) 'tree)
459     (notmuch-tree (widget-get widget
460                               :notmuch-search-terms)))
461    ((eq (widget-get widget :notmuch-search-type) 'unthreaded)
462     (notmuch-unthreaded (widget-get widget
463                                     :notmuch-search-terms)))
464    (t
465     (notmuch-search (widget-get widget
466                                 :notmuch-search-terms)
467                     (widget-get widget
468                                 :notmuch-search-oldest-first)))))
469
470 (defun notmuch-saved-search-count (search)
471   (car (process-lines notmuch-command "count" search)))
472
473 (defun notmuch-hello-tags-per-line (widest)
474   "Determine how many tags to show per line and how wide they
475 should be. Returns a cons cell `(tags-per-line width)'."
476   (let ((tags-per-line
477          (cond
478           ((integerp notmuch-column-control)
479            (max 1
480                 (/ (- (window-width) notmuch-hello-indent)
481                    ;; Count is 9 wide (8 digits plus space), 1 for the space
482                    ;; after the name.
483                    (+ 9 1 (max notmuch-column-control widest)))))
484           ((floatp notmuch-column-control)
485            (let* ((available-width (- (window-width) notmuch-hello-indent))
486                   (proposed-width (max (* available-width notmuch-column-control)
487                                        widest)))
488              (floor available-width proposed-width)))
489           (t
490            (max 1
491                 (/ (- (window-width) notmuch-hello-indent)
492                    ;; Count is 9 wide (8 digits plus space), 1 for the space
493                    ;; after the name.
494                    (+ 9 1 widest)))))))
495     (cons tags-per-line (/ (max 1
496                                 (- (window-width) notmuch-hello-indent
497                                    ;; Count is 9 wide (8 digits plus
498                                    ;; space), 1 for the space after the
499                                    ;; name.
500                                    (* tags-per-line (+ 9 1))))
501                            tags-per-line))))
502
503 (defun notmuch-hello-filtered-query (query filter)
504   "Constructs a query to search all messages matching QUERY and FILTER.
505
506 If FILTER is a string, it is directly used in the returned query.
507
508 If FILTER is a function, it is called with QUERY as a parameter and
509 the string it returns is used as the query. If nil is returned,
510 the entry is hidden.
511
512 Otherwise, FILTER is ignored."
513   (cond
514    ((functionp filter) (funcall filter query))
515    ((stringp filter)
516     (concat "(" query ") and (" filter ")"))
517    (t query)))
518
519 (defun notmuch-hello-query-counts (query-list &rest options)
520   "Compute list of counts of matched messages from QUERY-LIST.
521
522 QUERY-LIST must be a list of saved-searches. Ideally each of
523 these is a plist but other options are available for backwards
524 compatibility: see `notmuch-saved-searches' for details.
525
526 The result is a list of plists each of which includes the
527 properties :name NAME, :query QUERY and :count COUNT, together
528 with any properties in the original saved-search.
529
530 The values :show-empty-searches, :filter and :filter-count from
531 options will be handled as specified for
532 `notmuch-hello-insert-searches'."
533   (with-temp-buffer
534     (dolist (elem query-list nil)
535       (let ((count-query (or (notmuch-saved-search-get elem :count-query)
536                              (notmuch-saved-search-get elem :query))))
537         (insert
538          (replace-regexp-in-string
539           "\n" " "
540           (notmuch-hello-filtered-query count-query
541                                         (or (plist-get options :filter-count)
542                                             (plist-get options :filter))))
543          "\n")))
544     (unless (= (call-process-region (point-min) (point-max) notmuch-command
545                                     t t nil "count" "--batch") 0)
546       (notmuch-logged-error
547        "notmuch count --batch failed"
548        "Please check that the notmuch CLI is new enough to support `count
549 --batch'. In general we recommend running matching versions of
550 the CLI and emacs interface."))
551     (goto-char (point-min))
552     (notmuch-remove-if-not
553      #'identity
554      (mapcar
555       (lambda (elem)
556         (let* ((elem-plist (notmuch-hello-saved-search-to-plist elem))
557                (search-query (plist-get elem-plist :query))
558                (filtered-query (notmuch-hello-filtered-query
559                                 search-query (plist-get options :filter)))
560                (message-count (prog1 (read (current-buffer))
561                                 (forward-line 1))))
562           (when (and filtered-query (or (plist-get options :show-empty-searches)
563                                         (> message-count 0)))
564             (setq elem-plist (plist-put elem-plist :query filtered-query))
565             (plist-put elem-plist :count message-count))))
566       query-list))))
567
568 (defun notmuch-hello-insert-buttons (searches)
569   "Insert buttons for SEARCHES.
570
571 SEARCHES must be a list of plists each of which should contain at
572 least the properties :name NAME :query QUERY and :count COUNT,
573 where QUERY is the query to start when the button for the
574 corresponding entry is activated, and COUNT should be the number
575 of messages matching the query.  Such a plist can be computed
576 with `notmuch-hello-query-counts'."
577   (let* ((widest (notmuch-hello-longest-label searches))
578          (tags-and-width (notmuch-hello-tags-per-line widest))
579          (tags-per-line (car tags-and-width))
580          (column-width (cdr tags-and-width))
581          (column-indent 0)
582          (count 0)
583          (reordered-list (notmuch-hello-reflect searches tags-per-line))
584          ;; Hack the display of the buttons used.
585          (widget-push-button-prefix "")
586          (widget-push-button-suffix ""))
587     ;; dme: It feels as though there should be a better way to
588     ;; implement this loop than using an incrementing counter.
589     (mapc (lambda (elem)
590             ;; (not elem) indicates an empty slot in the matrix.
591             (when elem
592               (when (> column-indent 0)
593                 (widget-insert (make-string column-indent ? )))
594               (let* ((name (plist-get elem :name))
595                      (query (plist-get elem :query))
596                      (oldest-first (cl-case (plist-get elem :sort-order)
597                                      (newest-first nil)
598                                      (oldest-first t)
599                                      (otherwise notmuch-search-oldest-first)))
600                      (search-type (plist-get elem :search-type))
601                      (msg-count (plist-get elem :count)))
602                 (widget-insert (format "%8s "
603                                        (notmuch-hello-nice-number msg-count)))
604                 (widget-create 'push-button
605                                :notify #'notmuch-hello-widget-search
606                                :notmuch-search-terms query
607                                :notmuch-search-oldest-first oldest-first
608                                :notmuch-search-type search-type
609                                name)
610                 (setq column-indent
611                       (1+ (max 0 (- column-width (length name)))))))
612             (setq count (1+ count))
613             (when (eq (% count tags-per-line) 0)
614               (setq column-indent 0)
615               (widget-insert "\n")))
616           reordered-list)
617     ;; If the last line was not full (and hence did not include a
618     ;; carriage return), insert one now.
619     (unless (eq (% count tags-per-line) 0)
620       (widget-insert "\n"))))
621
622 (defimage notmuch-hello-logo ((:type png :file "notmuch-logo.png")))
623
624 (defun notmuch-hello-update ()
625   "Update the notmuch-hello buffer."
626   ;; Lazy - rebuild everything.
627   (interactive)
628   (notmuch-hello t))
629
630 (defun notmuch-hello-window-configuration-change ()
631   "Hook function to update the hello buffer when it is switched to."
632   (let ((hello-buf (get-buffer "*notmuch-hello*"))
633         (do-refresh nil))
634     ;; Consider all windows in the currently selected frame, since
635     ;; that's where the configuration change happened.  This also
636     ;; refreshes our snapshot of all windows, so we have to do this
637     ;; even if we know we won't refresh (e.g., hello-buf is null).
638     (dolist (window (window-list))
639       (let ((last-buf (window-parameter window 'notmuch-hello-last-buffer))
640             (cur-buf (window-buffer window)))
641         (unless (eq last-buf cur-buf)
642           ;; This window changed or is new.  Update recorded buffer
643           ;; for next time.
644           (set-window-parameter window 'notmuch-hello-last-buffer cur-buf)
645           (when (and (eq cur-buf hello-buf) last-buf)
646             ;; The user just switched to hello in this window (hello
647             ;; is currently visible, was not visible on the last
648             ;; configuration change, and this is not a new window)
649             (setq do-refresh t)))))
650     (when (and do-refresh notmuch-hello-auto-refresh)
651       ;; Refresh hello as soon as we get back to redisplay.  On Emacs
652       ;; 24, we can't do it right here because something in this
653       ;; hook's call stack overrides hello's point placement.
654       (run-at-time nil nil #'notmuch-hello t))
655     (unless hello-buf
656       ;; Clean up hook
657       (remove-hook 'window-configuration-change-hook
658                    #'notmuch-hello-window-configuration-change))))
659
660 ;; the following variable is defined as being defconst in notmuch-version.el
661 (defvar notmuch-emacs-version)
662
663 (defun notmuch-hello-versions ()
664   "Display the notmuch version(s)."
665   (interactive)
666   (let ((notmuch-cli-version (notmuch-cli-version)))
667     (message "notmuch version %s"
668              (if (string= notmuch-emacs-version notmuch-cli-version)
669                  notmuch-cli-version
670                (concat notmuch-cli-version
671                        " (emacs mua version " notmuch-emacs-version ")")))))
672
673 (defvar notmuch-hello-mode-map
674   (let ((map (if (fboundp 'make-composed-keymap)
675                  ;; Inherit both widget-keymap and
676                  ;; notmuch-common-keymap. We have to use
677                  ;; make-sparse-keymap to force this to be a new
678                  ;; keymap (so that when we modify map it does not
679                  ;; modify widget-keymap).
680                  (make-composed-keymap (list (make-sparse-keymap) widget-keymap))
681                ;; Before Emacs 24, keymaps didn't support multiple
682                ;; inheritance,, so just copy the widget keymap since
683                ;; it's unlikely to change.
684                (copy-keymap widget-keymap))))
685     (set-keymap-parent map notmuch-common-keymap)
686     (define-key map "v" 'notmuch-hello-versions)
687     (define-key map (kbd "<C-tab>") 'widget-backward)
688     map)
689   "Keymap for \"notmuch hello\" buffers.")
690
691 (define-derived-mode notmuch-hello-mode fundamental-mode "notmuch-hello"
692   "Major mode for convenient notmuch navigation. This is your entry portal into notmuch.
693
694 Saved searches are \"bookmarks\" for arbitrary queries. Hit RET
695 or click on a saved search to view matching threads. Edit saved
696 searches with the `edit' button. Type `\\[notmuch-jump-search]'
697 in any Notmuch screen for quick access to saved searches that
698 have shortcut keys.
699
700 Type new searches in the search box and hit RET to view matching
701 threads. Hit RET in a recent search box to re-submit a previous
702 search. Edit it first if you like. Save a recent search to saved
703 searches with the `save' button.
704
705 Hit `\\[notmuch-search]' or `\\[notmuch-tree]' in any Notmuch
706 screen to search for messages and view matching threads or
707 messages, respectively. Recent searches are available in the
708 minibuffer history.
709
710 Expand the all tags view with the `show' button (and collapse
711 again with the `hide' button). Hit RET or click on a tag name to
712 view matching threads.
713
714 Hit `\\[notmuch-refresh-this-buffer]' to refresh the screen and
715 `\\[notmuch-bury-or-kill-this-buffer]' to quit.
716
717 The screen may be customized via `\\[customize]'.
718
719 Complete list of currently available key bindings:
720
721 \\{notmuch-hello-mode-map}"
722   (setq notmuch-buffer-refresh-function #'notmuch-hello-update)
723   ;;(setq buffer-read-only t)
724   )
725
726 (defun notmuch-hello-generate-tag-alist (&optional hide-tags)
727   "Return an alist from tags to queries to display in the all-tags section."
728   (mapcar (lambda (tag)
729             (cons tag (concat "tag:" (notmuch-escape-boolean-term tag))))
730           (notmuch-remove-if-not
731            (lambda (tag)
732              (not (member tag hide-tags)))
733            (process-lines notmuch-command "search" "--output=tags" "*"))))
734
735 (defun notmuch-hello-insert-header ()
736   "Insert the default notmuch-hello header."
737   (when notmuch-show-logo
738     (let ((image notmuch-hello-logo))
739       ;; The notmuch logo uses transparency. That can display poorly
740       ;; when inserting the image into an emacs buffer (black logo on
741       ;; a black background), so force the background colour of the
742       ;; image. We use a face to represent the colour so that
743       ;; `defface' can be used to declare the different possible
744       ;; colours, which depend on whether the frame has a light or
745       ;; dark background.
746       (setq image (cons 'image
747                         (append (cdr image)
748                                 (list :background
749                                       (face-background
750                                        'notmuch-hello-logo-background)))))
751       (insert-image image))
752     (widget-insert "  "))
753
754   (widget-insert "Welcome to ")
755   ;; Hack the display of the links used.
756   (let ((widget-link-prefix "")
757         (widget-link-suffix ""))
758     (widget-create 'link
759                    :notify (lambda (&rest ignore)
760                              (browse-url notmuch-hello-url))
761                    :help-echo "Visit the notmuch website."
762                    "notmuch")
763     (widget-insert ". ")
764     (widget-insert "You have ")
765     (widget-create 'link
766                    :notify (lambda (&rest ignore)
767                              (notmuch-hello-update))
768                    :help-echo "Refresh"
769                    (notmuch-hello-nice-number
770                     (string-to-number
771                      (car (process-lines notmuch-command "count")))))
772     (widget-insert " messages.\n")))
773
774 (defun notmuch-hello-insert-saved-searches ()
775   "Insert the saved-searches section."
776   (let ((searches (notmuch-hello-query-counts
777                    (if notmuch-saved-search-sort-function
778                        (funcall notmuch-saved-search-sort-function
779                                 notmuch-saved-searches)
780                      notmuch-saved-searches)
781                    :show-empty-searches notmuch-show-empty-saved-searches)))
782     (when searches
783       (widget-insert "Saved searches: ")
784       (widget-create 'push-button
785                      :notify (lambda (&rest ignore)
786                                (customize-variable 'notmuch-saved-searches))
787                      "edit")
788       (widget-insert "\n\n")
789       (let ((start (point)))
790         (notmuch-hello-insert-buttons searches)
791         (indent-rigidly start (point) notmuch-hello-indent)))))
792
793 (defun notmuch-hello-insert-search ()
794   "Insert a search widget."
795   (widget-insert "Search: ")
796   (widget-create 'editable-field
797                  ;; Leave some space at the start and end of the
798                  ;; search boxes.
799                  :size (max 8 (- (window-width) notmuch-hello-indent
800                                  (length "Search: ")))
801                  :action (lambda (widget &rest ignore)
802                            (notmuch-hello-search (widget-value widget))))
803   ;; Add an invisible dot to make `widget-end-of-line' ignore
804   ;; trailing spaces in the search widget field.  A dot is used
805   ;; instead of a space to make `show-trailing-whitespace'
806   ;; happy, i.e. avoid it marking the whole line as trailing
807   ;; spaces.
808   (widget-insert ".")
809   (put-text-property (1- (point)) (point) 'invisible t)
810   (widget-insert "\n"))
811
812 (defun notmuch-hello-insert-recent-searches ()
813   "Insert recent searches."
814   (when notmuch-search-history
815     (widget-insert "Recent searches: ")
816     (widget-create 'push-button
817                    :notify (lambda (&rest ignore)
818                              (when (y-or-n-p "Are you sure you want to clear the searches? ")
819                                (setq notmuch-search-history nil)
820                                (notmuch-hello-update)))
821                    "clear")
822     (widget-insert "\n\n")
823     (let ((start (point)))
824       (cl-loop for i from 1 to notmuch-hello-recent-searches-max
825                for search in notmuch-search-history do
826                (let ((widget-symbol (intern (format "notmuch-hello-search-%d" i))))
827                  (set widget-symbol
828                       (widget-create 'editable-field
829                                      ;; Don't let the search boxes be
830                                      ;; less than 8 characters wide.
831                                      :size (max 8
832                                                 (- (window-width)
833                                                    ;; Leave some space
834                                                    ;; at the start and
835                                                    ;; end of the
836                                                    ;; boxes.
837                                                    (* 2 notmuch-hello-indent)
838                                                    ;; 1 for the space
839                                                    ;; before the
840                                                    ;; `[save]' button. 6
841                                                    ;; for the `[save]'
842                                                    ;; button.
843                                                    1 6
844                                                    ;; 1 for the space
845                                                    ;; before the `[del]'
846                                                    ;; button. 5 for the
847                                                    ;; `[del]' button.
848                                                    1 5))
849                                      :action (lambda (widget &rest ignore)
850                                                (notmuch-hello-search (widget-value widget)))
851                                      search))
852                  (widget-insert " ")
853                  (widget-create 'push-button
854                                 :notify (lambda (widget &rest ignore)
855                                           (notmuch-hello-add-saved-search widget))
856                                 :notmuch-saved-search-widget widget-symbol
857                                 "save")
858                  (widget-insert " ")
859                  (widget-create 'push-button
860                                 :notify (lambda (widget &rest ignore)
861                                           (when (y-or-n-p "Are you sure you want to delete this search? ")
862                                             (notmuch-hello-delete-search-from-history widget)))
863                                 :notmuch-saved-search-widget widget-symbol
864                                 "del"))
865                (widget-insert "\n"))
866       (indent-rigidly start (point) notmuch-hello-indent))
867     nil))
868
869 (defun notmuch-hello-insert-searches (title query-list &rest options)
870   "Insert a section with TITLE showing a list of buttons made from QUERY-LIST.
871
872 QUERY-LIST should ideally be a plist but for backwards
873 compatibility other forms are also accepted (see
874 `notmuch-saved-searches' for details).  The plist should
875 contain keys :name and :query; if :count-query is also present
876 then it specifies an alternate query to be used to generate the
877 count for the associated search.
878
879 Supports the following entries in OPTIONS as a plist:
880 :initially-hidden - if non-nil, section will be hidden on startup
881 :show-empty-searches - show buttons with no matching messages
882 :hide-if-empty - hide if no buttons would be shown
883    (only makes sense without :show-empty-searches)
884 :filter - This can be a function that takes the search query as its argument and
885    returns a filter to be used in conjunction with the query for that search or nil
886    to hide the element. This can also be a string that is used as a combined with
887    each query using \"and\".
888 :filter-count - Separate filter to generate the count displayed each search. Accepts
889    the same values as :filter. If :filter and :filter-count are specified, this
890    will be used instead of :filter, not in conjunction with it."
891   (widget-insert title ": ")
892   (when (and notmuch-hello-first-run (plist-get options :initially-hidden))
893     (add-to-list 'notmuch-hello-hidden-sections title))
894   (let ((is-hidden (member title notmuch-hello-hidden-sections))
895         (start (point)))
896     (if is-hidden
897         (widget-create 'push-button
898                        :notify `(lambda (widget &rest ignore)
899                                   (setq notmuch-hello-hidden-sections
900                                         (delete ,title notmuch-hello-hidden-sections))
901                                   (notmuch-hello-update))
902                        "show")
903       (widget-create 'push-button
904                      :notify `(lambda (widget &rest ignore)
905                                 (add-to-list 'notmuch-hello-hidden-sections
906                                              ,title)
907                                 (notmuch-hello-update))
908                      "hide"))
909     (widget-insert "\n")
910     (unless is-hidden
911       (let ((searches (apply 'notmuch-hello-query-counts query-list options)))
912         (when (or (not (plist-get options :hide-if-empty))
913                   searches)
914           (widget-insert "\n")
915           (notmuch-hello-insert-buttons searches)
916           (indent-rigidly start (point) notmuch-hello-indent))))))
917
918 (defun notmuch-hello-insert-tags-section (&optional title &rest options)
919   "Insert a section displaying all tags with message counts.
920
921 TITLE defaults to \"All tags\".
922 Allowed options are those accepted by `notmuch-hello-insert-searches' and the
923 following:
924
925 :hide-tags - List of tags that should be excluded."
926   (apply 'notmuch-hello-insert-searches
927          (or title "All tags")
928          (notmuch-hello-generate-tag-alist (plist-get options :hide-tags))
929          options))
930
931 (defun notmuch-hello-insert-inbox ()
932   "Show an entry for each saved search and inboxed messages for each tag."
933   (notmuch-hello-insert-searches "What's in your inbox"
934                                  (append
935                                   notmuch-saved-searches
936                                   (notmuch-hello-generate-tag-alist))
937                                  :filter "tag:inbox"))
938
939 (defun notmuch-hello-insert-alltags ()
940   "Insert a section displaying all tags and associated message counts."
941   (notmuch-hello-insert-tags-section
942    nil
943    :initially-hidden (not notmuch-show-all-tags-list)
944    :hide-tags notmuch-hello-hide-tags
945    :filter notmuch-hello-tag-list-make-query))
946
947 (defun notmuch-hello-insert-footer ()
948   "Insert the notmuch-hello footer."
949   (let ((start (point)))
950     (widget-insert "Hit `?' for context-sensitive help in any Notmuch screen.\n")
951     (widget-insert "Customize ")
952     (widget-create 'link
953                    :notify (lambda (&rest ignore)
954                              (customize-group 'notmuch))
955                    :button-prefix "" :button-suffix ""
956                    "Notmuch")
957     (widget-insert " or ")
958     (widget-create 'link
959                    :notify (lambda (&rest ignore)
960                              (customize-variable 'notmuch-hello-sections))
961                    :button-prefix "" :button-suffix ""
962                    "this page.")
963     (let ((fill-column (- (window-width) notmuch-hello-indent)))
964       (center-region start (point)))))
965
966 ;;;###autoload
967 (defun notmuch-hello (&optional no-display)
968   "Run notmuch and display saved searches, known tags, etc."
969   (interactive)
970   (notmuch-assert-cli-sane)
971   ;; This may cause a window configuration change, so if the
972   ;; auto-refresh hook is already installed, avoid recursive refresh.
973   (let ((notmuch-hello-auto-refresh nil))
974     (if no-display
975         (set-buffer "*notmuch-hello*")
976       (switch-to-buffer "*notmuch-hello*")))
977   ;; Install auto-refresh hook
978   (when notmuch-hello-auto-refresh
979     (add-hook 'window-configuration-change-hook
980               #'notmuch-hello-window-configuration-change))
981   (let ((target-line (line-number-at-pos))
982         (target-column (current-column))
983         (inhibit-read-only t))
984     ;; Delete all editable widget fields.  Editable widget fields are
985     ;; tracked in a buffer local variable `widget-field-list' (and
986     ;; others).  If we do `erase-buffer' without properly deleting the
987     ;; widgets, some widget-related functions are confused later.
988     (mapc 'widget-delete widget-field-list)
989     (erase-buffer)
990     (unless (eq major-mode 'notmuch-hello-mode)
991       (notmuch-hello-mode))
992     (let ((all (overlay-lists)))
993       ;; Delete all the overlays.
994       (mapc 'delete-overlay (car all))
995       (mapc 'delete-overlay (cdr all)))
996     (mapc
997      (lambda (section)
998        (let ((point-before (point)))
999          (if (functionp section)
1000              (funcall section)
1001            (apply (car section) (cdr section)))
1002          ;; don't insert a newline when the previous section didn't
1003          ;; show anything.
1004          (unless (eq (point) point-before)
1005            (widget-insert "\n"))))
1006      notmuch-hello-sections)
1007     (widget-setup)
1008     ;; Move point back to where it was before refresh. Use line and
1009     ;; column instead of point directly to be insensitive to additions
1010     ;; and removals of text within earlier lines.
1011     (goto-char (point-min))
1012     (forward-line (1- target-line))
1013     (move-to-column target-column))
1014   (run-hooks 'notmuch-hello-refresh-hook)
1015   (setq notmuch-hello-first-run nil))
1016
1017 (defun notmuch-folder ()
1018   "Deprecated function for invoking notmuch---calling `notmuch' is preferred now."
1019   (interactive)
1020   (notmuch-hello))
1021
1022 ;;
1023
1024 (provide 'notmuch-hello)
1025
1026 ;;; notmuch-hello.el ends here