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