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