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