]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
6970bc343ad49582be7558746f5588711bfcea12
[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 (search)
176   (unless (null search)
177     (setq search (notmuch-hello-trim search))
178     (let ((history-delete-duplicates t))
179       (add-to-history 'notmuch-search-history search)))
180   (notmuch-search search notmuch-search-oldest-first nil nil
181                   #'notmuch-hello-search-continuation))
182
183 (defun notmuch-hello-add-saved-search (widget)
184   (interactive)
185   (let ((search (widget-value
186                  (symbol-value
187                   (widget-get widget :notmuch-saved-search-widget))))
188         (name (completing-read "Name for saved search: "
189                                notmuch-saved-searches)))
190     ;; If an existing saved search with this name exists, remove it.
191     (setq notmuch-saved-searches
192           (loop for elem in notmuch-saved-searches
193                 if (not (equal name
194                                (car elem)))
195                 collect elem))
196     ;; Add the new one.
197     (customize-save-variable 'notmuch-saved-searches
198                              (add-to-list 'notmuch-saved-searches
199                                           (cons name search) t))
200     (message "Saved '%s' as '%s'." search name)
201     (notmuch-hello-update)))
202
203 (defun notmuch-hello-longest-label (tag-alist)
204   (or (loop for elem in tag-alist
205             maximize (length (car elem)))
206       0))
207
208 (defun notmuch-hello-reflect-generate-row (ncols nrows row list)
209   (let ((len (length list)))
210     (loop for col from 0 to (- ncols 1)
211           collect (let ((offset (+ (* nrows col) row)))
212                     (if (< offset len)
213                         (nth offset list)
214                       ;; Don't forget to insert an empty slot in the
215                       ;; output matrix if there is no corresponding
216                       ;; value in the input matrix.
217                       nil)))))
218
219 (defun notmuch-hello-reflect (list ncols)
220   "Reflect a `ncols' wide matrix represented by `list' along the
221 diagonal."
222   ;; Not very lispy...
223   (let ((nrows (ceiling (length list) ncols)))
224     (loop for row from 0 to (- nrows 1)
225           append (notmuch-hello-reflect-generate-row ncols nrows row list))))
226
227 (defun notmuch-hello-widget-search (widget &rest ignore)
228   (notmuch-search (widget-get widget
229                               :notmuch-search-terms)
230                   notmuch-search-oldest-first
231                   nil nil #'notmuch-hello-search-continuation))
232
233 (defun notmuch-saved-search-count (search)
234   (car (process-lines notmuch-command "count" search)))
235
236 (defun notmuch-hello-tags-per-line (widest)
237   "Determine how many tags to show per line and how wide they
238 should be. Returns a cons cell `(tags-per-line width)'."
239   (let ((tags-per-line
240          (cond
241           ((integerp notmuch-column-control)
242            (max 1
243                 (/ (- (window-width) notmuch-hello-indent)
244                    ;; Count is 9 wide (8 digits plus space), 1 for the space
245                    ;; after the name.
246                    (+ 9 1 (max notmuch-column-control widest)))))
247
248           ((floatp notmuch-column-control)
249            (let* ((available-width (- (window-width) notmuch-hello-indent))
250                   (proposed-width (max (* available-width notmuch-column-control) widest)))
251              (floor available-width proposed-width)))
252
253           (t
254            (max 1
255                 (/ (- (window-width) notmuch-hello-indent)
256                    ;; Count is 9 wide (8 digits plus space), 1 for the space
257                    ;; after the name.
258                    (+ 9 1 widest)))))))
259
260     (cons tags-per-line (/ (max 1
261                                 (- (window-width) notmuch-hello-indent
262                                    ;; Count is 9 wide (8 digits plus
263                                    ;; space), 1 for the space after the
264                                    ;; name.
265                                    (* tags-per-line (+ 9 1))))
266                            tags-per-line))))
267
268 (defun notmuch-hello-insert-tags (tag-alist widest target)
269   (let* ((tags-and-width (notmuch-hello-tags-per-line widest))
270          (tags-per-line (car tags-and-width))
271          (widest (cdr tags-and-width))
272          (count 0)
273          (reordered-list (notmuch-hello-reflect tag-alist tags-per-line))
274          ;; Hack the display of the buttons used.
275          (widget-push-button-prefix "")
276          (widget-push-button-suffix "")
277          (found-target-pos nil))
278     ;; dme: It feels as though there should be a better way to
279     ;; implement this loop than using an incrementing counter.
280     (mapc (lambda (elem)
281             ;; (not elem) indicates an empty slot in the matrix.
282             (when elem
283               (let* ((name (car elem))
284                      (query (cdr elem))
285                      (formatted-name (format "%s " name)))
286                 (widget-insert (format "%8s "
287                                        (notmuch-hello-nice-number
288                                         (string-to-number (notmuch-saved-search-count query)))))
289                 (if (string= formatted-name target)
290                     (setq found-target-pos (point-marker)))
291                 (widget-create 'push-button
292                                :notify #'notmuch-hello-widget-search
293                                :notmuch-search-terms query
294                                formatted-name)
295                 (unless (eq (% count tags-per-line) (1- tags-per-line))
296                   ;; If this is not the last tag on the line, insert
297                   ;; enough space to consume the rest of the column.
298                   ;; Because the button for the name is `(1+ (length
299                   ;; name))' long (due to the trailing space) we can
300                   ;; just insert `(- widest (length name))' spaces - the
301                   ;; column separator is included in the button if
302                   ;; `(equal widest (length name)'.
303                   (widget-insert (make-string (max 1
304                                                    (- widest (length name)))
305                                               ? )))))
306             (setq count (1+ count))
307             (if (eq (% count tags-per-line) 0)
308                 (widget-insert "\n")))
309           reordered-list)
310
311     ;; If the last line was not full (and hence did not include a
312     ;; carriage return), insert one now.
313     (unless (eq (% count tags-per-line) 0)
314       (widget-insert "\n"))
315     found-target-pos))
316
317 (defimage notmuch-hello-logo ((:type png :file "notmuch-logo.png")))
318
319 (defun notmuch-hello-search-continuation()
320   (notmuch-hello-update t))
321
322 (defun notmuch-hello-update (&optional no-display)
323   "Update the current notmuch view."
324   ;; Lazy - rebuild everything.
325   (interactive)
326   (notmuch-hello no-display))
327
328 (defun notmuch-hello-poll-and-update ()
329   "Invoke `notmuch-poll' to import mail, then refresh the current view."
330   (interactive)
331   (notmuch-poll)
332   (notmuch-hello-update))
333
334
335 (defvar notmuch-hello-mode-map
336   (let ((map (make-sparse-keymap)))
337     (set-keymap-parent map widget-keymap)
338     (define-key map "v" (lambda () "Display the notmuch version" (interactive)
339                           (message "notmuch version %s" (notmuch-version))))
340     (define-key map "?" 'notmuch-help)
341     (define-key map "q" 'notmuch-kill-this-buffer)
342     (define-key map "=" 'notmuch-hello-update)
343     (define-key map "G" 'notmuch-hello-poll-and-update)
344     (define-key map (kbd "<C-tab>") 'widget-backward)
345     (define-key map "m" 'notmuch-mua-new-mail)
346     (define-key map "s" 'notmuch-search)
347     map)
348   "Keymap for \"notmuch hello\" buffers.")
349 (fset 'notmuch-hello-mode-map notmuch-hello-mode-map)
350
351 (defun notmuch-hello-mode ()
352  "Major mode for convenient notmuch navigation. This is your entry portal into notmuch.
353
354 Complete list of currently available key bindings:
355
356 \\{notmuch-hello-mode-map}"
357  (interactive)
358  (kill-all-local-variables)
359  (use-local-map notmuch-hello-mode-map)
360  (setq major-mode 'notmuch-hello-mode
361        mode-name "notmuch-hello")
362  (run-mode-hooks 'notmuch-hello-mode-hook)
363  ;;(setq buffer-read-only t)
364 )
365
366 (defun notmuch-hello-generate-tag-alist ()
367   "Return an alist from tags to queries to display in the all-tags section."
368   (notmuch-remove-if-not
369    #'cdr
370    (mapcar (lambda (tag)
371              (cons tag
372                    (cond
373                     ((functionp notmuch-hello-tag-list-make-query)
374                      (concat "tag:" tag " and ("
375                              (funcall notmuch-hello-tag-list-make-query tag) ")"))
376                     ((stringp notmuch-hello-tag-list-make-query)
377                      (concat "tag:" tag " and ("
378                              notmuch-hello-tag-list-make-query ")"))
379                     (t (concat "tag:" tag)))))
380            (notmuch-remove-if-not
381             (lambda (tag)
382               (not (member tag notmuch-hello-hide-tags)))
383             (process-lines notmuch-command "search-tags")))))
384
385 ;;;###autoload
386 (defun notmuch-hello (&optional no-display)
387   "Run notmuch and display saved searches, known tags, etc."
388   (interactive)
389
390   ;; Jump through a hoop to get this value from the deprecated variable
391   ;; name (`notmuch-folders') or from the default value.
392   (unless notmuch-saved-searches
393     (setq notmuch-saved-searches (notmuch-saved-searches)))
394
395   (if no-display
396       (set-buffer "*notmuch-hello*")
397     (switch-to-buffer "*notmuch-hello*"))
398
399   (let ((target (if (widget-at)
400                    (widget-value (widget-at))
401                  (condition-case nil
402                      (progn
403                        (widget-forward 1)
404                        (widget-value (widget-at)))
405                    (error nil))))
406         (inhibit-read-only t))
407
408     ;; Delete all editable widget fields.  Editable widget fields are
409     ;; tracked in a buffer local variable `widget-field-list' (and
410     ;; others).  If we do `erase-buffer' without properly deleting the
411     ;; widgets, some widget-related functions are confused later.
412     (mapc 'widget-delete widget-field-list)
413
414     (erase-buffer)
415
416     (unless (eq major-mode 'notmuch-hello-mode)
417       (notmuch-hello-mode))
418
419     (let ((all (overlay-lists)))
420       ;; Delete all the overlays.
421       (mapc 'delete-overlay (car all))
422       (mapc 'delete-overlay (cdr all)))
423
424     (when notmuch-show-logo
425       (let ((image notmuch-hello-logo))
426         ;; The notmuch logo uses transparency. That can display poorly
427         ;; when inserting the image into an emacs buffer (black logo on
428         ;; a black background), so force the background colour of the
429         ;; image. We use a face to represent the colour so that
430         ;; `defface' can be used to declare the different possible
431         ;; colours, which depend on whether the frame has a light or
432         ;; dark background.
433         (setq image (cons 'image
434                           (append (cdr image)
435                                   (list :background (face-background 'notmuch-hello-logo-background)))))
436         (insert-image image))
437       (widget-insert "  "))
438
439     (widget-insert "Welcome to ")
440     ;; Hack the display of the links used.
441     (let ((widget-link-prefix "")
442           (widget-link-suffix ""))
443       (widget-create 'link
444                      :notify (lambda (&rest ignore)
445                                (browse-url notmuch-hello-url))
446                      :help-echo "Visit the notmuch website."
447                      "notmuch")
448       (widget-insert ". ")
449       (widget-insert "You have ")
450       (widget-create 'link
451                      :notify (lambda (&rest ignore)
452                                (notmuch-hello-update))
453                      :help-echo "Refresh"
454                      (notmuch-hello-nice-number
455                       (string-to-number (car (process-lines notmuch-command "count")))))
456       (widget-insert " messages.\n"))
457
458     (let ((found-target-pos nil)
459           (final-target-pos nil)
460           (default-pos))
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 default-pos (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 dot to make `widget-end-of-line' ignore
501         ;; trailing spaces in the search widget field.  A dot is used
502         ;; instead of a space to make `show-trailing-whitespace'
503         ;; happy, i.e. avoid it marking the whole line as trailing
504         ;; spaces.
505         (widget-insert ".")
506         (put-text-property (1- (point)) (point) 'invisible t)
507         (widget-insert "\n")
508
509         (when notmuch-search-history
510           (widget-insert "\nRecent searches: ")
511           (widget-create 'push-button
512                          :notify (lambda (&rest ignore)
513                                    (setq notmuch-search-history nil)
514                                    (notmuch-hello-update))
515                          "clear")
516           (widget-insert "\n\n")
517           (let ((start (point)))
518             (loop for i from 1 to notmuch-hello-recent-searches-max
519                   for search in notmuch-search-history do
520                     (let ((widget-symbol (intern (format "notmuch-hello-search-%d" i))))
521                       (set widget-symbol
522                            (widget-create 'editable-field
523                                           ;; Don't let the search boxes be
524                                           ;; less than 8 characters wide.
525                                           :size (max 8
526                                                      (- (window-width)
527                                                         ;; Leave some space
528                                                         ;; at the start and
529                                                         ;; end of the
530                                                         ;; boxes.
531                                                         (* 2 notmuch-hello-indent)
532                                                         ;; 1 for the space
533                                                         ;; before the
534                                                         ;; `[save]' button. 6
535                                                         ;; for the `[save]'
536                                                         ;; button.
537                                                         1 6))
538                                           :action (lambda (widget &rest ignore)
539                                                     (notmuch-hello-search (widget-value widget)))
540                                           search))
541                       (widget-insert " ")
542                       (widget-create 'push-button
543                                      :notify (lambda (widget &rest ignore)
544                                                (notmuch-hello-add-saved-search widget))
545                                      :notmuch-saved-search-widget widget-symbol
546                                      "save"))
547                     (widget-insert "\n"))
548             (indent-rigidly start (point) notmuch-hello-indent)))
549
550         (when alltags-alist
551           (widget-insert "\nAll tags: ")
552           (widget-create 'push-button
553                          :notify (lambda (widget &rest ignore)
554                                    (setq notmuch-show-all-tags-list nil)
555                                    (notmuch-hello-update))
556                          "hide")
557           (widget-insert "\n\n")
558           (let ((start (point)))
559             (setq found-target-pos (notmuch-hello-insert-tags alltags-alist widest target))
560             (unless final-target-pos
561               (setq final-target-pos found-target-pos))
562             (indent-rigidly start (point) notmuch-hello-indent)))
563
564         (widget-insert "\n")
565
566         (unless notmuch-show-all-tags-list
567           (widget-create 'push-button
568                          :notify (lambda (widget &rest ignore)
569                                    (setq notmuch-show-all-tags-list t)
570                                    (notmuch-hello-update))
571                          "Show all tags")))
572
573       (let ((start (point)))
574         (widget-insert "\n\n")
575         (widget-insert "Type a search query and hit RET to view matching threads.\n")
576         (when notmuch-search-history
577           (widget-insert "Hit RET to re-submit a previous search. Edit it first if you like.\n")
578           (widget-insert "Save recent searches with the `save' button.\n"))
579         (when notmuch-saved-searches
580           (widget-insert "Edit saved searches with the `edit' button.\n"))
581         (widget-insert "Hit RET or click on a saved search or tag name to view matching threads.\n")
582         (widget-insert "`=' refreshes this screen. `s' to search messages. `q' to quit.\n")
583         (let ((fill-column (- (window-width) notmuch-hello-indent)))
584           (center-region start (point))))
585
586       (widget-setup)
587
588       (when final-target-pos
589         (goto-char final-target-pos)
590         (unless (widget-at)
591           (widget-forward 1)))
592
593       (unless (widget-at)
594         (goto-char default-pos))))
595
596   (run-hooks 'notmuch-hello-refresh-hook))
597
598 (defun notmuch-folder ()
599   "Deprecated function for invoking notmuch---calling `notmuch' is preferred now."
600   (interactive)
601   (notmuch-hello))
602
603 ;;
604
605 (provide 'notmuch-hello)