]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-hello.el
d88a870085b567d9bc5ac97f92e0456468137c11
[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-recent-searches-max 10
33   "The number of recent searches to store and 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 (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     (unless (eq (% count tags-per-line) 0)
321       (widget-insert "\n"))
322     found-target-pos))
323
324 (defimage notmuch-hello-logo ((:type png :file "notmuch-logo.png")))
325
326 (defun notmuch-hello-search-continuation()
327   (notmuch-hello-update t))
328
329 (defun notmuch-hello-update (&optional no-display)
330   "Update the current notmuch view."
331   ;; Lazy - rebuild everything.
332   (interactive)
333   (notmuch-hello no-display))
334
335 (defun notmuch-hello-poll-and-update ()
336   "Invoke `notmuch-poll' to import mail, then refresh the current view."
337   (interactive)
338   (notmuch-poll)
339   (notmuch-hello-update))
340
341
342 (defvar notmuch-hello-mode-map
343   (let ((map (make-sparse-keymap)))
344     (set-keymap-parent map widget-keymap)
345     (define-key map "v" (lambda () "Display the notmuch version" (interactive)
346                           (message "notmuch version %s" (notmuch-version))))
347     (define-key map "?" 'notmuch-help)
348     (define-key map "q" 'notmuch-kill-this-buffer)
349     (define-key map "=" 'notmuch-hello-update)
350     (define-key map "G" 'notmuch-hello-poll-and-update)
351     (define-key map (kbd "<C-tab>") 'widget-backward)
352     (define-key map "m" 'notmuch-mua-new-mail)
353     (define-key map "s" 'notmuch-search)
354     map)
355   "Keymap for \"notmuch hello\" buffers.")
356 (fset 'notmuch-hello-mode-map notmuch-hello-mode-map)
357
358 (defun notmuch-hello-mode ()
359  "Major mode for convenient notmuch navigation. This is your entry portal into notmuch.
360
361 Complete list of currently available key bindings:
362
363 \\{notmuch-hello-mode-map}"
364  (interactive)
365  (kill-all-local-variables)
366  (use-local-map notmuch-hello-mode-map)
367  (setq major-mode 'notmuch-hello-mode
368        mode-name "notmuch-hello")
369  (run-mode-hooks 'notmuch-hello-mode-hook)
370  ;;(setq buffer-read-only t)
371 )
372
373 (defun notmuch-hello-generate-tag-alist ()
374   "Return an alist from tags to queries to display in the all-tags section."
375   (notmuch-remove-if-not
376    #'cdr
377    (mapcar (lambda (tag)
378              (cons tag
379                    (cond
380                     ((functionp notmuch-hello-tag-list-make-query)
381                      (concat "tag:" tag " and ("
382                              (funcall notmuch-hello-tag-list-make-query tag) ")"))
383                     ((stringp notmuch-hello-tag-list-make-query)
384                      (concat "tag:" tag " and ("
385                              notmuch-hello-tag-list-make-query ")"))
386                     (t (concat "tag:" tag)))))
387            (notmuch-remove-if-not
388             (lambda (tag)
389               (not (member tag notmuch-hello-hide-tags)))
390             (process-lines notmuch-command "search-tags")))))
391
392 ;;;###autoload
393 (defun notmuch-hello (&optional no-display)
394   "Run notmuch and display saved searches, known tags, etc."
395   (interactive)
396
397   ;; Jump through a hoop to get this value from the deprecated variable
398   ;; name (`notmuch-folders') or from the default value.
399   (unless notmuch-saved-searches
400     (setq notmuch-saved-searches (notmuch-saved-searches)))
401
402   (if no-display
403       (set-buffer "*notmuch-hello*")
404     (switch-to-buffer "*notmuch-hello*"))
405
406   (let ((target (if (widget-at)
407                    (widget-value (widget-at))
408                  (condition-case nil
409                      (progn
410                        (widget-forward 1)
411                        (widget-value (widget-at)))
412                    (error nil))))
413         (inhibit-read-only t))
414
415     ;; Delete all editable widget fields.  Editable widget fields are
416     ;; tracked in a buffer local variable `widget-field-list' (and
417     ;; others).  If we do `erase-buffer' without properly deleting the
418     ;; widgets, some widget-related functions are confused later.
419     (mapc 'widget-delete widget-field-list)
420
421     (erase-buffer)
422
423     (unless (eq major-mode 'notmuch-hello-mode)
424       (notmuch-hello-mode))
425
426     (let ((all (overlay-lists)))
427       ;; Delete all the overlays.
428       (mapc 'delete-overlay (car all))
429       (mapc 'delete-overlay (cdr all)))
430
431     (when notmuch-show-logo
432       (let ((image notmuch-hello-logo))
433         ;; The notmuch logo uses transparency. That can display poorly
434         ;; when inserting the image into an emacs buffer (black logo on
435         ;; a black background), so force the background colour of the
436         ;; image. We use a face to represent the colour so that
437         ;; `defface' can be used to declare the different possible
438         ;; colours, which depend on whether the frame has a light or
439         ;; dark background.
440         (setq image (cons 'image
441                           (append (cdr image)
442                                   (list :background (face-background 'notmuch-hello-logo-background)))))
443         (insert-image image))
444       (widget-insert "  "))
445
446     (widget-insert "Welcome to ")
447     ;; Hack the display of the links used.
448     (let ((widget-link-prefix "")
449           (widget-link-suffix ""))
450       (widget-create 'link
451                      :notify (lambda (&rest ignore)
452                                (browse-url notmuch-hello-url))
453                      :help-echo "Visit the notmuch website."
454                      "notmuch")
455       (widget-insert ". ")
456       (widget-insert "You have ")
457       (widget-create 'link
458                      :notify (lambda (&rest ignore)
459                                (notmuch-hello-update))
460                      :help-echo "Refresh"
461                      (notmuch-hello-nice-number
462                       (string-to-number (car (process-lines notmuch-command "count")))))
463       (widget-insert " messages.\n"))
464
465     (let ((found-target-pos nil)
466           (final-target-pos nil)
467           (search-bar-pos))
468       (let* ((saved-alist
469               ;; Filter out empty saved searches if required.
470               (if notmuch-show-empty-saved-searches
471                   notmuch-saved-searches
472                 (loop for elem in notmuch-saved-searches
473                       if (> (string-to-number (notmuch-saved-search-count (cdr elem))) 0)
474                       collect elem)))
475              (saved-widest (notmuch-hello-longest-label saved-alist))
476              (alltags-alist (if notmuch-show-all-tags-list (notmuch-hello-generate-tag-alist)))
477              (alltags-widest (notmuch-hello-longest-label alltags-alist))
478              (widest (max saved-widest alltags-widest)))
479
480         (when saved-alist
481           ;; Sort saved searches if required.
482           (when notmuch-saved-search-sort-function
483             (setq saved-alist
484                   (funcall notmuch-saved-search-sort-function saved-alist)))
485           (widget-insert "\nSaved searches: ")
486           (widget-create 'push-button
487                          :notify (lambda (&rest ignore)
488                                    (customize-variable 'notmuch-saved-searches))
489                          "edit")
490           (widget-insert "\n\n")
491           (setq final-target-pos (point-marker))
492           (let ((start (point)))
493             (setq found-target-pos (notmuch-hello-insert-tags saved-alist widest target))
494             (if found-target-pos
495                 (setq final-target-pos found-target-pos))
496             (indent-rigidly start (point) notmuch-hello-indent)))
497
498         (widget-insert "\nSearch: ")
499         (setq search-bar-pos (point-marker))
500         (widget-create 'editable-field
501                        ;; Leave some space at the start and end of the
502                        ;; search boxes.
503                        :size (max 8 (- (window-width) notmuch-hello-indent
504                                        (length "Search: ")))
505                        :action (lambda (widget &rest ignore)
506                                  (notmuch-hello-search (widget-value widget))))
507         ;; Add an invisible dot to make `widget-end-of-line' ignore
508         ;; trailing spaces in the search widget field.  A dot is used
509         ;; instead of a space to make `show-trailing-whitespace'
510         ;; happy, i.e. avoid it marking the whole line as trailing
511         ;; spaces.
512         (widget-insert ".")
513         (put-text-property (1- (point)) (point) 'invisible t)
514         (widget-insert "\n")
515
516         (when notmuch-hello-recent-searches
517           (widget-insert "\nRecent searches: ")
518           (widget-create 'push-button
519                          :notify (lambda (&rest ignore)
520                                    (setq notmuch-hello-recent-searches nil)
521                                    (notmuch-hello-update))
522                          "clear")
523           (widget-insert "\n\n")
524           (let ((start (point))
525                 (nth 0))
526             (mapc (lambda (search)
527                     (let ((widget-symbol (intern (format "notmuch-hello-search-%d" nth))))
528                       (set widget-symbol
529                            (widget-create 'editable-field
530                                           ;; Don't let the search boxes be
531                                           ;; less than 8 characters wide.
532                                           :size (max 8
533                                                      (- (window-width)
534                                                         ;; Leave some space
535                                                         ;; at the start and
536                                                         ;; end of the
537                                                         ;; boxes.
538                                                         (* 2 notmuch-hello-indent)
539                                                         ;; 1 for the space
540                                                         ;; before the
541                                                         ;; `[save]' button. 6
542                                                         ;; for the `[save]'
543                                                         ;; button.
544                                                         1 6))
545                                           :action (lambda (widget &rest ignore)
546                                                     (notmuch-hello-search (widget-value widget)))
547                                           search))
548                       (widget-insert " ")
549                       (widget-create 'push-button
550                                      :notify (lambda (widget &rest ignore)
551                                                (notmuch-hello-add-saved-search widget))
552                                      :notmuch-saved-search-widget widget-symbol
553                                      "save"))
554                     (widget-insert "\n")
555                     (setq nth (1+ nth)))
556                   notmuch-hello-recent-searches)
557             (indent-rigidly start (point) notmuch-hello-indent)))
558
559         (when alltags-alist
560           (widget-insert "\nAll tags: ")
561           (widget-create 'push-button
562                          :notify (lambda (widget &rest ignore)
563                                    (setq notmuch-show-all-tags-list nil)
564                                    (notmuch-hello-update))
565                          "hide")
566           (widget-insert "\n\n")
567           (let ((start (point)))
568             (setq found-target-pos (notmuch-hello-insert-tags alltags-alist widest target))
569             (unless final-target-pos
570               (setq final-target-pos found-target-pos))
571             (indent-rigidly start (point) notmuch-hello-indent)))
572
573         (widget-insert "\n")
574
575         (unless notmuch-show-all-tags-list
576           (widget-create 'push-button
577                          :notify (lambda (widget &rest ignore)
578                                    (setq notmuch-show-all-tags-list t)
579                                    (notmuch-hello-update))
580                          "Show all tags")))
581
582       (let ((start (point)))
583         (widget-insert "\n\n")
584         (widget-insert "Type a search query and hit RET to view matching threads.\n")
585         (when notmuch-hello-recent-searches
586           (widget-insert "Hit RET to re-submit a previous search. Edit it first if you like.\n")
587           (widget-insert "Save recent searches with the `save' button.\n"))
588         (when notmuch-saved-searches
589           (widget-insert "Edit saved searches with the `edit' button.\n"))
590         (widget-insert "Hit RET or click on a saved search or tag name to view matching threads.\n")
591         (widget-insert "`=' refreshes this screen. `s' to search messages. `q' to quit.\n")
592         (let ((fill-column (- (window-width) notmuch-hello-indent)))
593           (center-region start (point))))
594
595       (widget-setup)
596
597       (when final-target-pos
598         (goto-char final-target-pos)
599         (unless (widget-at)
600           (widget-forward 1)))
601
602       (unless (widget-at)
603         (goto-char search-bar-pos))))
604
605   (run-hooks 'notmuch-hello-refresh-hook))
606
607 (defun notmuch-folder ()
608   "Deprecated function for invoking notmuch---calling `notmuch' is preferred now."
609   (interactive)
610   (notmuch-hello))
611
612 ;;
613
614 (provide 'notmuch-hello)