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