]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
emacs: various comment improvements
[notmuch] / emacs / notmuch-hello.el
1 ;;; notmuch-hello.el --- welcome to notmuch, a frontend  -*- lexical-binding: t -*-
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                    unless (equal name (notmuch-saved-search-get elem :name))
436                    collect elem))
437     ;; Add the new one.
438     (customize-save-variable 'notmuch-saved-searches
439                              (add-to-list 'notmuch-saved-searches
440                                           (list :name name :query search) t))
441     (message "Saved '%s' as '%s'." search name)
442     (notmuch-hello-update)))
443
444 (defun notmuch-hello-delete-search-from-history (widget &rest _event)
445   (when (y-or-n-p "Are you sure you want to delete this search? ")
446     (let ((search (widget-value (widget-get widget :parent))))
447       (setq notmuch-search-history
448             (delete search notmuch-search-history)))
449     (notmuch-hello-update)))
450
451 ;;; Button utilities
452
453 ;; `notmuch-hello-query-counts', `notmuch-hello-nice-number' and
454 ;; `notmuch-hello-insert-buttons' are used outside this section.
455 ;; All other functions that are defined in this section are only
456 ;; used by these two functions.
457
458 (defun notmuch-hello-longest-label (searches-alist)
459   (or (cl-loop for elem in searches-alist
460                maximize (length (notmuch-saved-search-get elem :name)))
461       0))
462
463 (defun notmuch-hello-reflect-generate-row (ncols nrows row list)
464   (let ((len (length list)))
465     (cl-loop for col from 0 to (- ncols 1)
466              collect (let ((offset (+ (* nrows col) row)))
467                        (if (< offset len)
468                            (nth offset list)
469                          ;; Don't forget to insert an empty slot in the
470                          ;; output matrix if there is no corresponding
471                          ;; value in the input matrix.
472                          nil)))))
473
474 (defun notmuch-hello-reflect (list ncols)
475   "Reflect a `ncols' wide matrix represented by `list' along the
476 diagonal."
477   ;; Not very lispy...
478   (let ((nrows (ceiling (length list) ncols)))
479     (cl-loop for row from 0 to (- nrows 1)
480              append (notmuch-hello-reflect-generate-row ncols nrows row list))))
481
482 (defun notmuch-hello-widget-search (widget &rest _ignore)
483   (cl-case (widget-get widget :notmuch-search-type)
484    (tree
485     (notmuch-tree (widget-get widget :notmuch-search-terms)))
486    (unthreaded
487     (notmuch-unthreaded (widget-get widget :notmuch-search-terms)))
488    (t
489     (notmuch-search (widget-get widget :notmuch-search-terms)
490                     (widget-get widget :notmuch-search-oldest-first)))))
491
492 (defun notmuch-saved-search-count (search)
493   (car (process-lines notmuch-command "count" search)))
494
495 (defun notmuch-hello-tags-per-line (widest)
496   "Determine how many tags to show per line and how wide they
497 should be. Returns a cons cell `(tags-per-line width)'."
498   (let ((tags-per-line
499          (cond
500           ((integerp notmuch-column-control)
501            (max 1
502                 (/ (- (window-width) notmuch-hello-indent)
503                    ;; Count is 9 wide (8 digits plus space), 1 for the space
504                    ;; after the name.
505                    (+ 9 1 (max notmuch-column-control widest)))))
506           ((floatp notmuch-column-control)
507            (let* ((available-width (- (window-width) notmuch-hello-indent))
508                   (proposed-width (max (* available-width notmuch-column-control)
509                                        widest)))
510              (floor available-width proposed-width)))
511           (t
512            (max 1
513                 (/ (- (window-width) notmuch-hello-indent)
514                    ;; Count is 9 wide (8 digits plus space), 1 for the space
515                    ;; after the name.
516                    (+ 9 1 widest)))))))
517     (cons tags-per-line (/ (max 1
518                                 (- (window-width) notmuch-hello-indent
519                                    ;; Count is 9 wide (8 digits plus
520                                    ;; space), 1 for the space after the
521                                    ;; name.
522                                    (* tags-per-line (+ 9 1))))
523                            tags-per-line))))
524
525 (defun notmuch-hello-filtered-query (query filter)
526   "Constructs a query to search all messages matching QUERY and FILTER.
527
528 If FILTER is a string, it is directly used in the returned query.
529
530 If FILTER is a function, it is called with QUERY as a parameter and
531 the string it returns is used as the query. If nil is returned,
532 the entry is hidden.
533
534 Otherwise, FILTER is ignored."
535   (cond
536    ((functionp filter) (funcall filter query))
537    ((stringp filter)
538     (concat "(" query ") and (" filter ")"))
539    (t query)))
540
541 (defun notmuch-hello-query-counts (query-list &rest options)
542   "Compute list of counts of matched messages from QUERY-LIST.
543
544 QUERY-LIST must be a list of saved-searches. Ideally each of
545 these is a plist but other options are available for backwards
546 compatibility: see `notmuch-saved-searches' for details.
547
548 The result is a list of plists each of which includes the
549 properties :name NAME, :query QUERY and :count COUNT, together
550 with any properties in the original saved-search.
551
552 The values :show-empty-searches, :filter and :filter-count from
553 options will be handled as specified for
554 `notmuch-hello-insert-searches'."
555   (with-temp-buffer
556     (dolist (elem query-list nil)
557       (let ((count-query (or (notmuch-saved-search-get elem :count-query)
558                              (notmuch-saved-search-get elem :query))))
559         (insert
560          (replace-regexp-in-string
561           "\n" " "
562           (notmuch-hello-filtered-query count-query
563                                         (or (plist-get options :filter-count)
564                                             (plist-get options :filter))))
565          "\n")))
566     (unless (= (call-process-region (point-min) (point-max) notmuch-command
567                                     t t nil "count" "--batch") 0)
568       (notmuch-logged-error
569        "notmuch count --batch failed"
570        "Please check that the notmuch CLI is new enough to support `count
571 --batch'. In general we recommend running matching versions of
572 the CLI and emacs interface."))
573     (goto-char (point-min))
574     (cl-mapcan
575      (lambda (elem)
576        (let* ((elem-plist (notmuch-hello-saved-search-to-plist elem))
577               (search-query (plist-get elem-plist :query))
578               (filtered-query (notmuch-hello-filtered-query
579                                search-query (plist-get options :filter)))
580               (message-count (prog1 (read (current-buffer))
581                                (forward-line 1))))
582          (when (and filtered-query (or (plist-get options :show-empty-searches)
583                                        (> message-count 0)))
584            (setq elem-plist (plist-put elem-plist :query filtered-query))
585            (list (plist-put elem-plist :count message-count)))))
586      query-list)))
587
588 (defun notmuch-hello-nice-number (n)
589   (let (result)
590     (while (> n 0)
591       (push (% n 1000) result)
592       (setq n (/ n 1000)))
593     (setq result (or result '(0)))
594     (apply #'concat
595            (number-to-string (car result))
596            (mapcar (lambda (elem)
597                      (format "%s%03d" notmuch-hello-thousands-separator elem))
598                    (cdr result)))))
599
600 (defun notmuch-hello-insert-buttons (searches)
601   "Insert buttons for SEARCHES.
602
603 SEARCHES must be a list of plists each of which should contain at
604 least the properties :name NAME :query QUERY and :count COUNT,
605 where QUERY is the query to start when the button for the
606 corresponding entry is activated, and COUNT should be the number
607 of messages matching the query.  Such a plist can be computed
608 with `notmuch-hello-query-counts'."
609   (let* ((widest (notmuch-hello-longest-label searches))
610          (tags-and-width (notmuch-hello-tags-per-line widest))
611          (tags-per-line (car tags-and-width))
612          (column-width (cdr tags-and-width))
613          (column-indent 0)
614          (count 0)
615          (reordered-list (notmuch-hello-reflect searches tags-per-line))
616          ;; Hack the display of the buttons used.
617          (widget-push-button-prefix "")
618          (widget-push-button-suffix ""))
619     ;; dme: It feels as though there should be a better way to
620     ;; implement this loop than using an incrementing counter.
621     (mapc (lambda (elem)
622             ;; (not elem) indicates an empty slot in the matrix.
623             (when elem
624               (when (> column-indent 0)
625                 (widget-insert (make-string column-indent ? )))
626               (let* ((name (plist-get elem :name))
627                      (query (plist-get elem :query))
628                      (oldest-first (cl-case (plist-get elem :sort-order)
629                                      (newest-first nil)
630                                      (oldest-first t)
631                                      (otherwise notmuch-search-oldest-first)))
632                      (search-type (plist-get elem :search-type))
633                      (msg-count (plist-get elem :count)))
634                 (widget-insert (format "%8s "
635                                        (notmuch-hello-nice-number msg-count)))
636                 (widget-create 'push-button
637                                :notify #'notmuch-hello-widget-search
638                                :notmuch-search-terms query
639                                :notmuch-search-oldest-first oldest-first
640                                :notmuch-search-type search-type
641                                name)
642                 (setq column-indent
643                       (1+ (max 0 (- column-width (length name)))))))
644             (cl-incf count)
645             (when (eq (% count tags-per-line) 0)
646               (setq column-indent 0)
647               (widget-insert "\n")))
648           reordered-list)
649     ;; If the last line was not full (and hence did not include a
650     ;; carriage return), insert one now.
651     (unless (eq (% count tags-per-line) 0)
652       (widget-insert "\n"))))
653
654 ;;; Mode
655
656 (defun notmuch-hello-update ()
657   "Update the notmuch-hello buffer."
658   ;; Lazy - rebuild everything.
659   (interactive)
660   (notmuch-hello t))
661
662 (defun notmuch-hello-window-configuration-change ()
663   "Hook function to update the hello buffer when it is switched to."
664   (let ((hello-buf (get-buffer "*notmuch-hello*"))
665         (do-refresh nil))
666     ;; Consider all windows in the currently selected frame, since
667     ;; that's where the configuration change happened.  This also
668     ;; refreshes our snapshot of all windows, so we have to do this
669     ;; even if we know we won't refresh (e.g., hello-buf is null).
670     (dolist (window (window-list))
671       (let ((last-buf (window-parameter window 'notmuch-hello-last-buffer))
672             (cur-buf (window-buffer window)))
673         (unless (eq last-buf cur-buf)
674           ;; This window changed or is new.  Update recorded buffer
675           ;; for next time.
676           (set-window-parameter window 'notmuch-hello-last-buffer cur-buf)
677           (when (and (eq cur-buf hello-buf) last-buf)
678             ;; The user just switched to hello in this window (hello
679             ;; is currently visible, was not visible on the last
680             ;; configuration change, and this is not a new window)
681             (setq do-refresh t)))))
682     (when (and do-refresh notmuch-hello-auto-refresh)
683       ;; Refresh hello as soon as we get back to redisplay.  On Emacs
684       ;; 24, we can't do it right here because something in this
685       ;; hook's call stack overrides hello's point placement.
686       ;; FIXME And on Emacs releases that we still support?
687       (run-at-time nil nil #'notmuch-hello t))
688     (unless hello-buf
689       ;; Clean up hook
690       (remove-hook 'window-configuration-change-hook
691                    #'notmuch-hello-window-configuration-change))))
692
693 (defvar notmuch-hello-mode-map
694   ;; Inherit both widget-keymap and notmuch-common-keymap.  We have
695   ;; to use make-sparse-keymap to force this to be a new keymap (so
696   ;; that when we modify map it does not modify widget-keymap).
697   (let ((map (make-composed-keymap (list (make-sparse-keymap) widget-keymap))))
698     (set-keymap-parent map notmuch-common-keymap)
699     (define-key map (kbd "<C-tab>") 'widget-backward)
700     map)
701   "Keymap for \"notmuch hello\" buffers.")
702
703 (define-derived-mode notmuch-hello-mode fundamental-mode "notmuch-hello"
704   "Major mode for convenient notmuch navigation. This is your entry portal into notmuch.
705
706 Saved searches are \"bookmarks\" for arbitrary queries. Hit RET
707 or click on a saved search to view matching threads. Edit saved
708 searches with the `edit' button. Type `\\[notmuch-jump-search]'
709 in any Notmuch screen for quick access to saved searches that
710 have shortcut keys.
711
712 Type new searches in the search box and hit RET to view matching
713 threads. Hit RET in a recent search box to re-submit a previous
714 search. Edit it first if you like. Save a recent search to saved
715 searches with the `save' button.
716
717 Hit `\\[notmuch-search]' or `\\[notmuch-tree]' in any Notmuch
718 screen to search for messages and view matching threads or
719 messages, respectively. Recent searches are available in the
720 minibuffer history.
721
722 Expand the all tags view with the `show' button (and collapse
723 again with the `hide' button). Hit RET or click on a tag name to
724 view matching threads.
725
726 Hit `\\[notmuch-refresh-this-buffer]' to refresh the screen and
727 `\\[notmuch-bury-or-kill-this-buffer]' to quit.
728
729 The screen may be customized via `\\[customize]'.
730
731 Complete list of currently available key bindings:
732
733 \\{notmuch-hello-mode-map}"
734   (setq notmuch-buffer-refresh-function #'notmuch-hello-update))
735
736 ;;; Inserters
737
738 (defun notmuch-hello-generate-tag-alist (&optional hide-tags)
739   "Return an alist from tags to queries to display in the all-tags section."
740   (cl-mapcan (lambda (tag)
741                (and (not (member tag hide-tags))
742                     (list (cons tag
743                                 (concat "tag:"
744                                         (notmuch-escape-boolean-term tag))))))
745              (process-lines notmuch-command "search" "--output=tags" "*")))
746
747 (defun notmuch-hello-insert-header ()
748   "Insert the default notmuch-hello header."
749   (when notmuch-show-logo
750     (let ((image notmuch-hello-logo))
751       ;; The notmuch logo uses transparency. That can display poorly
752       ;; when inserting the image into an emacs buffer (black logo on
753       ;; a black background), so force the background colour of the
754       ;; image. We use a face to represent the colour so that
755       ;; `defface' can be used to declare the different possible
756       ;; colours, which depend on whether the frame has a light or
757       ;; dark background.
758       (setq image (cons 'image
759                         (append (cdr image)
760                                 (list :background
761                                       (face-background
762                                        'notmuch-hello-logo-background)))))
763       (insert-image image))
764     (widget-insert "  "))
765
766   (widget-insert "Welcome to ")
767   ;; Hack the display of the links used.
768   (let ((widget-link-prefix "")
769         (widget-link-suffix ""))
770     (widget-create 'link
771                    :notify (lambda (&rest _ignore)
772                              (browse-url notmuch-hello-url))
773                    :help-echo "Visit the notmuch website."
774                    "notmuch")
775     (widget-insert ". ")
776     (widget-insert "You have ")
777     (widget-create 'link
778                    :notify (lambda (&rest _ignore)
779                              (notmuch-hello-update))
780                    :help-echo "Refresh"
781                    (notmuch-hello-nice-number
782                     (string-to-number
783                      (car (process-lines notmuch-command "count")))))
784     (widget-insert " messages.\n")))
785
786 (defun notmuch-hello-insert-saved-searches ()
787   "Insert the saved-searches section."
788   (let ((searches (notmuch-hello-query-counts
789                    (if notmuch-saved-search-sort-function
790                        (funcall notmuch-saved-search-sort-function
791                                 notmuch-saved-searches)
792                      notmuch-saved-searches)
793                    :show-empty-searches notmuch-show-empty-saved-searches)))
794     (when searches
795       (widget-insert "Saved searches: ")
796       (widget-create 'push-button
797                      :notify (lambda (&rest _ignore)
798                                (customize-variable 'notmuch-saved-searches))
799                      "edit")
800       (widget-insert "\n\n")
801       (let ((start (point)))
802         (notmuch-hello-insert-buttons searches)
803         (indent-rigidly start (point) notmuch-hello-indent)))))
804
805 (defun notmuch-hello-insert-search ()
806   "Insert a search widget."
807   (widget-insert "Search: ")
808   (widget-create 'editable-field
809                  ;; Leave some space at the start and end of the
810                  ;; search boxes.
811                  :size (max 8 (- (window-width) notmuch-hello-indent
812                                  (length "Search: ")))
813                  :action #'notmuch-hello-search)
814   ;; Add an invisible dot to make `widget-end-of-line' ignore
815   ;; trailing spaces in the search widget field.  A dot is used
816   ;; instead of a space to make `show-trailing-whitespace'
817   ;; happy, i.e. avoid it marking the whole line as trailing
818   ;; spaces.
819   (widget-insert (propertize "." 'invisible t))
820   (widget-insert "\n"))
821
822 (defun notmuch-hello-insert-recent-searches ()
823   "Insert recent searches."
824   (when notmuch-search-history
825     (widget-insert "Recent searches: ")
826     (widget-create
827      'push-button
828      :notify (lambda (&rest _ignore)
829                (when (y-or-n-p "Are you sure you want to clear the searches? ")
830                  (setq notmuch-search-history nil)
831                  (notmuch-hello-update)))
832      "clear")
833     (widget-insert "\n\n")
834     (let ((width (notmuch-search-item-field-width)))
835       (dolist (search (seq-take notmuch-search-history
836                                 notmuch-hello-recent-searches-max))
837         (widget-create 'notmuch-search-item :value search :size width)))))
838
839 (defun notmuch-hello-insert-searches (title query-list &rest options)
840   "Insert a section with TITLE showing a list of buttons made from QUERY-LIST.
841
842 QUERY-LIST should ideally be a plist but for backwards
843 compatibility other forms are also accepted (see
844 `notmuch-saved-searches' for details).  The plist should
845 contain keys :name and :query; if :count-query is also present
846 then it specifies an alternate query to be used to generate the
847 count for the associated search.
848
849 Supports the following entries in OPTIONS as a plist:
850 :initially-hidden - if non-nil, section will be hidden on startup
851 :show-empty-searches - show buttons with no matching messages
852 :hide-if-empty - hide if no buttons would be shown
853    (only makes sense without :show-empty-searches)
854 :filter - This can be a function that takes the search query as its argument and
855    returns a filter to be used in conjunction with the query for that search or nil
856    to hide the element. This can also be a string that is used as a combined with
857    each query using \"and\".
858 :filter-count - Separate filter to generate the count displayed each search. Accepts
859    the same values as :filter. If :filter and :filter-count are specified, this
860    will be used instead of :filter, not in conjunction with it."
861   (widget-insert title ": ")
862   (when (and notmuch-hello-first-run (plist-get options :initially-hidden))
863     (add-to-list 'notmuch-hello-hidden-sections title))
864   (let ((is-hidden (member title notmuch-hello-hidden-sections))
865         (start (point)))
866     (if is-hidden
867         (widget-create 'push-button
868                        :notify `(lambda (widget &rest _ignore)
869                                   (setq notmuch-hello-hidden-sections
870                                         (delete ,title notmuch-hello-hidden-sections))
871                                   (notmuch-hello-update))
872                        "show")
873       (widget-create 'push-button
874                      :notify `(lambda (widget &rest _ignore)
875                                 (add-to-list 'notmuch-hello-hidden-sections
876                                              ,title)
877                                 (notmuch-hello-update))
878                      "hide"))
879     (widget-insert "\n")
880     (unless is-hidden
881       (let ((searches (apply 'notmuch-hello-query-counts query-list options)))
882         (when (or (not (plist-get options :hide-if-empty))
883                   searches)
884           (widget-insert "\n")
885           (notmuch-hello-insert-buttons searches)
886           (indent-rigidly start (point) notmuch-hello-indent))))))
887
888 (defun notmuch-hello-insert-tags-section (&optional title &rest options)
889   "Insert a section displaying all tags with message counts.
890
891 TITLE defaults to \"All tags\".
892 Allowed options are those accepted by `notmuch-hello-insert-searches' and the
893 following:
894
895 :hide-tags - List of tags that should be excluded."
896   (apply 'notmuch-hello-insert-searches
897          (or title "All tags")
898          (notmuch-hello-generate-tag-alist (plist-get options :hide-tags))
899          options))
900
901 (defun notmuch-hello-insert-inbox ()
902   "Show an entry for each saved search and inboxed messages for each tag."
903   (notmuch-hello-insert-searches "What's in your inbox"
904                                  (append
905                                   notmuch-saved-searches
906                                   (notmuch-hello-generate-tag-alist))
907                                  :filter "tag:inbox"))
908
909 (defun notmuch-hello-insert-alltags ()
910   "Insert a section displaying all tags and associated message counts."
911   (notmuch-hello-insert-tags-section
912    nil
913    :initially-hidden (not notmuch-show-all-tags-list)
914    :hide-tags notmuch-hello-hide-tags
915    :filter notmuch-hello-tag-list-make-query))
916
917 (defun notmuch-hello-insert-footer ()
918   "Insert the notmuch-hello footer."
919   (let ((start (point)))
920     (widget-insert "Hit `?' for context-sensitive help in any Notmuch screen.\n")
921     (widget-insert "Customize ")
922     (widget-create 'link
923                    :notify (lambda (&rest _ignore)
924                              (customize-group 'notmuch))
925                    :button-prefix "" :button-suffix ""
926                    "Notmuch")
927     (widget-insert " or ")
928     (widget-create 'link
929                    :notify (lambda (&rest _ignore)
930                              (customize-variable 'notmuch-hello-sections))
931                    :button-prefix "" :button-suffix ""
932                    "this page.")
933     (let ((fill-column (- (window-width) notmuch-hello-indent)))
934       (center-region start (point)))))
935
936 ;;; Hello!
937
938 ;;;###autoload
939 (defun notmuch-hello (&optional no-display)
940   "Run notmuch and display saved searches, known tags, etc."
941   (interactive)
942   (notmuch-assert-cli-sane)
943   ;; This may cause a window configuration change, so if the
944   ;; auto-refresh hook is already installed, avoid recursive refresh.
945   (let ((notmuch-hello-auto-refresh nil))
946     (if no-display
947         (set-buffer "*notmuch-hello*")
948       (pop-to-buffer-same-window "*notmuch-hello*")))
949   ;; Install auto-refresh hook
950   (when notmuch-hello-auto-refresh
951     (add-hook 'window-configuration-change-hook
952               #'notmuch-hello-window-configuration-change))
953   (let ((target-line (line-number-at-pos))
954         (target-column (current-column))
955         (inhibit-read-only t))
956     ;; Delete all editable widget fields.  Editable widget fields are
957     ;; tracked in a buffer local variable `widget-field-list' (and
958     ;; others).  If we do `erase-buffer' without properly deleting the
959     ;; widgets, some widget-related functions are confused later.
960     (mapc 'widget-delete widget-field-list)
961     (erase-buffer)
962     (unless (eq major-mode 'notmuch-hello-mode)
963       (notmuch-hello-mode))
964     (let ((all (overlay-lists)))
965       ;; Delete all the overlays.
966       (mapc 'delete-overlay (car all))
967       (mapc 'delete-overlay (cdr all)))
968     (mapc
969      (lambda (section)
970        (let ((point-before (point)))
971          (if (functionp section)
972              (funcall section)
973            (apply (car section) (cdr section)))
974          ;; don't insert a newline when the previous section didn't
975          ;; show anything.
976          (unless (eq (point) point-before)
977            (widget-insert "\n"))))
978      notmuch-hello-sections)
979     (widget-setup)
980     ;; Move point back to where it was before refresh. Use line and
981     ;; column instead of point directly to be insensitive to additions
982     ;; and removals of text within earlier lines.
983     (goto-char (point-min))
984     (forward-line (1- target-line))
985     (move-to-column target-column))
986   (run-hooks 'notmuch-hello-refresh-hook)
987   (setq notmuch-hello-first-run nil))
988
989 ;;; _
990
991 (provide 'notmuch-hello)
992
993 ;;; notmuch-hello.el ends here