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