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