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