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