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