]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
d17a30f91e0c830dc3e394c97ff48b666401936d
[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 (defcustom notmuch-hello-recent-searches-max 10
33   "The number of recent searches to display."
34   :type 'integer
35   :group 'notmuch-hello)
36
37 (defcustom notmuch-show-empty-saved-searches nil
38   "Should saved searches with no messages be listed?"
39   :type 'boolean
40   :group 'notmuch-hello)
41
42 (defun notmuch-sort-saved-searches (alist)
43   "Generate an alphabetically sorted saved searches alist."
44   (sort alist (lambda (a b) (string< (car a) (car b)))))
45
46 (defcustom notmuch-saved-search-sort-function nil
47   "Function used to sort the saved searches for the notmuch-hello view.
48
49 This variable controls how saved searches should be sorted. No
50 sorting (nil) displays the saved searches in the order they are
51 stored in `notmuch-saved-searches'. Sort alphabetically sorts the
52 saved searches in alphabetical order. Custom sort function should
53 be a function or a lambda expression that takes the saved
54 searches alist as a parameter, and returns a new saved searches
55 alist to be used."
56   :type '(choice (const :tag "No sorting" nil)
57                  (const :tag "Sort alphabetically" notmuch-sort-saved-searches)
58                  (function :tag "Custom sort function"
59                            :value notmuch-sort-saved-searches))
60   :group 'notmuch-hello)
61
62 (defvar notmuch-hello-indent 4
63   "How much to indent non-headers.")
64
65 (defcustom notmuch-show-logo t
66   "Should the notmuch logo be shown?"
67   :type 'boolean
68   :group 'notmuch-hello)
69
70 (defcustom notmuch-show-all-tags-list nil
71   "Should all tags be shown in the notmuch-hello view?"
72   :type 'boolean
73   :group 'notmuch-hello)
74
75 (defcustom notmuch-hello-tag-list-make-query nil
76   "Function or string to generate queries for the all tags list.
77
78 This variable controls which query results are shown for each tag
79 in the \"all tags\" list. If nil, it will use all messages with
80 that tag. If this is set to a string, it is used as a filter for
81 messages having that tag (equivalent to \"tag:TAG and (THIS-VARIABLE)\").
82 Finally this can be a function that will be called for each tag and
83 should return a filter for that tag, or nil to hide the tag."
84   :type '(choice (const :tag "All messages" nil)
85                  (const :tag "Unread messages" "tag:unread")
86                  (string :tag "Custom filter"
87                          :value "tag:unread")
88                  (function :tag "Custom filter function"))
89   :group 'notmuch-hello)
90
91 (defcustom notmuch-hello-hide-tags nil
92   "List of tags to be hidden in the \"all tags\"-section."
93   :type '(repeat string)
94   :group 'notmuch-hello)
95
96 (defface notmuch-hello-logo-background
97   '((((class color)
98       (background dark))
99      (:background "#5f5f5f"))
100     (((class color)
101       (background light))
102      (:background "white")))
103   "Background colour for the notmuch logo."
104   :group 'notmuch-hello
105   :group 'notmuch-faces)
106
107 (defcustom notmuch-column-control t
108   "Controls the number of columns for saved searches/tags in notmuch view.
109
110 This variable has three potential sets of values:
111
112 - t: automatically calculate the number of columns possible based
113   on the tags to be shown and the window width,
114 - an integer: a lower bound on the number of characters that will
115   be used to display each column,
116 - a float: a fraction of the window width that is the lower bound
117   on the number of characters that should be used for each
118   column.
119
120 So:
121 - if you would like two columns of tags, set this to 0.5.
122 - if you would like a single column of tags, set this to 1.0.
123 - if you would like tags to be 30 characters wide, set this to
124   30.
125 - if you don't want to worry about all of this nonsense, leave
126   this set to `t'."
127   :type '(choice
128           (const :tag "Automatically calculated" t)
129           (integer :tag "Number of characters")
130           (float :tag "Fraction of window"))
131   :group 'notmuch-hello)
132
133 (defcustom notmuch-hello-thousands-separator " "
134   "The string used as a thousands separator.
135
136 Typically \",\" in the US and UK and \".\" or \" \" in Europe.
137 The latter is recommended in the SI/ISO 31-0 standard and by the
138 International Bureau of Weights and Measures."
139   :type 'string
140   :group 'notmuch-hello)
141
142 (defcustom notmuch-hello-mode-hook nil
143   "Functions called after entering `notmuch-hello-mode'."
144   :type 'hook
145   :group 'notmuch-hello
146   :group 'notmuch-hooks)
147
148 (defcustom notmuch-hello-refresh-hook nil
149   "Functions called after updating a `notmuch-hello' buffer."
150   :type 'hook
151   :group 'notmuch-hello
152   :group 'notmuch-hooks)
153
154 (defvar notmuch-hello-url "http://notmuchmail.org"
155   "The `notmuch' web site.")
156
157 (defun notmuch-hello-nice-number (n)
158   (let (result)
159     (while (> n 0)
160       (push (% n 1000) result)
161       (setq n (/ n 1000)))
162     (setq result (or result '(0)))
163     (apply #'concat
164      (number-to-string (car result))
165      (mapcar (lambda (elem)
166               (format "%s%03d" notmuch-hello-thousands-separator elem))
167              (cdr result)))))
168
169 (defun notmuch-hello-trim (search)
170   "Trim whitespace."
171   (if (string-match "^[[:space:]]*\\(.*[^[:space:]]\\)[[:space:]]*$" search)
172       (match-string 1 search)
173     search))
174
175 (defun notmuch-hello-search (&optional search)
176   (interactive)
177   (unless (null search)
178     (setq search (notmuch-hello-trim search))
179     (let ((history-delete-duplicates t))
180       (add-to-history 'notmuch-search-history search)))
181   (notmuch-search search notmuch-search-oldest-first nil nil
182                   #'notmuch-hello-search-continuation))
183
184 (defun notmuch-hello-add-saved-search (widget)
185   (interactive)
186   (let ((search (widget-value
187                  (symbol-value
188                   (widget-get widget :notmuch-saved-search-widget))))
189         (name (completing-read "Name for saved search: "
190                                notmuch-saved-searches)))
191     ;; If an existing saved search with this name exists, remove it.
192     (setq notmuch-saved-searches
193           (loop for elem in notmuch-saved-searches
194                 if (not (equal name
195                                (car elem)))
196                 collect elem))
197     ;; Add the new one.
198     (customize-save-variable 'notmuch-saved-searches
199                              (add-to-list 'notmuch-saved-searches
200                                           (cons name search) t))
201     (message "Saved '%s' as '%s'." search name)
202     (notmuch-hello-update)))
203
204 (defun notmuch-hello-longest-label (tag-alist)
205   (or (loop for elem in tag-alist
206             maximize (length (car elem)))
207       0))
208
209 (defun notmuch-hello-reflect-generate-row (ncols nrows row list)
210   (let ((len (length list)))
211     (loop for col from 0 to (- ncols 1)
212           collect (let ((offset (+ (* nrows col) row)))
213                     (if (< offset len)
214                         (nth offset list)
215                       ;; Don't forget to insert an empty slot in the
216                       ;; output matrix if there is no corresponding
217                       ;; value in the input matrix.
218                       nil)))))
219
220 (defun notmuch-hello-reflect (list ncols)
221   "Reflect a `ncols' wide matrix represented by `list' along the
222 diagonal."
223   ;; Not very lispy...
224   (let ((nrows (ceiling (length list) ncols)))
225     (loop for row from 0 to (- nrows 1)
226           append (notmuch-hello-reflect-generate-row ncols nrows row list))))
227
228 (defun notmuch-hello-widget-search (widget &rest ignore)
229   (notmuch-search (widget-get widget
230                               :notmuch-search-terms)
231                   notmuch-search-oldest-first
232                   nil nil #'notmuch-hello-search-continuation))
233
234 (defun notmuch-saved-search-count (search)
235   (car (process-lines notmuch-command "count" search)))
236
237 (defun notmuch-hello-tags-per-line (widest)
238   "Determine how many tags to show per line and how wide they
239 should be. Returns a cons cell `(tags-per-line width)'."
240   (let ((tags-per-line
241          (cond
242           ((integerp notmuch-column-control)
243            (max 1
244                 (/ (- (window-width) notmuch-hello-indent)
245                    ;; Count is 9 wide (8 digits plus space), 1 for the space
246                    ;; after the name.
247                    (+ 9 1 (max notmuch-column-control widest)))))
248
249           ((floatp notmuch-column-control)
250            (let* ((available-width (- (window-width) notmuch-hello-indent))
251                   (proposed-width (max (* available-width notmuch-column-control) widest)))
252              (floor available-width proposed-width)))
253
254           (t
255            (max 1
256                 (/ (- (window-width) notmuch-hello-indent)
257                    ;; Count is 9 wide (8 digits plus space), 1 for the space
258                    ;; after the name.
259                    (+ 9 1 widest)))))))
260
261     (cons tags-per-line (/ (max 1
262                                 (- (window-width) notmuch-hello-indent
263                                    ;; Count is 9 wide (8 digits plus
264                                    ;; space), 1 for the space after the
265                                    ;; name.
266                                    (* tags-per-line (+ 9 1))))
267                            tags-per-line))))
268
269 (defun notmuch-hello-insert-tags (tag-alist widest target)
270   (let* ((tags-and-width (notmuch-hello-tags-per-line widest))
271          (tags-per-line (car tags-and-width))
272          (widest (cdr tags-and-width))
273          (count 0)
274          (reordered-list (notmuch-hello-reflect tag-alist tags-per-line))
275          ;; Hack the display of the buttons used.
276          (widget-push-button-prefix "")
277          (widget-push-button-suffix "")
278          (found-target-pos nil))
279     ;; dme: It feels as though there should be a better way to
280     ;; implement this loop than using an incrementing counter.
281     (mapc (lambda (elem)
282             ;; (not elem) indicates an empty slot in the matrix.
283             (when elem
284               (let* ((name (car elem))
285                      (query (cdr elem))
286                      (formatted-name (format "%s " name)))
287                 (widget-insert (format "%8s "
288                                        (notmuch-hello-nice-number
289                                         (string-to-number (notmuch-saved-search-count query)))))
290                 (if (string= formatted-name target)
291                     (setq found-target-pos (point-marker)))
292                 (widget-create 'push-button
293                                :notify #'notmuch-hello-widget-search
294                                :notmuch-search-terms query
295                                formatted-name)
296                 (unless (eq (% count tags-per-line) (1- tags-per-line))
297                   ;; If this is not the last tag on the line, insert
298                   ;; enough space to consume the rest of the column.
299                   ;; Because the button for the name is `(1+ (length
300                   ;; name))' long (due to the trailing space) we can
301                   ;; just insert `(- widest (length name))' spaces - the
302                   ;; column separator is included in the button if
303                   ;; `(equal widest (length name)'.
304                   (widget-insert (make-string (max 1
305                                                    (- widest (length name)))
306                                               ? )))))
307             (setq count (1+ count))
308             (if (eq (% count tags-per-line) 0)
309                 (widget-insert "\n")))
310           reordered-list)
311
312     ;; If the last line was not full (and hence did not include a
313     ;; carriage return), insert one now.
314     (unless (eq (% count tags-per-line) 0)
315       (widget-insert "\n"))
316     found-target-pos))
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-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   (unless 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           (default-pos))
462       (let* ((saved-alist
463               ;; Filter out empty saved searches if required.
464               (if notmuch-show-empty-saved-searches
465                   notmuch-saved-searches
466                 (loop for elem in notmuch-saved-searches
467                       if (> (string-to-number (notmuch-saved-search-count (cdr elem))) 0)
468                       collect elem)))
469              (saved-widest (notmuch-hello-longest-label saved-alist))
470              (alltags-alist (if notmuch-show-all-tags-list (notmuch-hello-generate-tag-alist)))
471              (alltags-widest (notmuch-hello-longest-label alltags-alist))
472              (widest (max saved-widest alltags-widest)))
473
474         (when saved-alist
475           ;; Sort saved searches if required.
476           (when notmuch-saved-search-sort-function
477             (setq saved-alist
478                   (funcall notmuch-saved-search-sort-function saved-alist)))
479           (widget-insert "\nSaved searches: ")
480           (widget-create 'push-button
481                          :notify (lambda (&rest ignore)
482                                    (customize-variable 'notmuch-saved-searches))
483                          "edit")
484           (widget-insert "\n\n")
485           (setq final-target-pos (point-marker))
486           (let ((start (point)))
487             (setq found-target-pos (notmuch-hello-insert-tags saved-alist widest target))
488             (if found-target-pos
489                 (setq final-target-pos found-target-pos))
490             (indent-rigidly start (point) notmuch-hello-indent)))
491
492         (widget-insert "\nSearch: ")
493         (setq default-pos (point-marker))
494         (widget-create 'editable-field
495                        ;; Leave some space at the start and end of the
496                        ;; search boxes.
497                        :size (max 8 (- (window-width) notmuch-hello-indent
498                                        (length "Search: ")))
499                        :action (lambda (widget &rest ignore)
500                                  (notmuch-hello-search (widget-value widget))))
501         ;; Add an invisible dot to make `widget-end-of-line' ignore
502         ;; trailing spaces in the search widget field.  A dot is used
503         ;; instead of a space to make `show-trailing-whitespace'
504         ;; happy, i.e. avoid it marking the whole line as trailing
505         ;; spaces.
506         (widget-insert ".")
507         (put-text-property (1- (point)) (point) 'invisible t)
508         (widget-insert "\n")
509
510         (when notmuch-search-history
511           (widget-insert "\nRecent searches: ")
512           (widget-create 'push-button
513                          :notify (lambda (&rest ignore)
514                                    (setq notmuch-search-history nil)
515                                    (notmuch-hello-update))
516                          "clear")
517           (widget-insert "\n\n")
518           (let ((start (point)))
519             (loop for i from 1 to notmuch-hello-recent-searches-max
520                   for search in notmuch-search-history do
521                     (let ((widget-symbol (intern (format "notmuch-hello-search-%d" i))))
522                       (set widget-symbol
523                            (widget-create 'editable-field
524                                           ;; Don't let the search boxes be
525                                           ;; less than 8 characters wide.
526                                           :size (max 8
527                                                      (- (window-width)
528                                                         ;; Leave some space
529                                                         ;; at the start and
530                                                         ;; end of the
531                                                         ;; boxes.
532                                                         (* 2 notmuch-hello-indent)
533                                                         ;; 1 for the space
534                                                         ;; before the
535                                                         ;; `[save]' button. 6
536                                                         ;; for the `[save]'
537                                                         ;; button.
538                                                         1 6))
539                                           :action (lambda (widget &rest ignore)
540                                                     (notmuch-hello-search (widget-value widget)))
541                                           search))
542                       (widget-insert " ")
543                       (widget-create 'push-button
544                                      :notify (lambda (widget &rest ignore)
545                                                (notmuch-hello-add-saved-search widget))
546                                      :notmuch-saved-search-widget widget-symbol
547                                      "save"))
548                     (widget-insert "\n"))
549             (indent-rigidly start (point) notmuch-hello-indent)))
550
551         (when alltags-alist
552           (widget-insert "\nAll tags: ")
553           (widget-create 'push-button
554                          :notify (lambda (widget &rest ignore)
555                                    (setq notmuch-show-all-tags-list nil)
556                                    (notmuch-hello-update))
557                          "hide")
558           (widget-insert "\n\n")
559           (let ((start (point)))
560             (setq found-target-pos (notmuch-hello-insert-tags alltags-alist widest target))
561             (unless final-target-pos
562               (setq final-target-pos found-target-pos))
563             (indent-rigidly start (point) notmuch-hello-indent)))
564
565         (widget-insert "\n")
566
567         (unless notmuch-show-all-tags-list
568           (widget-create 'push-button
569                          :notify (lambda (widget &rest ignore)
570                                    (setq notmuch-show-all-tags-list t)
571                                    (notmuch-hello-update))
572                          "Show all tags")))
573
574       (let ((start (point)))
575         (widget-insert "\n\n")
576         (widget-insert "Type a search query and hit RET to view matching threads.\n")
577         (when notmuch-search-history
578           (widget-insert "Hit RET to re-submit a previous search. Edit it first if you like.\n")
579           (widget-insert "Save recent searches with the `save' button.\n"))
580         (when notmuch-saved-searches
581           (widget-insert "Edit saved searches with the `edit' button.\n"))
582         (widget-insert "Hit RET or click on a saved search or tag name to view matching threads.\n")
583         (widget-insert "`=' to refresh this screen. `s' to search messages. `q' to quit.\n")
584         (let ((fill-column (- (window-width) notmuch-hello-indent)))
585           (center-region start (point))))
586
587       (widget-setup)
588
589       (when final-target-pos
590         (goto-char final-target-pos)
591         (unless (widget-at)
592           (widget-forward 1)))
593
594       (unless (widget-at)
595         (goto-char default-pos))))
596
597   (run-hooks 'notmuch-hello-refresh-hook))
598
599 (defun notmuch-folder ()
600   "Deprecated function for invoking notmuch---calling `notmuch' is preferred now."
601   (interactive)
602   (notmuch-hello))
603
604 ;;
605
606 (provide 'notmuch-hello)