]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
emacs: hello: add helper functions for saved-searches
[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   (unless (null search)
267     (setq search (notmuch-hello-trim search))
268     (let ((history-delete-duplicates t))
269       (add-to-history 'notmuch-search-history search)))
270   (notmuch-search search notmuch-search-oldest-first))
271
272 (defun notmuch-saved-search-get (saved-search field)
273   "Get FIELD from SAVED-SEARCH.
274
275 If SAVED-SEARCH is a plist, this is just `plist-get', but for
276 backwards compatibility, this also deals with the two other
277 possible formats for SAVED-SEARCH: cons cells (NAME . QUERY) and
278 lists (NAME QUERY COUNT-QUERY)."
279   (cond
280    ((keywordp (car saved-search))
281     (plist-get saved-search field))
282    ;; It is not a plist so it is an old-style entry.
283    ((consp (cdr saved-search)) ;; It is a list (NAME QUERY COUNT-QUERY)
284     (case field
285       (:name (first saved-search))
286       (:query (second saved-search))
287       (:count-query (third saved-search))
288       (t nil)))
289    (t  ;; It is a cons-cell (NAME . QUERY)
290     (case field
291       (:name (car saved-search))
292       (:query (cdr saved-search))
293       (t nil)))))
294
295 (defun notmuch-hello-saved-search-to-plist (saved-search)
296   "Return a copy of SAVED-SEARCH in plist form.
297
298 If saved search is a plist then just return a copy. In other
299 cases, for backwards compatability, convert to plist form and
300 return that."
301   (if (keywordp (car saved-search))
302       (copy-seq saved-search)
303     (let ((fields (list :name :query :count-query))
304           plist-search)
305       (dolist (field fields plist-search)
306         (let ((string (notmuch-saved-search-get saved-search field)))
307           (when string
308             (setq plist-search (append plist-search (list field string)))))))))
309
310 (defun notmuch-hello-add-saved-search (widget)
311   (interactive)
312   (let ((search (widget-value
313                  (symbol-value
314                   (widget-get widget :notmuch-saved-search-widget))))
315         (name (completing-read "Name for saved search: "
316                                notmuch-saved-searches)))
317     ;; If an existing saved search with this name exists, remove it.
318     (setq notmuch-saved-searches
319           (loop for elem in notmuch-saved-searches
320                 if (not (equal name
321                                (car elem)))
322                 collect elem))
323     ;; Add the new one.
324     (customize-save-variable 'notmuch-saved-searches
325                              (add-to-list 'notmuch-saved-searches
326                                           (cons name search) t))
327     (message "Saved '%s' as '%s'." search name)
328     (notmuch-hello-update)))
329
330 (defun notmuch-hello-delete-search-from-history (widget)
331   (interactive)
332   (let ((search (widget-value
333                  (symbol-value
334                   (widget-get widget :notmuch-saved-search-widget)))))
335     (setq notmuch-search-history (delete search
336                                          notmuch-search-history))
337     (notmuch-hello-update)))
338
339 (defun notmuch-hello-longest-label (searches-alist)
340   (or (loop for elem in searches-alist
341             maximize (length (car elem)))
342       0))
343
344 (defun notmuch-hello-reflect-generate-row (ncols nrows row list)
345   (let ((len (length list)))
346     (loop for col from 0 to (- ncols 1)
347           collect (let ((offset (+ (* nrows col) row)))
348                     (if (< offset len)
349                         (nth offset list)
350                       ;; Don't forget to insert an empty slot in the
351                       ;; output matrix if there is no corresponding
352                       ;; value in the input matrix.
353                       nil)))))
354
355 (defun notmuch-hello-reflect (list ncols)
356   "Reflect a `ncols' wide matrix represented by `list' along the
357 diagonal."
358   ;; Not very lispy...
359   (let ((nrows (ceiling (length list) ncols)))
360     (loop for row from 0 to (- nrows 1)
361           append (notmuch-hello-reflect-generate-row ncols nrows row list))))
362
363 (defun notmuch-hello-widget-search (widget &rest ignore)
364   (notmuch-search (widget-get widget
365                               :notmuch-search-terms)
366                   notmuch-search-oldest-first))
367
368 (defun notmuch-saved-search-count (search)
369   (car (process-lines notmuch-command "count" search)))
370
371 (defun notmuch-hello-tags-per-line (widest)
372   "Determine how many tags to show per line and how wide they
373 should be. Returns a cons cell `(tags-per-line width)'."
374   (let ((tags-per-line
375          (cond
376           ((integerp notmuch-column-control)
377            (max 1
378                 (/ (- (window-width) notmuch-hello-indent)
379                    ;; Count is 9 wide (8 digits plus space), 1 for the space
380                    ;; after the name.
381                    (+ 9 1 (max notmuch-column-control widest)))))
382
383           ((floatp notmuch-column-control)
384            (let* ((available-width (- (window-width) notmuch-hello-indent))
385                   (proposed-width (max (* available-width notmuch-column-control) widest)))
386              (floor available-width proposed-width)))
387
388           (t
389            (max 1
390                 (/ (- (window-width) notmuch-hello-indent)
391                    ;; Count is 9 wide (8 digits plus space), 1 for the space
392                    ;; after the name.
393                    (+ 9 1 widest)))))))
394
395     (cons tags-per-line (/ (max 1
396                                 (- (window-width) notmuch-hello-indent
397                                    ;; Count is 9 wide (8 digits plus
398                                    ;; space), 1 for the space after the
399                                    ;; name.
400                                    (* tags-per-line (+ 9 1))))
401                            tags-per-line))))
402
403 (defun notmuch-hello-filtered-query (query filter)
404   "Constructs a query to search all messages matching QUERY and FILTER.
405
406 If FILTER is a string, it is directly used in the returned query.
407
408 If FILTER is a function, it is called with QUERY as a parameter and
409 the string it returns is used as the query. If nil is returned,
410 the entry is hidden.
411
412 Otherwise, FILTER is ignored.
413 "
414   (cond
415    ((functionp filter) (funcall filter query))
416    ((stringp filter)
417     (concat "(" query ") and (" filter ")"))
418    (t query)))
419
420 (defun notmuch-hello-query-counts (query-alist &rest options)
421   "Compute list of counts of matched messages from QUERY-ALIST.
422
423 QUERY-ALIST must be a list containing elements of the form (NAME . QUERY)
424 or (NAME QUERY COUNT-QUERY). If the latter form is used,
425 COUNT-QUERY specifies an alternate query to be used to generate
426 the count for the associated query.
427
428 The result is the list of elements of the form (NAME QUERY COUNT).
429
430 The values :show-empty-searches, :filter and :filter-count from
431 options will be handled as specified for
432 `notmuch-hello-insert-searches'."
433   (with-temp-buffer
434     (dolist (elem query-alist nil)
435       (let ((count-query (if (consp (cdr elem))
436                              ;; do we have a different query for the message count?
437                              (third elem)
438                            (cdr elem))))
439         (insert
440          (replace-regexp-in-string
441           "\n" " "
442           (notmuch-hello-filtered-query count-query
443                                         (or (plist-get options :filter-count)
444                                             (plist-get options :filter))))
445           "\n")))
446
447     (unless (= (call-process-region (point-min) (point-max) notmuch-command
448                                     t t nil "count" "--batch") 0)
449       (notmuch-logged-error "notmuch count --batch failed"
450                             "Please check that the notmuch CLI is new enough to support `count
451 --batch'. In general we recommend running matching versions of
452 the CLI and emacs interface."))
453
454     (goto-char (point-min))
455
456     (notmuch-remove-if-not
457      #'identity
458      (mapcar
459       (lambda (elem)
460         (let ((name (car elem))
461               (search-query (if (consp (cdr elem))
462                                  ;; do we have a different query for the message count?
463                                  (second elem)
464                               (cdr elem)))
465               (message-count (prog1 (read (current-buffer))
466                                 (forward-line 1))))
467           (and (or (plist-get options :show-empty-searches) (> message-count 0))
468                (list name (notmuch-hello-filtered-query
469                            search-query (plist-get options :filter))
470                      message-count))))
471       query-alist))))
472
473 (defun notmuch-hello-insert-buttons (searches)
474   "Insert buttons for SEARCHES.
475
476 SEARCHES must be a list containing lists of the form (NAME QUERY COUNT), where
477 QUERY is the query to start when the button for the corresponding entry is
478 activated. COUNT should be the number of messages matching the query.
479 Such a list can be computed with `notmuch-hello-query-counts'."
480   (let* ((widest (notmuch-hello-longest-label searches))
481          (tags-and-width (notmuch-hello-tags-per-line widest))
482          (tags-per-line (car tags-and-width))
483          (column-width (cdr tags-and-width))
484          (column-indent 0)
485          (count 0)
486          (reordered-list (notmuch-hello-reflect searches tags-per-line))
487          ;; Hack the display of the buttons used.
488          (widget-push-button-prefix "")
489          (widget-push-button-suffix ""))
490     ;; dme: It feels as though there should be a better way to
491     ;; implement this loop than using an incrementing counter.
492     (mapc (lambda (elem)
493             ;; (not elem) indicates an empty slot in the matrix.
494             (when elem
495               (if (> column-indent 0)
496                   (widget-insert (make-string column-indent ? )))
497               (let* ((name (first elem))
498                      (query (second elem))
499                      (msg-count (third elem)))
500                 (widget-insert (format "%8s "
501                                        (notmuch-hello-nice-number msg-count)))
502                 (widget-create 'push-button
503                                :notify #'notmuch-hello-widget-search
504                                :notmuch-search-terms query
505                                name)
506                 (setq column-indent
507                       (1+ (max 0 (- column-width (length name)))))))
508             (setq count (1+ count))
509             (when (eq (% count tags-per-line) 0)
510               (setq column-indent 0)
511               (widget-insert "\n")))
512           reordered-list)
513
514     ;; If the last line was not full (and hence did not include a
515     ;; carriage return), insert one now.
516     (unless (eq (% count tags-per-line) 0)
517       (widget-insert "\n"))))
518
519 (defimage notmuch-hello-logo ((:type png :file "notmuch-logo.png")))
520
521 (defun notmuch-hello-update (&optional no-display)
522   "Update the current notmuch view."
523   ;; Lazy - rebuild everything.
524   (notmuch-hello no-display))
525
526 (defun notmuch-hello-window-configuration-change ()
527   "Hook function to update the hello buffer when it is switched to."
528   (let ((hello-buf (get-buffer "*notmuch-hello*"))
529         (do-refresh nil))
530     ;; Consider all windows in the currently selected frame, since
531     ;; that's where the configuration change happened.  This also
532     ;; refreshes our snapshot of all windows, so we have to do this
533     ;; even if we know we won't refresh (e.g., hello-buf is null).
534     (dolist (window (window-list))
535       (let ((last-buf (window-parameter window 'notmuch-hello-last-buffer))
536             (cur-buf (window-buffer window)))
537         (when (not (eq last-buf cur-buf))
538           ;; This window changed or is new.  Update recorded buffer
539           ;; for next time.
540           (set-window-parameter window 'notmuch-hello-last-buffer cur-buf)
541           (when (and (eq cur-buf hello-buf) last-buf)
542             ;; The user just switched to hello in this window (hello
543             ;; is currently visible, was not visible on the last
544             ;; configuration change, and this is not a new window)
545             (setq do-refresh t)))))
546     (when (and do-refresh notmuch-hello-auto-refresh)
547       ;; Refresh hello as soon as we get back to redisplay.  On Emacs
548       ;; 24, we can't do it right here because something in this
549       ;; hook's call stack overrides hello's point placement.
550       (run-at-time nil nil #'notmuch-hello t))
551     (when (null hello-buf)
552       ;; Clean up hook
553       (remove-hook 'window-configuration-change-hook
554                    #'notmuch-hello-window-configuration-change))))
555
556 ;; the following variable is defined as being defconst in notmuch-version.el
557 (defvar notmuch-emacs-version)
558
559 (defun notmuch-hello-versions ()
560   "Display the notmuch version(s)"
561   (interactive)
562   (let ((notmuch-cli-version (notmuch-version)))
563     (message "notmuch version %s"
564              (if (string= notmuch-emacs-version notmuch-cli-version)
565                  notmuch-cli-version
566                (concat notmuch-cli-version
567                        " (emacs mua version " notmuch-emacs-version ")")))))
568
569 (defvar notmuch-hello-mode-map
570   (let ((map (if (fboundp 'make-composed-keymap)
571                  ;; Inherit both widget-keymap and notmuch-common-keymap
572                  (make-composed-keymap widget-keymap)
573                ;; Before Emacs 24, keymaps didn't support multiple
574                ;; inheritance,, so just copy the widget keymap since
575                ;; it's unlikely to change.
576                (copy-keymap widget-keymap))))
577     (set-keymap-parent map notmuch-common-keymap)
578     (define-key map "v" 'notmuch-hello-versions)
579     (define-key map (kbd "<C-tab>") 'widget-backward)
580     map)
581   "Keymap for \"notmuch hello\" buffers.")
582 (fset 'notmuch-hello-mode-map notmuch-hello-mode-map)
583
584 (defun notmuch-hello-mode ()
585  "Major mode for convenient notmuch navigation. This is your entry portal into notmuch.
586
587 Complete list of currently available key bindings:
588
589 \\{notmuch-hello-mode-map}"
590  (interactive)
591  (kill-all-local-variables)
592  (setq notmuch-buffer-refresh-function #'notmuch-hello-update)
593  (use-local-map notmuch-hello-mode-map)
594  (setq major-mode 'notmuch-hello-mode
595         mode-name "notmuch-hello")
596  (run-mode-hooks 'notmuch-hello-mode-hook)
597  ;;(setq buffer-read-only t)
598 )
599
600 (defun notmuch-hello-generate-tag-alist (&optional hide-tags)
601   "Return an alist from tags to queries to display in the all-tags section."
602   (mapcar (lambda (tag)
603             (cons tag (concat "tag:" (notmuch-escape-boolean-term tag))))
604           (notmuch-remove-if-not
605            (lambda (tag)
606              (not (member tag hide-tags)))
607            (process-lines notmuch-command "search" "--output=tags" "*"))))
608
609 (defun notmuch-hello-insert-header ()
610   "Insert the default notmuch-hello header."
611   (when notmuch-show-logo
612     (let ((image notmuch-hello-logo))
613       ;; The notmuch logo uses transparency. That can display poorly
614       ;; when inserting the image into an emacs buffer (black logo on
615       ;; a black background), so force the background colour of the
616       ;; image. We use a face to represent the colour so that
617       ;; `defface' can be used to declare the different possible
618       ;; colours, which depend on whether the frame has a light or
619       ;; dark background.
620       (setq image (cons 'image
621                         (append (cdr image)
622                                 (list :background (face-background 'notmuch-hello-logo-background)))))
623       (insert-image image))
624     (widget-insert "  "))
625
626   (widget-insert "Welcome to ")
627   ;; Hack the display of the links used.
628   (let ((widget-link-prefix "")
629         (widget-link-suffix ""))
630     (widget-create 'link
631                    :notify (lambda (&rest ignore)
632                              (browse-url notmuch-hello-url))
633                    :help-echo "Visit the notmuch website."
634                    "notmuch")
635     (widget-insert ". ")
636     (widget-insert "You have ")
637     (widget-create 'link
638                    :notify (lambda (&rest ignore)
639                              (notmuch-hello-update))
640                    :help-echo "Refresh"
641                    (notmuch-hello-nice-number
642                     (string-to-number (car (process-lines notmuch-command "count")))))
643     (widget-insert " messages.\n")))
644
645
646 (defun notmuch-hello-insert-saved-searches ()
647   "Insert the saved-searches section."
648   (let ((searches (notmuch-hello-query-counts
649                    (if notmuch-saved-search-sort-function
650                        (funcall notmuch-saved-search-sort-function
651                                 notmuch-saved-searches)
652                      notmuch-saved-searches)
653                    :show-empty-searches notmuch-show-empty-saved-searches)))
654     (when searches
655       (widget-insert "Saved searches: ")
656       (widget-create 'push-button
657                      :notify (lambda (&rest ignore)
658                                (customize-variable 'notmuch-saved-searches))
659                      "edit")
660       (widget-insert "\n\n")
661       (let ((start (point)))
662         (notmuch-hello-insert-buttons searches)
663         (indent-rigidly start (point) notmuch-hello-indent)))))
664
665 (defun notmuch-hello-insert-search ()
666   "Insert a search widget."
667   (widget-insert "Search: ")
668   (widget-create 'editable-field
669                  ;; Leave some space at the start and end of the
670                  ;; search boxes.
671                  :size (max 8 (- (window-width) notmuch-hello-indent
672                                  (length "Search: ")))
673                  :action (lambda (widget &rest ignore)
674                            (notmuch-hello-search (widget-value widget))))
675   ;; Add an invisible dot to make `widget-end-of-line' ignore
676   ;; trailing spaces in the search widget field.  A dot is used
677   ;; instead of a space to make `show-trailing-whitespace'
678   ;; happy, i.e. avoid it marking the whole line as trailing
679   ;; spaces.
680   (widget-insert ".")
681   (put-text-property (1- (point)) (point) 'invisible t)
682   (widget-insert "\n"))
683
684 (defun notmuch-hello-insert-recent-searches ()
685   "Insert recent searches."
686   (when notmuch-search-history
687     (widget-insert "Recent searches: ")
688     (widget-create 'push-button
689                    :notify (lambda (&rest ignore)
690                              (when (y-or-n-p "Are you sure you want to clear the searches? ")
691                                (setq notmuch-search-history nil)
692                                (notmuch-hello-update)))
693                    "clear")
694     (widget-insert "\n\n")
695     (let ((start (point)))
696       (loop for i from 1 to notmuch-hello-recent-searches-max
697             for search in notmuch-search-history do
698             (let ((widget-symbol (intern (format "notmuch-hello-search-%d" i))))
699               (set widget-symbol
700                    (widget-create 'editable-field
701                                   ;; Don't let the search boxes be
702                                   ;; less than 8 characters wide.
703                                   :size (max 8
704                                              (- (window-width)
705                                                 ;; Leave some space
706                                                 ;; at the start and
707                                                 ;; end of the
708                                                 ;; boxes.
709                                                 (* 2 notmuch-hello-indent)
710                                                 ;; 1 for the space
711                                                 ;; before the
712                                                 ;; `[save]' button. 6
713                                                 ;; for the `[save]'
714                                                 ;; button.
715                                                 1 6
716                                                 ;; 1 for the space
717                                                 ;; before the `[del]'
718                                                 ;; button. 5 for the
719                                                 ;; `[del]' button.
720                                                 1 5))
721                                   :action (lambda (widget &rest ignore)
722                                             (notmuch-hello-search (widget-value widget)))
723                                   search))
724               (widget-insert " ")
725               (widget-create 'push-button
726                              :notify (lambda (widget &rest ignore)
727                                        (notmuch-hello-add-saved-search widget))
728                              :notmuch-saved-search-widget widget-symbol
729                              "save")
730               (widget-insert " ")
731               (widget-create 'push-button
732                              :notify (lambda (widget &rest ignore)
733                                        (when (y-or-n-p "Are you sure you want to delete this search? ")
734                                          (notmuch-hello-delete-search-from-history widget)))
735                              :notmuch-saved-search-widget widget-symbol
736                              "del"))
737             (widget-insert "\n"))
738       (indent-rigidly start (point) notmuch-hello-indent))
739     nil))
740
741 (defun notmuch-hello-insert-searches (title query-alist &rest options)
742   "Insert a section with TITLE showing a list of buttons made from QUERY-ALIST.
743
744 QUERY-ALIST must be a list containing elements of the form (NAME . QUERY)
745 or (NAME QUERY COUNT-QUERY). If the latter form is used,
746 COUNT-QUERY specifies an alternate query to be used to generate
747 the count for the associated item.
748
749 Supports the following entries in OPTIONS as a plist:
750 :initially-hidden - if non-nil, section will be hidden on startup
751 :show-empty-searches - show buttons with no matching messages
752 :hide-if-empty - hide if no buttons would be shown
753    (only makes sense without :show-empty-searches)
754 :filter - This can be a function that takes the search query as its argument and
755    returns a filter to be used in conjuction with the query for that search or nil
756    to hide the element. This can also be a string that is used as a combined with
757    each query using \"and\".
758 :filter-count - Separate filter to generate the count displayed each search. Accepts
759    the same values as :filter. If :filter and :filter-count are specified, this
760    will be used instead of :filter, not in conjunction with it."
761   (widget-insert title ": ")
762   (if (and notmuch-hello-first-run (plist-get options :initially-hidden))
763       (add-to-list 'notmuch-hello-hidden-sections title))
764   (let ((is-hidden (member title notmuch-hello-hidden-sections))
765         (start (point)))
766     (if is-hidden
767         (widget-create 'push-button
768                        :notify `(lambda (widget &rest ignore)
769                                   (setq notmuch-hello-hidden-sections
770                                         (delete ,title notmuch-hello-hidden-sections))
771                                   (notmuch-hello-update))
772                        "show")
773       (widget-create 'push-button
774                      :notify `(lambda (widget &rest ignore)
775                                 (add-to-list 'notmuch-hello-hidden-sections
776                                              ,title)
777                                 (notmuch-hello-update))
778                      "hide"))
779     (widget-insert "\n")
780     (when (not is-hidden)
781       (let ((searches (apply 'notmuch-hello-query-counts query-alist options)))
782         (when (or (not (plist-get options :hide-if-empty))
783                   searches)
784           (widget-insert "\n")
785           (notmuch-hello-insert-buttons searches)
786           (indent-rigidly start (point) notmuch-hello-indent))))))
787
788 (defun notmuch-hello-insert-tags-section (&optional title &rest options)
789   "Insert a section displaying all tags with message counts.
790
791 TITLE defaults to \"All tags\".
792 Allowed options are those accepted by `notmuch-hello-insert-searches' and the
793 following:
794
795 :hide-tags - List of tags that should be excluded."
796   (apply 'notmuch-hello-insert-searches
797          (or title "All tags")
798          (notmuch-hello-generate-tag-alist (plist-get options :hide-tags))
799          options))
800
801 (defun notmuch-hello-insert-inbox ()
802   "Show an entry for each saved search and inboxed messages for each tag"
803   (notmuch-hello-insert-searches "What's in your inbox"
804                                  (append
805                                   notmuch-saved-searches
806                                   (notmuch-hello-generate-tag-alist))
807                                  :filter "tag:inbox"))
808
809 (defun notmuch-hello-insert-alltags ()
810   "Insert a section displaying all tags and associated message counts"
811   (notmuch-hello-insert-tags-section
812    nil
813    :initially-hidden (not notmuch-show-all-tags-list)
814    :hide-tags notmuch-hello-hide-tags
815    :filter notmuch-hello-tag-list-make-query))
816
817 (defun notmuch-hello-insert-footer ()
818   "Insert the notmuch-hello footer."
819   (let ((start (point)))
820     (widget-insert "Type a search query and hit RET to view matching threads.\n")
821     (when notmuch-search-history
822       (widget-insert "Hit RET to re-submit a previous search. Edit it first if you like.\n")
823       (widget-insert "Save recent searches with the `save' button.\n"))
824     (when notmuch-saved-searches
825       (widget-insert "Edit saved searches with the `edit' button.\n"))
826     (widget-insert "Hit RET or click on a saved search or tag name to view matching threads.\n")
827     (widget-insert "`=' to refresh this screen. `s' to search messages. `q' to quit.\n")
828     (widget-create 'link
829                    :notify (lambda (&rest ignore)
830                              (customize-variable 'notmuch-hello-sections))
831                    :button-prefix "" :button-suffix ""
832                    "Customize")
833     (widget-insert " this page.")
834     (let ((fill-column (- (window-width) notmuch-hello-indent)))
835       (center-region start (point)))))
836
837 ;;;###autoload
838 (defun notmuch-hello (&optional no-display)
839   "Run notmuch and display saved searches, known tags, etc."
840   (interactive)
841
842   (notmuch-assert-cli-sane)
843   ;; This may cause a window configuration change, so if the
844   ;; auto-refresh hook is already installed, avoid recursive refresh.
845   (let ((notmuch-hello-auto-refresh nil))
846     (if no-display
847         (set-buffer "*notmuch-hello*")
848       (switch-to-buffer "*notmuch-hello*")))
849
850   ;; Install auto-refresh hook
851   (when notmuch-hello-auto-refresh
852     (add-hook 'window-configuration-change-hook
853               #'notmuch-hello-window-configuration-change))
854
855   (let ((target-line (line-number-at-pos))
856         (target-column (current-column))
857         (inhibit-read-only t))
858
859     ;; Delete all editable widget fields.  Editable widget fields are
860     ;; tracked in a buffer local variable `widget-field-list' (and
861     ;; others).  If we do `erase-buffer' without properly deleting the
862     ;; widgets, some widget-related functions are confused later.
863     (mapc 'widget-delete widget-field-list)
864
865     (erase-buffer)
866
867     (unless (eq major-mode 'notmuch-hello-mode)
868       (notmuch-hello-mode))
869
870     (let ((all (overlay-lists)))
871       ;; Delete all the overlays.
872       (mapc 'delete-overlay (car all))
873       (mapc 'delete-overlay (cdr all)))
874
875     (mapc
876      (lambda (section)
877        (let ((point-before (point)))
878          (if (functionp section)
879              (funcall section)
880            (apply (car section) (cdr section)))
881          ;; don't insert a newline when the previous section didn't
882          ;; show anything.
883          (unless (eq (point) point-before)
884            (widget-insert "\n"))))
885      notmuch-hello-sections)
886     (widget-setup)
887
888     ;; Move point back to where it was before refresh. Use line and
889     ;; column instead of point directly to be insensitive to additions
890     ;; and removals of text within earlier lines.
891     (goto-char (point-min))
892     (forward-line (1- target-line))
893     (move-to-column target-column))
894   (run-hooks 'notmuch-hello-refresh-hook)
895   (setq notmuch-hello-first-run nil))
896
897 (defun notmuch-folder ()
898   "Deprecated function for invoking notmuch---calling `notmuch' is preferred now."
899   (interactive)
900   (notmuch-hello))
901
902 ;;
903
904 (provide 'notmuch-hello)