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