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