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