]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
ca3a3813a5dd31bb9cc3552fda4eb3a89eb00566
[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
408     (kill-all-local-variables)
409     (let ((inhibit-read-only t))
410       (erase-buffer))
411
412     (unless (eq major-mode 'notmuch-hello-mode)
413       (notmuch-hello-mode))
414
415     (let ((all (overlay-lists)))
416       ;; Delete all the overlays.
417       (mapc 'delete-overlay (car all))
418       (mapc 'delete-overlay (cdr all)))
419
420     (when notmuch-show-logo
421       (let ((image notmuch-hello-logo))
422         ;; The notmuch logo uses transparency. That can display poorly
423         ;; when inserting the image into an emacs buffer (black logo on
424         ;; a black background), so force the background colour of the
425         ;; image. We use a face to represent the colour so that
426         ;; `defface' can be used to declare the different possible
427         ;; colours, which depend on whether the frame has a light or
428         ;; dark background.
429         (setq image (cons 'image
430                           (append (cdr image)
431                                   (list :background (face-background 'notmuch-hello-logo-background)))))
432         (insert-image image))
433       (widget-insert "  "))
434
435     (widget-insert "Welcome to ")
436     ;; Hack the display of the links used.
437     (let ((widget-link-prefix "")
438           (widget-link-suffix ""))
439       (widget-create 'link
440                      :notify (lambda (&rest ignore)
441                                (browse-url notmuch-hello-url))
442                      :help-echo "Visit the notmuch website."
443                      "notmuch")
444       (widget-insert ". ")
445       (widget-insert "You have ")
446       (widget-create 'link
447                      :notify (lambda (&rest ignore)
448                                (notmuch-hello-update))
449                      :help-echo "Refresh"
450                      (notmuch-hello-nice-number
451                       (string-to-number (car (process-lines notmuch-command "count")))))
452       (widget-insert " messages.\n"))
453
454     (let ((found-target-pos nil)
455           (final-target-pos nil))
456       (let* ((saved-alist
457               ;; Filter out empty saved searches if required.
458               (if notmuch-show-empty-saved-searches
459                   notmuch-saved-searches
460                 (loop for elem in notmuch-saved-searches
461                       if (> (string-to-number (notmuch-saved-search-count (cdr elem))) 0)
462                       collect elem)))
463              (saved-widest (notmuch-hello-longest-label saved-alist))
464              (alltags-alist (if notmuch-show-all-tags-list (notmuch-hello-generate-tag-alist)))
465              (alltags-widest (notmuch-hello-longest-label alltags-alist))
466              (widest (max saved-widest alltags-widest)))
467
468         (when saved-alist
469           ;; Sort saved searches if required.
470           (when notmuch-saved-search-sort-function
471             (setq saved-alist
472                   (funcall notmuch-saved-search-sort-function saved-alist)))
473           (widget-insert "\nSaved searches: ")
474           (widget-create 'push-button
475                          :notify (lambda (&rest ignore)
476                                    (customize-variable 'notmuch-saved-searches))
477                          "edit")
478           (widget-insert "\n\n")
479           (setq final-target-pos (point-marker))
480           (let ((start (point)))
481             (setq found-target-pos (notmuch-hello-insert-tags saved-alist widest target))
482             (if found-target-pos
483                 (setq final-target-pos found-target-pos))
484             (indent-rigidly start (point) notmuch-hello-indent)))
485
486         (widget-insert "\nSearch: ")
487         (setq notmuch-hello-search-bar-marker (point-marker))
488         (widget-create 'editable-field
489                        ;; Leave some space at the start and end of the
490                        ;; search boxes.
491                        :size (max 8 (- (window-width) notmuch-hello-indent
492                                        (length "Search: ")))
493                        :action (lambda (widget &rest ignore)
494                                  (notmuch-hello-search (widget-value widget))))
495         ;; add an invisible space to make `widget-end-of-line' ignore
496         ;; trailine spaces in the search widget field
497         (widget-insert " ")
498         (put-text-property (1- (point)) (point) 'invisible t)
499         (widget-insert "\n")
500
501         (when notmuch-hello-recent-searches
502           (widget-insert "\nRecent searches: ")
503           (widget-create 'push-button
504                          :notify (lambda (&rest ignore)
505                                    (setq notmuch-hello-recent-searches nil)
506                                    (notmuch-hello-update))
507                          "clear")
508           (widget-insert "\n\n")
509           (let ((start (point))
510                 (nth 0))
511             (mapc '(lambda (search)
512                      (let ((widget-symbol (intern (format "notmuch-hello-search-%d" nth))))
513                        (set widget-symbol
514                             (widget-create 'editable-field
515                                        ;; Don't let the search boxes be
516                                        ;; less than 8 characters wide.
517                                        :size (max 8
518                                                   (- (window-width)
519                                                      ;; Leave some space
520                                                      ;; at the start and
521                                                      ;; end of the
522                                                      ;; boxes.
523                                                      (* 2 notmuch-hello-indent)
524                                                      ;; 1 for the space
525                                                      ;; before the
526                                                      ;; `[save]' button. 6
527                                                      ;; for the `[save]'
528                                                      ;; button.
529                                                      1 6))
530                                        :action (lambda (widget &rest ignore)
531                                                  (notmuch-hello-search (widget-value widget)))
532                                        search))
533                        (widget-insert " ")
534                        (widget-create 'push-button
535                                       :notify (lambda (widget &rest ignore)
536                                                 (notmuch-hello-add-saved-search widget))
537                                       :notmuch-saved-search-widget widget-symbol
538                                       "save"))
539                      (widget-insert "\n")
540                      (setq nth (1+ nth)))
541                   notmuch-hello-recent-searches)
542             (indent-rigidly start (point) notmuch-hello-indent)))
543
544         (when alltags-alist
545           (widget-insert "\nAll tags: ")
546           (widget-create 'push-button
547                          :notify (lambda (widget &rest ignore)
548                                    (setq notmuch-show-all-tags-list nil)
549                                    (notmuch-hello-update))
550                          "hide")
551           (widget-insert "\n\n")
552           (let ((start (point)))
553             (setq found-target-pos (notmuch-hello-insert-tags alltags-alist widest target))
554             (if (not final-target-pos)
555                 (setq final-target-pos found-target-pos))
556             (indent-rigidly start (point) notmuch-hello-indent)))
557
558         (widget-insert "\n")
559
560         (if (not notmuch-show-all-tags-list)
561             (widget-create 'push-button
562                            :notify (lambda (widget &rest ignore)
563                                      (setq notmuch-show-all-tags-list t)
564                                      (notmuch-hello-update))
565                            "Show all tags")))
566
567       (let ((start (point)))
568         (widget-insert "\n\n")
569         (widget-insert "Type a search query and hit RET to view matching threads.\n")
570         (when notmuch-hello-recent-searches
571           (widget-insert "Hit RET to re-submit a previous search. Edit it first if you like.\n")
572           (widget-insert "Save recent searches with the `save' button.\n"))
573         (when notmuch-saved-searches
574           (widget-insert "Edit saved searches with the `edit' button.\n"))
575         (widget-insert "Hit RET or click on a saved search or tag name to view matching threads.\n")
576         (widget-insert "`=' refreshes this screen. `s' jumps to the search box. `q' to quit.\n")
577         (let ((fill-column (- (window-width) notmuch-hello-indent)))
578           (center-region start (point))))
579
580       (widget-setup)
581
582       (when final-target-pos
583         (goto-char final-target-pos)
584         (unless (widget-at)
585           (widget-forward 1)))
586
587       (unless (widget-at)
588         (notmuch-hello-goto-search)))))
589
590 (defun notmuch-folder ()
591   "Deprecated function for invoking notmuch---calling `notmuch' is preferred now."
592   (interactive)
593   (notmuch-hello))
594
595 ;;
596
597 (provide 'notmuch-hello)