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