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