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