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