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