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