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