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