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