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