]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
emacs: do not call `notmuch-hello-mode' on update
[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" (query &optional oldest-first target-thread target-line continuation))
30 (declare-function notmuch-poll "notmuch" ())
31
32 (defvar notmuch-hello-search-bar-marker nil
33   "The position of the search bar within the notmuch-hello buffer.")
34
35 (defcustom notmuch-recent-searches-max 10
36   "The number of recent searches to store and display."
37   :type 'integer
38   :group 'notmuch)
39
40 (defcustom notmuch-show-empty-saved-searches nil
41   "Should saved searches with no messages be listed?"
42   :type 'boolean
43   :group 'notmuch)
44
45 (defun notmuch-sort-saved-searches (alist)
46   "Generate an alphabetically sorted saved searches alist."
47   (sort alist (lambda (a b) (string< (car a) (car b)))))
48
49 (defcustom notmuch-saved-search-sort-function nil
50   "Function used to sort the saved searches for the notmuch-hello view.
51
52 This variable controls how saved searches should be sorted. No
53 sorting (nil) displays the saved searches in the order they are
54 stored in `notmuch-saved-searches'. Sort alphabetically sorts the
55 saved searches in alphabetical order. Custom sort function should
56 be a function or a lambda expression that takes the saved
57 searches alist as a parameter, and returns a new saved searches
58 alist to be used."
59   :type '(choice (const :tag "No sorting" nil)
60                  (const :tag "Sort alphabetically" notmuch-sort-saved-searches)
61                  (function :tag "Custom sort function"
62                            :value notmuch-sort-saved-searches))
63   :group 'notmuch)
64
65 (defvar notmuch-hello-indent 4
66   "How much to indent non-headers.")
67
68 (defcustom notmuch-show-logo t
69   "Should the notmuch logo be shown?"
70   :type 'boolean
71   :group 'notmuch)
72
73 (defcustom notmuch-show-all-tags-list nil
74   "Should all tags be shown in the notmuch-hello view?"
75   :type 'boolean
76   :group 'notmuch)
77
78 (defcustom notmuch-hello-tag-list-make-query nil
79   "Function or string to generate queries for the all tags list.
80
81 This variable controls which query results are shown for each tag
82 in the \"all tags\" list. If nil, it will use all messages with
83 that tag. If this is set to a string, it is used as a filter for
84 messages having that tag (equivalent to \"tag:TAG and (THIS-VARIABLE)\").
85 Finally this can be a function that will be called for each tag and
86 should return a filter for that tag, or nil to hide the tag."
87   :type '(choice (const :tag "All messages" nil)
88                  (const :tag "Unread messages" "tag:unread")
89                  (const :tag "Custom filter" string)
90                  (const :tag "Custom filter function" function))
91   :group 'notmuch)
92
93 (defcustom notmuch-hello-hide-tags nil
94   "List of tags to be hidden in the \"all tags\"-section."
95   :type '(repeat string)
96   :group 'notmuch)
97
98 (defface notmuch-hello-logo-background
99   '((((class color)
100       (background dark))
101      (:background "#5f5f5f"))
102     (((class color)
103       (background light))
104      (:background "white")))
105   "Background colour for the notmuch logo."
106   :group 'notmuch)
107
108 (defcustom notmuch-column-control t
109   "Controls the number of columns for saved searches/tags in notmuch view.
110
111 This variable has three potential sets of values:
112
113 - t: automatically calculate the number of columns possible based
114   on the tags to be shown and the window width,
115 - an integer: a lower bound on the number of characters that will
116   be used to display each column,
117 - a float: a fraction of the window width that is the lower bound
118   on the number of characters that should be used for each
119   column.
120
121 So:
122 - if you would like two columns of tags, set this to 0.5.
123 - if you would like a single column of tags, set this to 1.0.
124 - if you would like tags to be 30 characters wide, set this to
125   30.
126 - if you don't want to worry about all of this nonsense, leave
127   this set to `t'."
128   :group 'notmuch
129   :type '(choice
130           (const :tag "Automatically calculated" t)
131           (integer :tag "Number of characters")
132           (float :tag "Fraction of window")))
133
134 (defcustom notmuch-decimal-separator ","
135   "The string used as a decimal separator.
136
137 Typically \",\" in the US and UK and \".\" in Europe."
138   :group 'notmuch
139   :type 'string)
140
141 (defcustom notmuch-hello-mode-hook nil
142   "Functions called after entering `notmuch-hello-mode'."
143   :group 'notmuch
144   :type 'hook)
145
146 (defvar notmuch-hello-url "http://notmuchmail.org"
147   "The `notmuch' web site.")
148
149 (defvar notmuch-hello-recent-searches nil)
150
151 (defun notmuch-hello-remember-search (search)
152   (if (not (member search notmuch-hello-recent-searches))
153       (push search notmuch-hello-recent-searches))
154   (if (> (length notmuch-hello-recent-searches)
155          notmuch-recent-searches-max)
156       (setq notmuch-hello-recent-searches (butlast notmuch-hello-recent-searches))))
157
158 (defun notmuch-hello-nice-number (n)
159   (let (result)
160     (while (> n 0)
161       (push (% n 1000) result)
162       (setq n (/ n 1000)))
163     (setq result (or result '(0)))
164     (apply #'concat
165      (number-to-string (car result))
166      (mapcar (lambda (elem)
167               (format "%s%03d" notmuch-decimal-separator elem))
168              (cdr result)))))
169
170 (defun notmuch-hello-trim (search)
171   "Trim whitespace."
172   (if (string-match "^[[:space:]]*\\(.*[^[:space:]]\\)[[:space:]]*$" search)
173       (match-string 1 search)
174     search))
175
176 (defun notmuch-hello-search (search)
177   (let ((search (notmuch-hello-trim search)))
178     (notmuch-hello-remember-search search)
179     (notmuch-search search notmuch-search-oldest-first nil nil #'notmuch-hello-search-continuation)))
180
181 (defun notmuch-hello-add-saved-search (widget)
182   (interactive)
183   (let ((search (widget-value
184                  (symbol-value
185                   (widget-get widget :notmuch-saved-search-widget))))
186         (name (completing-read "Name for saved search: "
187                                notmuch-saved-searches)))
188     ;; If an existing saved search with this name exists, remove it.
189     (setq notmuch-saved-searches
190           (loop for elem in notmuch-saved-searches
191                 if (not (equal name
192                                (car elem)))
193                 collect elem))
194     ;; Add the new one.
195     (customize-save-variable 'notmuch-saved-searches
196                              (add-to-list 'notmuch-saved-searches
197                                           (cons name search) t))
198     (message "Saved '%s' as '%s'." search name)
199     (notmuch-hello-update)))
200
201 (defun notmuch-hello-longest-label (tag-alist)
202   (or (loop for elem in tag-alist
203             maximize (length (car elem)))
204       0))
205
206 (defun notmuch-hello-reflect-generate-row (ncols nrows row list)
207   (let ((len (length list)))
208     (loop for col from 0 to (- ncols 1)
209           collect (let ((offset (+ (* nrows col) row)))
210                     (if (< offset len)
211                         (nth offset list)
212                       ;; Don't forget to insert an empty slot in the
213                       ;; output matrix if there is no corresponding
214                       ;; value in the input matrix.
215                       nil)))))
216
217 (defun notmuch-hello-reflect (list ncols)
218   "Reflect a `ncols' wide matrix represented by `list' along the
219 diagonal."
220   ;; Not very lispy...
221   (let ((nrows (ceiling (length list) ncols)))
222     (loop for row from 0 to (- nrows 1)
223           append (notmuch-hello-reflect-generate-row ncols nrows row list))))
224
225 (defun notmuch-hello-widget-search (widget &rest ignore)
226   (notmuch-search (widget-get widget
227                               :notmuch-search-terms)
228                   notmuch-search-oldest-first
229                   nil nil #'notmuch-hello-search-continuation))
230
231 (defun notmuch-saved-search-count (search)
232   (car (process-lines notmuch-command "count" search)))
233
234 (defun notmuch-hello-tags-per-line (widest)
235   "Determine how many tags to show per line and how wide they
236 should be. Returns a cons cell `(tags-per-line width)'."
237   (let ((tags-per-line
238          (cond
239           ((integerp notmuch-column-control)
240            (max 1
241                 (/ (- (window-width) notmuch-hello-indent)
242                    ;; Count is 9 wide (8 digits plus space), 1 for the space
243                    ;; after the name.
244                    (+ 9 1 (max notmuch-column-control widest)))))
245
246           ((floatp notmuch-column-control)
247            (let* ((available-width (- (window-width) notmuch-hello-indent))
248                   (proposed-width (max (* available-width notmuch-column-control) widest)))
249              (floor available-width proposed-width)))
250
251           (t
252            (max 1
253                 (/ (- (window-width) notmuch-hello-indent)
254                    ;; Count is 9 wide (8 digits plus space), 1 for the space
255                    ;; after the name.
256                    (+ 9 1 widest)))))))
257
258     (cons tags-per-line (/ (max 1
259                                 (- (window-width) notmuch-hello-indent
260                                    ;; Count is 9 wide (8 digits plus
261                                    ;; space), 1 for the space after the
262                                    ;; name.
263                                    (* tags-per-line (+ 9 1))))
264                            tags-per-line))))
265
266 (defun notmuch-hello-insert-tags (tag-alist widest target)
267   (let* ((tags-and-width (notmuch-hello-tags-per-line widest))
268          (tags-per-line (car tags-and-width))
269          (widest (cdr tags-and-width))
270          (count 0)
271          (reordered-list (notmuch-hello-reflect tag-alist tags-per-line))
272          ;; Hack the display of the buttons used.
273          (widget-push-button-prefix "")
274          (widget-push-button-suffix "")
275          (found-target-pos nil))
276     ;; dme: It feels as though there should be a better way to
277     ;; implement this loop than using an incrementing counter.
278     (mapc (lambda (elem)
279             ;; (not elem) indicates an empty slot in the matrix.
280             (when elem
281               (let* ((name (car elem))
282                      (query (cdr elem))
283                      (formatted-name (format "%s " name)))
284                 (widget-insert (format "%8s "
285                                        (notmuch-hello-nice-number
286                                         (string-to-number (notmuch-saved-search-count query)))))
287                 (if (string= formatted-name target)
288                     (setq found-target-pos (point-marker)))
289                 (widget-create 'push-button
290                                :notify #'notmuch-hello-widget-search
291                                :notmuch-search-terms query
292                                formatted-name)
293                 ;; Insert enough space to consume the rest of the
294                 ;; column.  Because the button for the name is `(1+
295                 ;; (length name))' long (due to the trailing space) we
296                 ;; can just insert `(- widest (length name))' spaces -
297                 ;; the column separator is included in the button if
298                 ;; `(equal widest (length name)'.
299                 (widget-insert (make-string (max 1
300                                                  (- widest (length name)))
301                                             ? ))))
302             (setq count (1+ count))
303             (if (eq (% count tags-per-line) 0)
304                 (widget-insert "\n")))
305           reordered-list)
306
307     ;; If the last line was not full (and hence did not include a
308     ;; carriage return), insert one now.
309     (if (not (eq (% count tags-per-line) 0))
310         (widget-insert "\n"))
311     found-target-pos))
312
313 (defun notmuch-hello-goto-search ()
314   "Put point inside the `search' widget."
315   (interactive)
316   (goto-char notmuch-hello-search-bar-marker))
317
318 (defimage notmuch-hello-logo ((:type png :file "notmuch-logo.png")))
319
320 (defun notmuch-hello-search-continuation()
321   (notmuch-hello-update t))
322
323 (defun notmuch-hello-update (&optional no-display)
324   "Update the current notmuch view."
325   ;; Lazy - rebuild everything.
326   (interactive)
327   (notmuch-hello no-display))
328
329 (defun notmuch-hello-poll-and-update ()
330   "Invoke `notmuch-poll' to import mail, then refresh the current view."
331   (interactive)
332   (notmuch-poll)
333   (notmuch-hello-update))
334
335
336 (defvar notmuch-hello-mode-map
337   (let ((map (make-sparse-keymap)))
338     (set-keymap-parent map widget-keymap)
339     (define-key map "v" '(lambda () "Display the notmuch version" (interactive)
340                            (message "notmuch version %s" (notmuch-version))))
341     (define-key map "?" 'notmuch-help)
342     (define-key map "q" 'notmuch-kill-this-buffer)
343     (define-key map "=" 'notmuch-hello-update)
344     (define-key map "G" 'notmuch-hello-poll-and-update)
345     (define-key map (kbd "<C-tab>") 'widget-backward)
346     (define-key map "m" 'notmuch-mua-new-mail)
347     (define-key map "s" 'notmuch-hello-goto-search)
348     map)
349   "Keymap for \"notmuch hello\" buffers.")
350 (fset 'notmuch-hello-mode-map notmuch-hello-mode-map)
351
352 (defun notmuch-hello-mode ()
353  "Major mode for convenient notmuch navigation. This is your entry portal into notmuch.
354
355 Complete list of currently available key bindings:
356
357 \\{notmuch-hello-mode-map}"
358  (interactive)
359  (kill-all-local-variables)
360  (use-local-map notmuch-hello-mode-map)
361  (setq major-mode 'notmuch-hello-mode
362        mode-name "notmuch-hello")
363  (run-mode-hooks 'notmuch-hello-mode-hook)
364  ;;(setq buffer-read-only t)
365 )
366
367 (defun notmuch-hello-generate-tag-alist ()
368   "Return an alist from tags to queries to display in the all-tags section."
369   (notmuch-remove-if-not
370    #'cdr
371    (mapcar (lambda (tag)
372              (cons tag
373                    (cond
374                     ((functionp notmuch-hello-tag-list-make-query)
375                      (concat "tag:" tag " and ("
376                              (funcall notmuch-hello-tag-list-make-query tag) ")"))
377                     ((stringp notmuch-hello-tag-list-make-query)
378                      (concat "tag:" tag " and ("
379                              notmuch-hello-tag-list-make-query ")"))
380                     (t (concat "tag:" tag)))))
381            (notmuch-remove-if-not
382             (lambda (tag)
383               (not (member tag notmuch-hello-hide-tags)))
384             (process-lines notmuch-command "search-tags")))))
385
386 ;;;###autoload
387 (defun notmuch-hello (&optional no-display)
388   "Run notmuch and display saved searches, known tags, etc."
389   (interactive)
390
391   ; Jump through a hoop to get this value from the deprecated variable
392   ; name (`notmuch-folders') or from the default value.
393   (if (not notmuch-saved-searches)
394     (setq notmuch-saved-searches (notmuch-saved-searches)))
395
396   (if no-display
397       (set-buffer "*notmuch-hello*")
398     (switch-to-buffer "*notmuch-hello*"))
399
400   (let ((target (if (widget-at)
401                    (widget-value (widget-at))
402                  (condition-case nil
403                      (progn
404                        (widget-forward 1)
405                        (widget-value (widget-at)))
406                    (error nil))))
407         (inhibit-read-only t))
408
409     ;; Delete all editable widget fields.  Editable widget fields are
410     ;; tracked in a buffer local variable `widget-field-list' (and
411     ;; others).  If we do `erase-buffer' without properly deleting the
412     ;; widgets, some widget-related functions are confused later.
413     (mapc 'widget-delete widget-field-list)
414
415     (erase-buffer)
416
417     (unless (eq major-mode 'notmuch-hello-mode)
418       (notmuch-hello-mode))
419
420     (let ((all (overlay-lists)))
421       ;; Delete all the overlays.
422       (mapc 'delete-overlay (car all))
423       (mapc 'delete-overlay (cdr all)))
424
425     (when notmuch-show-logo
426       (let ((image notmuch-hello-logo))
427         ;; The notmuch logo uses transparency. That can display poorly
428         ;; when inserting the image into an emacs buffer (black logo on
429         ;; a black background), so force the background colour of the
430         ;; image. We use a face to represent the colour so that
431         ;; `defface' can be used to declare the different possible
432         ;; colours, which depend on whether the frame has a light or
433         ;; dark background.
434         (setq image (cons 'image
435                           (append (cdr image)
436                                   (list :background (face-background 'notmuch-hello-logo-background)))))
437         (insert-image image))
438       (widget-insert "  "))
439
440     (widget-insert "Welcome to ")
441     ;; Hack the display of the links used.
442     (let ((widget-link-prefix "")
443           (widget-link-suffix ""))
444       (widget-create 'link
445                      :notify (lambda (&rest ignore)
446                                (browse-url notmuch-hello-url))
447                      :help-echo "Visit the notmuch website."
448                      "notmuch")
449       (widget-insert ". ")
450       (widget-insert "You have ")
451       (widget-create 'link
452                      :notify (lambda (&rest ignore)
453                                (notmuch-hello-update))
454                      :help-echo "Refresh"
455                      (notmuch-hello-nice-number
456                       (string-to-number (car (process-lines notmuch-command "count")))))
457       (widget-insert " messages.\n"))
458
459     (let ((found-target-pos nil)
460           (final-target-pos nil))
461       (let* ((saved-alist
462               ;; Filter out empty saved searches if required.
463               (if notmuch-show-empty-saved-searches
464                   notmuch-saved-searches
465                 (loop for elem in notmuch-saved-searches
466                       if (> (string-to-number (notmuch-saved-search-count (cdr elem))) 0)
467                       collect elem)))
468              (saved-widest (notmuch-hello-longest-label saved-alist))
469              (alltags-alist (if notmuch-show-all-tags-list (notmuch-hello-generate-tag-alist)))
470              (alltags-widest (notmuch-hello-longest-label alltags-alist))
471              (widest (max saved-widest alltags-widest)))
472
473         (when saved-alist
474           ;; Sort saved searches if required.
475           (when notmuch-saved-search-sort-function
476             (setq saved-alist
477                   (funcall notmuch-saved-search-sort-function saved-alist)))
478           (widget-insert "\nSaved searches: ")
479           (widget-create 'push-button
480                          :notify (lambda (&rest ignore)
481                                    (customize-variable 'notmuch-saved-searches))
482                          "edit")
483           (widget-insert "\n\n")
484           (setq final-target-pos (point-marker))
485           (let ((start (point)))
486             (setq found-target-pos (notmuch-hello-insert-tags saved-alist widest target))
487             (if found-target-pos
488                 (setq final-target-pos found-target-pos))
489             (indent-rigidly start (point) notmuch-hello-indent)))
490
491         (widget-insert "\nSearch: ")
492         (setq notmuch-hello-search-bar-marker (point-marker))
493         (widget-create 'editable-field
494                        ;; Leave some space at the start and end of the
495                        ;; search boxes.
496                        :size (max 8 (- (window-width) notmuch-hello-indent
497                                        (length "Search: ")))
498                        :action (lambda (widget &rest ignore)
499                                  (notmuch-hello-search (widget-value widget))))
500         ;; add an invisible space to make `widget-end-of-line' ignore
501         ;; trailine spaces in the search widget field
502         (widget-insert " ")
503         (put-text-property (1- (point)) (point) 'invisible t)
504         (widget-insert "\n")
505
506         (when notmuch-hello-recent-searches
507           (widget-insert "\nRecent searches: ")
508           (widget-create 'push-button
509                          :notify (lambda (&rest ignore)
510                                    (setq notmuch-hello-recent-searches nil)
511                                    (notmuch-hello-update))
512                          "clear")
513           (widget-insert "\n\n")
514           (let ((start (point))
515                 (nth 0))
516             (mapc '(lambda (search)
517                      (let ((widget-symbol (intern (format "notmuch-hello-search-%d" nth))))
518                        (set widget-symbol
519                             (widget-create 'editable-field
520                                        ;; Don't let the search boxes be
521                                        ;; less than 8 characters wide.
522                                        :size (max 8
523                                                   (- (window-width)
524                                                      ;; Leave some space
525                                                      ;; at the start and
526                                                      ;; end of the
527                                                      ;; boxes.
528                                                      (* 2 notmuch-hello-indent)
529                                                      ;; 1 for the space
530                                                      ;; before the
531                                                      ;; `[save]' button. 6
532                                                      ;; for the `[save]'
533                                                      ;; button.
534                                                      1 6))
535                                        :action (lambda (widget &rest ignore)
536                                                  (notmuch-hello-search (widget-value widget)))
537                                        search))
538                        (widget-insert " ")
539                        (widget-create 'push-button
540                                       :notify (lambda (widget &rest ignore)
541                                                 (notmuch-hello-add-saved-search widget))
542                                       :notmuch-saved-search-widget widget-symbol
543                                       "save"))
544                      (widget-insert "\n")
545                      (setq nth (1+ nth)))
546                   notmuch-hello-recent-searches)
547             (indent-rigidly start (point) notmuch-hello-indent)))
548
549         (when alltags-alist
550           (widget-insert "\nAll tags: ")
551           (widget-create 'push-button
552                          :notify (lambda (widget &rest ignore)
553                                    (setq notmuch-show-all-tags-list nil)
554                                    (notmuch-hello-update))
555                          "hide")
556           (widget-insert "\n\n")
557           (let ((start (point)))
558             (setq found-target-pos (notmuch-hello-insert-tags alltags-alist widest target))
559             (if (not final-target-pos)
560                 (setq final-target-pos found-target-pos))
561             (indent-rigidly start (point) notmuch-hello-indent)))
562
563         (widget-insert "\n")
564
565         (if (not notmuch-show-all-tags-list)
566             (widget-create 'push-button
567                            :notify (lambda (widget &rest ignore)
568                                      (setq notmuch-show-all-tags-list t)
569                                      (notmuch-hello-update))
570                            "Show all tags")))
571
572       (let ((start (point)))
573         (widget-insert "\n\n")
574         (widget-insert "Type a search query and hit RET to view matching threads.\n")
575         (when notmuch-hello-recent-searches
576           (widget-insert "Hit RET to re-submit a previous search. Edit it first if you like.\n")
577           (widget-insert "Save recent searches with the `save' button.\n"))
578         (when notmuch-saved-searches
579           (widget-insert "Edit saved searches with the `edit' button.\n"))
580         (widget-insert "Hit RET or click on a saved search or tag name to view matching threads.\n")
581         (widget-insert "`=' refreshes this screen. `s' jumps to the search box. `q' to quit.\n")
582         (let ((fill-column (- (window-width) notmuch-hello-indent)))
583           (center-region start (point))))
584
585       (widget-setup)
586
587       (when final-target-pos
588         (goto-char final-target-pos)
589         (unless (widget-at)
590           (widget-forward 1)))
591
592       (unless (widget-at)
593         (notmuch-hello-goto-search)))))
594
595 (defun notmuch-folder ()
596   "Deprecated function for invoking notmuch---calling `notmuch' is preferred now."
597   (interactive)
598   (notmuch-hello))
599
600 ;;
601
602 (provide 'notmuch-hello)