-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconsult-mu.el
1527 lines (1245 loc) · 68.9 KB
/
consult-mu.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; consult-mu.el --- Consult Mu4e asynchronously in GNU Emacs -*- lexical-binding: t -*-
;; Copyright (C) 2023 Armin Darvish
;; Author: Armin Darvish
;; Maintainer: Armin Darvish
;; Created: 2023
;; Version: 1.0
;; Package-Requires: ((emacs "28.0") (consult "2.0"))
;; Keywords: convenience, matching, tools, email
;; Homepage: https://github.com/armindarvish/consult-mu
;; SPDX-License-Identifier: GPL-3.0-or-later
;; This file is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation, either version 3 of the License,
;; or (at your option) any later version.
;;
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this file. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This package provides an alternative interactive serach interface for
;; mu and mu4e (see URL `https://djcbsoftware.nl/code/mu/mu4e.html').
;; It uses a consult-based minibuffer completion for searching and
;; selecting, and marking emails, as well as additional utilities for
;; composing emails and more.
;; This package requires mu4e version "1.10.8" or later.
;;; Code:
;;; Requirements
(require 'consult)
(require 'mu4e)
;;; Group
(defgroup consult-mu nil
"Options for `consult-mu'."
:group 'convenience
:group 'minibuffer
:group 'consult
:group 'mu4e
:prefix "consult-mu-")
;;; Customization Variables
(defcustom consult-mu-args '("mu")
"Command line arguments to call `mu` asynchronously.
The dynamically computed arguments are appended.
Can be either a string, or a list of strings or expressions."
:group 'consult-mu
:type '(choice string (repeat (choice string sexp))))
(defcustom consult-mu-maxnum mu4e-search-results-limit
"Maximum number of results
This is normally passed to \"--maxnum\" in the command line or is defined by `mu4e-search-results-limit'. By default inherits from `mu4e-search-results-limit'. "
:group 'consult-mu
:type '(choice (const :tag "Unlimited" -1)
(integer :tag "Limit")))
(defcustom consult-mu-search-sort-field mu4e-search-sort-field
"What field to sort results by?
By defualt inherits from `mu4e-search-sort-field'."
:group 'consult-mu
:type '(radio (const :tag "Date" :date)
(const :tag "Subject" :subject)
(const :tag "File Size" :size)
(const :tag "Priority" :prio)
(const :tag "From (Sender)" :from)
(const :tag "To (Recipients)" :to)
(const :tag "Mailing List" :list)))
(defcustom consult-mu-headers-fields mu4e-headers-fields
"A list of header fields to show in the headers buffer.
By default inherits from `mu4e-headers-field'.
From mu4e docs:
Each element has the form (HEADER . WIDTH), where HEADER is one of
the available headers (see `mu4e-header-info') and WIDTH is the
respective width in characters.
A width of nil means \"unrestricted\", and this is best reserved
for the rightmost (last) field. Note that emacs may become very
slow with excessively long lines (1000s of characters), so if you
regularly get such messages, you want to avoid fields with nil
altogether."
:group 'consult-mu
:type `(repeat (cons (choice ,@(mapcar (lambda (h)
(list 'const
:tag (plist-get (cdr h) :help)
(car h)))
mu4e-header-info))
(choice (integer :tag "width")
(const :tag "unrestricted width" nil)))))
(defcustom consult-mu-headers-template nil
"A template string to make custom header formats.
If non-nil, consult-mu uses this string to format the headers instead of `consult-mu-headers-field'.
The string should be of the format “%[char][integer]%[char][integer]...”, and allow dynamic insertion of the content. Each “%[char][integer]“ chunk represents a different field and the integer defines the length of the field. for exmaple \"%d15%s50\" means 15 characters for date and 50 charcters for subject.
The list of available fields are:
%f sender(s) (e.g. from: field of email)
%t receivers(s) (i.e. to: field of email)
%s subject (i.e. title of email)
%d date (i.e. the date email was sent/received)
%p priority
%z size
%i message-id (as defined by mu)
%g flags (as defined by mu)
%G pretty flags (this uses `mu4e~headers-flags-str' to pretify flags)
%x tags (as defined by mu)
%c cc (i.e. cc: field of the email)
%h bcc (i.e. bcc: field of the email)
%r date chaged (as defined by :changed in mu4e)
For example, the string \"%d13%s50%f17\" would make a header containing 13 characters for Date, 50 characters for Subject, and 20 characters for From field, making a header that looks like this:
Thu 09 Nov 23 Title of the Email Limited to 50 Characters Onl... example@domain...
"
:group 'consult-mu
:type '(choice (const :tag "Fromatted String" :format "%{%%d13%%s50%%f17%}")
(function :tag "Custom Function")))
(defcustom consult-mu-search-sort-direction mu4e-search-sort-direction
"Direction to sort by a symbol.
By defualt inherits from 'mu4e-search-sort-direction'. and can either be
`descending' (sorting Z->A)
or
`ascending' (sorting A->Z)."
:group 'consult-mu
:type '(radio (const ascending)
(const descending)))
(defcustom consult-mu-search-threads mu4e-search-threads
"Whether to calculate threads for search results.
By defualt inherits from 'mu4e-search-threads'.
Note that per mu4e docs:
When threading is enabled, the headers are exclusively sorted
chronologically (:date) by the newest message in the thread.
"
:group 'consult-mu
:type 'boolean)
(defcustom consult-mu-group-by nil
"What field to use to group the results in the minibuffer.
By default it is set to :date. But can be any of:
:subject group by subject
:from group by the name/email the sender(s)
:to group by name/email of the reciver(s)
:date group by date
:time group by the time of email (i.e. hour, minute, seconds)
:datetime group by date and time of the email
:year group by the year of the email (i.e. 2023, 2022, ...)
:month group by the month of the email (i.e. Jan, Feb, ..., Dec)
:week group by the week number of the email (.i.e. 1st week, 2nd week, ... 52nd week)
:day-of-week group by the day email was sent (i.e. Mondays, Tuesdays, ...)
:day group by the day email was sent (similar to :day-of-week)
:size group by the file size of the email
:flags group by flags (as defined by mu)
:tags group by tags (as defined by mu)
:changed group by the date changed (as defined by :changed field in mu4e)
"
:group 'consult-mu
:type '(radio (const :date)
(const :subject)
(const :from)
(const :to)
(const :time)
(const :datetime)
(const :year)
(const :month)
(const :week)
(const :day-of-week)
(const :day)
(const :size)
(const :flags)
(const :tags)
(const :changed)
(const nil)))
(defcustom consult-mu-mark-previewed-as-read nil
"Whether to mark PREVIEWED emails as read or not?"
:group 'consult-mu
:type 'boolean)
(defcustom consult-mu-mark-viewed-as-read t
"Whether to mark VIEWED emails as read or not?"
:group 'consult-mu
:type 'boolean)
(defcustom consult-mu-headers-buffer-name "*consult-mu-headers*"
"Default name for HEADERS buffer explicitly for consult-mu.
For more info see `mu4e-headers-buffer-name'."
:group 'consult-mu
:type 'string)
(defcustom consult-mu-view-buffer-name "*consult-mu-view*"
"Default name for VIEW buffer explicitly for consult-mu.
For more info see `mu4e-view-buffer-name'."
:group 'consult-mu
:type 'string)
(defcustom consult-mu-preview-key consult-preview-key
"Preview key for `consult-mu'.
This is similar to `consult-preview-key' but explicitly for consult-mu."
:type '(choice (const :tag "Any key" any)
(list :tag "Debounced"
(const :debounce)
(float :tag "Seconds" 0.1)
(const any))
(const :tag "No preview" nil)
(key :tag "Key")
(repeat :tag "List of keys" key)))
(defcustom consult-mu-highlight-matches t
"Should `consult-mu' highlight search queries in preview buffers?"
:group 'consult-mu
:type 'boolean)
(defcustom consult-mu-use-wide-reply 'ask
"Reply to all or not?
This defines whether `consult-mu--reply-action' should reply to all or not."
:group 'consult-mu
:type '(choice (const :tag "Ask for confirmation" 'ask)
(const :tag "Do not reply to all" nil)
(const :tag "Always reply to all" t)))
(defcustom consult-mu-action #'consult-mu--view-action
"The function that is used when selecting a message.
By default it is bound to `consult-mu--view-action'."
:group 'consult-mu
:type '(choice (function :tag "(Default) View Message in Mu4e Buffers" #'consult-mu--view-action)
(function :tag "Reply to Message" #'consult-mu--reply-action)
(function :tag "Forward Message" #'consult-mu--forward-action)
(function :tag "Custom Function")))
(defcustom consult-mu-default-command #'consult-mu-dynamic
"Which command should `consult-mu' call."
:group 'consult-mu
:type '(choice (function :tag "(Default) Use Dynamic Collection (i.e. `consult-mu-dynamic')" #'consult-mu-dynamic)
(function :tag "Use Async Collection (i.e. `consult-mu-async')" #'consult-mu-async)
(function :tag "Custom Function")))
;;; Other Variables
(defvar consult-mu-category 'consult-mu
"Category symbol for the `consult-mu' package.")
(defvar consult-mu-messages-category 'consult-mu-messages
"Category symbol for messages in `consult-mu' package.")
(defvar consult-mu--view-buffers-list (list)
"List of currently open preview buffers for `consult-mu'.")
(defvar consult-mu--history nil
"History variable for `consult-mu'.")
(defvar consult-mu-delimiter " "
"Delimiter to use for fields in mu command output.
The idea is Taken from https://github.com/seanfarley/counsel-mu.")
(defvar consult-mu-saved-searches-dynamic (list)
"List of Favorite searches for `consult-mu-dynamic'.")
(defvar consult-mu-saved-searches-async consult-mu-saved-searches-dynamic
"List of Favorite searches for `consult-mu-async'.")
(defvar consult-mu--override-group nil
"Override grouping in `consult-mu' based on user input.")
;;; Faces
(defface consult-mu-highlight-match-face
`((t :inherit 'consult-highlight-match))
"Highlight match face in `consult-mu''s view buffer.
By default inherits from `consult-highlight-match'.
This is used to highlight matches of search queries in the minibufffer completion list.")
(defface consult-mu-preview-match-face
`((t :inherit 'consult-preview-match))
"Preview match face in `consult-mu''s preview buffers.
By default inherits from `consult-preview-match'.
This is used to highlight matches of search query terms in preview buffers \(i.e. `consult-mu-view-buffer-name'\).")
(defface consult-mu-default-face
`((t :inherit 'default))
"Default face in `consult-mu''s minibuffer annotations.
By default inherits from `default' face.")
(defface consult-mu-subject-face
`((t :inherit 'font-lock-keyword-face))
"Subject face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-keyword-face'.")
(defface consult-mu-sender-face
`((t :inherit 'font-lock-variable-name-face))
"Contact face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-variable-name-face'.")
(defface consult-mu-receiver-face
`((t :inherit 'font-lock-variable-name-face))
"Contact face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-variable-name-face'.")
(defface consult-mu-date-face
`((t :inherit 'font-lock-preprocessor-face))
"Date face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-preprocessor-face'.")
(defface consult-mu-count-face
`((t :inherit 'font-lock-string-face))
"Count face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-string-face'.")
(defface consult-mu-size-face
`((t :inherit 'font-lock-string-face))
"Size face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-string-face'.")
(defface consult-mu-tags-face
`((t :inherit 'font-lock-comment-face))
"Tags/Comments face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-comment-face'.")
(defface consult-mu-flags-face
`((t :inherit 'font-lock-function-call-face))
"Flags face in `consult-mu''s minibuffer annotations.
By default inherits from `font-lock-function-call-face'.")
(defface consult-mu-url-face
`((t :inherit 'link))
"URL face in `consult-mu''s minibuffer annotations;
By default inherits from `link'.")
(defun consult-mu--pulse-regexp (regexp)
"Finds and pulses REGEXP"
(goto-char (point-min))
(while (re-search-forward regexp nil t)
(when-let* ((m (match-data))
(beg (car m))
(end (cadr m))
(ov (make-overlay beg end))
(pulse-delay 0.075))
(pulse-momentary-highlight-overlay ov 'highlight))))
(defun consult-mu--pulse-region (beg end)
"Finds and pulses region from BEG to END"
(let ((ov (make-overlay beg end))
(pulse-delay 0.075))
(pulse-momentary-highlight-overlay ov 'highlight)))
(defun consult-mu--pulse-line ()
"Pulses line at point momentarily"
(let* ((pulse-delay 0.055)
(ov (make-overlay (car (bounds-of-thing-at-point 'line))
(cdr (bounds-of-thing-at-point 'line)))))
(pulse-momentary-highlight-overlay ov 'highlight)))
(defun consult-mu--set-string-width (string width &optional prepend)
"Sets the STRING width to a fixed value, WIDTH.
If the STRING is longer than WIDTH, it truncates the string and adds ellipsis, \"...\". If the string is shorter it adds whitespace to the string.
If PREPEND is non-nil, it truncates or adds whitespace from the beginning of string, instead of the end."
(let* ((string (format "%s" string))
(w (string-width string)))
(when (< w width)
(if prepend
(setq string (format "%s%s" (make-string (- width w) ?\s) (substring string)))
(setq string (format "%s%s" (substring string) (make-string (- width w) ?\s)))))
(when (> w width)
(if prepend
(setq string (format "...%s" (substring string (- w (- width 3)) w)))
(setq string (format "%s..." (substring string 0 (- width (+ w 3)))))))
string))
(defun consult-mu--justify-left (string prefix maxwidth)
"Sets the width of STRING+PREFIX justified from left.
It uses `consult-mu--set-string-width' and sets the width of the concatenate of STRING+PREFIX (e.g. `(concat prefix string)`) within MAXWIDTH. This is used for aligning marginalia info in minibuffer when using `consult-mu'."
(let ((s (string-width string))
(w (string-width prefix)))
(if (> maxwidth w)
(consult-mu--set-string-width string (- maxwidth w) t)
string)))
(defun consult-mu--highlight-match (regexp str ignore-case)
"Highlights REGEXP in STR.
If a regular expression contains capturing groups, only these are highlighted.
If no capturing groups are used highlight the whole match. Case is ignored
if IGNORE-CASE is non-nil.
(This is adapted from `consult--highlight-regexps'.)"
(let ((i 0))
(while (and (let ((case-fold-search ignore-case))
(string-match regexp str i))
(> (match-end 0) i))
(let ((m (match-data)))
(setq i (cadr m)
m (or (cddr m) m))
(while m
(when (car m)
(add-face-text-property (car m) (cadr m)
'consult-mu-highlight-match-face nil str))
(setq m (cddr m))))))
str)
(defun consult-mu--overlay-match (match-str buffer ignore-case)
"Highlights MATCH-STR in BUFFER using an overlay.
If IGNORE-CASE is non-nil, it uses case-insensitive match.
This is used to highlight matches to use rqueries when viewing emails in consult-mu. See `consult-mu-overlays-toggle' for toggling highligths on/off."
(with-current-buffer (or (get-buffer buffer) (current-buffer))
(remove-overlays (point-min) (point-max) 'consult-mu-overlay t)
(goto-char (point-min))
(let ((case-fold-search ignore-case)
(consult-mu-overlays (list)))
(while (search-forward match-str nil t)
(when-let* ((m (match-data))
(beg (car m))
(end (cadr m))
(overlay (make-overlay beg end)))
(overlay-put overlay 'consult-mu-overlay t)
(overlay-put overlay 'face 'consult-mu-highlight-match-face))))))
(defun consult-mu-overlays-toggle (&optional buffer)
"Toggles overlay highlights in consult-mu view/preview buffers."
(interactive)
(let ((buffer (or buffer (current-buffer))))
(with-current-buffer buffer
(dolist (o (overlays-in (point-min) (point-max)))
(when (overlay-get o 'consult-mu-overlay)
(if (and (overlay-get o 'face) (eq (overlay-get o 'face) 'consult-mu-highlight-match-face))
(overlay-put o 'face nil)
(overlay-put o 'face 'consult-mu-highlight-match-face)))))))
(defun consult-mu--format-date (string)
"Format the date STRING from mu output.
STRING is the output form mu command. for example from `mu find query --fields d`
Returns the date in the format Day-of-Week Month Day Year Time (e.g. Sat Nov 04 2023 09:46:54)"
(let ((string (replace-regexp-in-string " " "0" string)))
(format "%s %s %s"
(substring string 0 10)
(substring string -4 nil)
(substring string 11 -4))))
(defun consult-mu-flags-to-string (FLAG)
"Coverts FLAGS, from mu output to strings.
FLAG is the output form mu command in the terminal. For example `mu find query --fields g`.
This function converts each character in FLAG to an expanded string of the flag and returns the list of these strings."
(cl-loop for c across FLAG
collect
(pcase (string c)
("D" 'draft)
("F" 'flagged)
("N" 'new)
("P" 'forwarded)
("R" 'replied)
("S" 'read)
("T" 'trashed)
("a" 'attachment)
("x" 'encrrypted)
("s" 'signed)
("u" 'unread)
("l" 'list)
("q" 'personal)
("c" 'calendar)
(_ nil))))
(defun consult-mu--message-extract-email-from-string (string)
"Finds and returns the first email address in the STRING"
(when (stringp string)
(string-match "[a-zA-Z0-9\_\.\+\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+" string)
(match-string 0 string)))
(defun consult-mu--message-emails-string-to-list (string)
"Converts comma-separated STRING containing email addresses to list of emails"
(when (stringp string)
(remove '(" " "\s" "\t") (mapcar #'consult-mu--message-extract-email-from-string
(split-string string ",\\|;\\|\t" t)))))
(defun consult-mu--message-get-header-field (&optional field)
"Retrive FIELD header from the message/mail in the current buffer"
(save-match-data
(save-excursion
(when (or (derived-mode-p 'message-mode)
(derived-mode-p 'mu4e-view-mode)
(derived-mode-p 'org-msg-edit-mode)
(derived-mode-p 'mu4e-compose-mode))
(let ((field (or field
(s-lower-camel-case (consult--read '("Subject" "From" "To" "Cc" "Bcc" "Reply-To" "Date" "Attachments" "Tags" "Flags" "Maildir" "Summary")
:prompt "Header Field: ")))))
(if (equal field "attachments") (setq field "\\(attachment\\|attachments\\)"))
(goto-char (point-min))
(let* ((match (re-search-forward (concat "^" field ": \\(?1:[[:ascii:][:nonascii:]]+?\\)\n.*?: ") nil t))
(str (if match (string-trim (match-string 1)))))
(if (string-empty-p str) nil str)))))))
(defun consult-mu--headers-append-handler (msglst)
"Overrides `mu4e~headers-append-handler' for `consult-mu'.
This is to ensure that buffer handling is done right for consult-mu.
From mu4e docs:
Append one-line descriptions of messages in MSGLIST.
Do this at the end of the headers-buffer.
"
(with-current-buffer "*consult-mu-headers*"
(let ((inhibit-read-only t))
(seq-do
;; I use mu4e-column-faces and it overrides the default append-handler. To get the same effect I check if mu4e-column-faces is active and enabled.
(if (and (featurep 'mu4e-column-faces) mu4e-column-faces-mode)
(lambda (msg)
(mu4e-column-faces--insert-header msg (point-max)))
(lambda (msg)
(mu4e~headers-insert-header msg (point-max))))
msglst))))
(defun consult-mu--view-msg (msg &optional buffername)
"Overrides `mu4e-view' for `consult-mu'.
This is to ensure that buffer handling is done right for consult-mu.
From mu4e docs:
Display the message MSG in a new buffer, and keep in sync with `consult-mu-headers-buffer-name' buffer.
\"In sync\" here means that moving to the next/previous message
in the the message view affects `consult-mu-headers-buffer-name', as does marking etc.
"
(let* ((linked-headers-buffer (mu4e-get-headers-buffer "*consult-mu-headers*" t))
(mu4e-view-buffer-name (or buffername consult-mu-view-buffer-name)))
(setq gnus-article-buffer (mu4e-get-view-buffer linked-headers-buffer t))
(with-current-buffer gnus-article-buffer
(let ((inhibit-read-only t))
(remove-overlays (point-min) (point-max) 'mu4e-overlay t)
(erase-buffer)
(insert-file-contents-literally
(mu4e-message-readable-path msg) nil nil nil t)
(setq-local mu4e--view-message msg)
(mu4e--view-render-buffer msg)
(mu4e-loading-mode 0)
(with-current-buffer linked-headers-buffer
(setq-local mu4e~headers-view-win (mu4e-display-buffer gnus-article-buffer nil)))
(run-hooks 'mu4e-view-rendered-hook)))))
(defun consult-mu--headers-clear (&optional text)
"Overrides `mu4e~headers-clear' for `consult-mu'.
This is to ensure that buffer handling is done right for consult-mu.
From mu4e docs:
Clear the headers buffer and related data structures.
Optionally, show TEXT. "
(setq mu4e~headers-render-start (float-time)
mu4e~headers-hidden 0)
(with-current-buffer "*consult-mu-headers*"
(let ((inhibit-read-only t))
(mu4e--mark-clear)
(erase-buffer)
(when text
(goto-char (point-min))
(insert (propertize text 'face 'mu4e-system-face 'intangible t))))))
(defun consult-mu--set-mu4e-search-sortfield (opts)
"Dynamically sets the `mu4e-search-sort-field' based on user input.
Uses user input (i.e. from `consult-mu' command) to define the sort field.
OPTS is the command line options for mu and can be set by entering options in the minibuffer input. For more details refer to `cpnsult-grep' and consult async documentation.
For example if the user enters the following in the minibuffer:
`#query -- --maxnum 400 --sortfield from --reverse --include-related --skip-dups --threads'
mu4e-search-sort-field is set to :from
Note that per mu4e docs:
When threading is enabled, the headers are exclusively sorted
chronologically (:date) by the newest message in the thread.
"
(let* ((sortfield (cond
((member "-s" opts) (nth (+ (cl-position "-s" opts :test 'equal) 1) opts))
((member "--sortfield" opts) (nth (+ (cl-position "--sortfield" opts :test 'equal) 1) opts))
(t consult-mu-search-sort-field))))
(pcase sortfield
('nil
consult-mu-search-sort-field)
((or "date" "d")
:date)
((or "subject" "s")
:subject)
((or "size" "z")
:size)
((or "prio" "p")
:prio)
((or "from" "f")
:from)
((or "to" "t")
:to)
((or "list" "v")
:list)
;; ((or "tags" "x")
;; :tags)
(_
consult-mu-search-sort-field))))
(defun consult-mu--set-mu4e-search-sort-direction (opts)
"Dynamically sets the `mu4e-search-sort-direction' based on user input.
Uses user input (i.e. from `consult-mu' command) to define the sort field.
OPTS is the command line options for mu and can be set by entering options in the minibuffer input. For more details refer to `cpnsult-grep' and consult async documentation.
For example if the user enters the following in the minibuffer:
`#query -- --maxnum 400 --sortfield from --reverse --include-related --skip-dups --threads'
the `mu4e-search-sort-direction' is reversed; if it is set to 'ascending, it is toggled to 'descending and vise versa.
"
(if (or (member "-z" opts) (member "--reverse" opts))
(pcase consult-mu-search-sort-direction
('descending
'ascending)
('ascending
'descending))
consult-mu-search-sort-direction))
(defun consult-mu--set-mu4e-skip-duplicates (opts)
"Dynamically sets the `mu4e-search-skip-duplicates' based on user input.
Uses user input (i.e. from `consult-mu' command) to define the sort field.
OPTS is the command line options for mu and can be set by entering options in the minibuffer input. For more details refer to `cpnsult-grep' and consult async documentation.
For example if the user enters the following in the minibuffer:
`#query -- --maxnum 400 --sortfield from --reverse --include-related --skip-dups --threads'
the `mu4e-search-skip-duplicates' is set to t.
"
(if (or (member "--skip-dups" opts) mu4e-search-skip-duplicates) t nil))
(defun consult-mu--set-mu4e-results-limit (opts)
"Dynamically sets the `mu4e-search-results-limit' based on user input.
Uses user input (i.e. from `consult-mu' command) to define the maximum number of results.
OPTS is the command line options for mu and can be set by entering options in the minibuffer input. For more details refer to `consult-mu' or `consult-mu-async' documentation.
For example if the user enters the following in the minibuffer:
`#query -- --maxnum 400 --sortfield from --reverse --include-related --skip-dups --threads'
the `mu4e-search-results-limit' is set to 400.
"
(cond
((member "-n" opts) (string-to-number (nth (+ (cl-position "-n" opts :test 'equal) 1) opts)))
((member "--maxnum" opts) (string-to-number (nth (+ (cl-position "--maxnum" opts :test 'equal) 1) opts)))
(t consult-mu-maxnum)))
(defun consult-mu--set-mu4e-include-related (opts)
"Dynamically sets the `mu4e-search-include-related' based on user input.
Uses user input (i.e. from `consult-mu' command) to define the include-related property.
OPTS is the command line options for mu and can be set by entering options in the minibuffer input. For more details refer to `consult-mu' or `consult-mu-async' documentation.
For example if the user enters the following in the minibuffer:
`#query -- --maxnum 400 --sortfield from --reverse --include-related --skip-dups --threads'
the `mu4e-search-include-related' is set to t.
"
(if (or (member "-r" opts) (member "--include-related" opts) mu4e-search-include-related) t nil))
(defun consult-mu--set-mu4e-threads (opts)
"Sets the `mu4e-search-threads' based on `mu4e-search-sort-field'.
Note that per mu4e docs, when threading is enabled, the headers are exclusively sorted by date.
Here the logic is reversed in order to allow dynamically sorting by fields other than date (even when threads are enabled).
In other words if the sort-field is not the :date threading is disabled (because otherwise sort field will be ignored anyway).This allows the user to use command line arguments to sort messages by fields other than the date. For example the user can enter the following in the minibuffer input to sort by subject
`#query -- --sortfield from'
When the sort-field is :date, then `consult-mu-search-threads' is used. If `consult-mu-search-threads' is set to nil, the user can use command line arguments (a.k.a. -t or --thread) to enable it dynamically.
"
(cond
((not (equal mu4e-search-sort-field :date))
nil)
((or (member "-t" opts) (member "--threads" opts) consult-mu-search-threads)
t)))
(defun consult-mu--update-headers (query ignore-history msg type)
"Search for QUERY, and updates `consult-mu-headers-buffer-name' buffer.
If IGNORE-HISTORY is true, does *not* update the query history stack, `mu4e--search-query-past'.
If MSGID is non-nil, put the cursor on message with MSGID.
"
(consult-mu--execute-all-marks)
(cl-letf* (((symbol-function #'mu4e~headers-append-handler) #'consult-mu--headers-append-handler))
(unless (mu4e-running-p) (mu4e--server-start))
(let* ((buf (mu4e-get-headers-buffer consult-mu-headers-buffer-name t))
(view-buffer (get-buffer consult-mu-view-buffer-name))
(expr (car (consult--command-split (substring-no-properties query))))
(rewritten-expr (funcall mu4e-query-rewrite-function expr))
(maxnum (unless mu4e-search-full mu4e-search-results-limit))
(mu4e-headers-fields consult-mu-headers-fields))
(pcase type
(:dynamic)
(:async
(setq rewritten-expr (funcall mu4e-query-rewrite-function (concat "msgid:" (plist-get msg :message-id)))))
(_ ))
(with-current-buffer buf
(save-excursion
(let ((inhibit-read-only t))
(erase-buffer)
(mu4e-headers-mode)
(setq-local mu4e-view-buffer-name consult-mu-view-buffer-name)
(if view-buffer
(setq-local mu4e~headers-view-win (mu4e-display-buffer gnus-article-buffer nil)))
(unless ignore-history
; save the old present query to the history list
(when mu4e--search-last-query
(mu4e--search-push-query mu4e--search-last-query 'past)))
(setq mu4e--search-last-query rewritten-expr)
(setq list-buffers-directory rewritten-expr)
(mu4e--modeline-update)
(run-hook-with-args 'mu4e-search-hook expr)
(consult-mu--headers-clear mu4e~search-message)
(setq mu4e~headers-search-start (float-time))
(pcase-let* ((`(,arg . ,opts) (consult--command-split query))
(mu4e-search-sort-field (consult-mu--set-mu4e-search-sortfield opts))
(mu4e-search-sort-direction (consult-mu--set-mu4e-search-sort-direction opts))
(mu4e-search-skip-duplicates (consult-mu--set-mu4e-skip-duplicates opts))
(mu4e-search-results-limit (consult-mu--set-mu4e-results-limit opts))
(mu4e-search-threads (consult-mu--set-mu4e-threads opts))
(mu4e-search-include-related (consult-mu--set-mu4e-include-related opts)))
(mu4e--server-find
rewritten-expr
mu4e-search-threads
mu4e-search-sort-field
mu4e-search-sort-direction
mu4e-search-results-limit
mu4e-search-skip-duplicates
mu4e-search-include-related))
(while (or (string-empty-p (buffer-substring (point-min) (point-max)))
(equal (buffer-substring (point-min) (+ (point-min) (length mu4e~search-message))) mu4e~search-message)
(not (or (equal (buffer-substring (- (point-max) (length mu4e~no-matches)) (point-max)) mu4e~no-matches) (equal (buffer-substring (- (point-max) (length mu4e~end-of-results)) (point-max)) mu4e~end-of-results))))
(sleep-for 0.005))))))))
(defun consult-mu--execute-all-marks (&optional no-confirmation)
"Execute the actions for all marked messages in `consult-mu-headers-buffer-name' buffer.
If NO-CONFIRMATION is non-nil, don't ask user for confirmation.
This is similar to `mu4e-mark-execute-all' but, with buffer/window handling set accordingly for consult-mu.
"
(interactive "P")
(when-let* ((buf (get-buffer consult-mu-headers-buffer-name)))
(with-current-buffer buf
(when (eq major-mode 'mu4e-headers-mode)
(mu4e--mark-in-context
(let* ((marknum (mu4e-mark-marks-num)))
(unless (zerop marknum)
(pop-to-buffer buf)
(unless (one-window-p) (delete-other-windows))
(mu4e-mark-execute-all no-confirmation)
(quit-window))))))))
(defun consult-mu--headers-goto-message-id (msgid)
"Jumps to message with MSGID
in `consult-mu-headers-buffer-name' buffer."
(when-let ((buffer consult-mu-headers-buffer-name))
(with-current-buffer buffer
(setq mu4e-view-buffer-name consult-mu-view-buffer-name)
(mu4e-headers-goto-message-id msgid))))
(defun consult-mu--get-message-by-id (msgid)
"Finds the message with MSGID and returns the mu4e MSG plist for it."
(cl-letf* (((symbol-function #'mu4e-view) #'consult-mu--view-msg))
(when-let ((buffer consult-mu-headers-buffer-name))
(with-current-buffer buffer
(setq mu4e-view-buffer-name consult-mu-view-buffer-name)
(mu4e-headers-goto-message-id msgid)
(mu4e-message-at-point)))))
(defun consult-mu--contact-string-to-plist (string)
"Convert STRING for contacts to plist.
STRING is the output form mu command. for example from `mu find query --fields f`
Returns plist with :email and :name keys.
For example
\"John Doe <[email protected]>\"
will be converted to
(:name \"John Doe\" :email \"[email protected]\")
"
(let* ((string (replace-regexp-in-string ">,\s\\|>;\s" ">\n" string))
(list (string-split string "\n" t)))
(mapcar (lambda (item)
(cond
((string-match "\\(?2:.*\\)\s+<\\(?1:.+\\)>" item)
(list :email (or (match-string 1 item) nil) :name (or (match-string 2 item) nil)))
((string-match "^\\(?1:[a-zA-Z0-9\_\.\+\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+\\)" item)
(list :email (or (match-string 1 item) nil) :name nil))
(t
(list :email (format "%s" item) :name nil)))) list)))
(defun consult-mu--contact-name-or-email (contact)
"Retrieve name or email of CONTACT.
Looks at the contact plist (e.g. (:name \"John Doe\" :email \"[email protected]\") ) and returns the name. If the name is missing returns the email address.
"
(cond
((stringp contact)
contact)
((listp contact)
(mapconcat (lambda (item) (or (plist-get item :name) (plist-get item :email) "")) contact ","))))
(defun consult-mu--headers-template ()
"Make headers template using `consult-mu-headers-template'."
(if (and consult-mu-headers-template (functionp consult-mu-headers-template))
(funcall consult-mu-headers-template)
consult-mu-headers-template))
(defun consult-mu--expand-headers-template (msg string)
"Expands STRING to create a custom header format for MSG.
See `consult-mu-headers-template' for explanation of the format of STRING.
"
(cl-loop with str = nil
for c in (string-split string "%" t)
concat (concat (pcase (substring c 0 1)
("f" (let ((sender (consult-mu--contact-name-or-email (plist-get msg :from)))
(length (string-to-number (substring c 1 nil))))
(if sender
(propertize (if (> length 0) (consult-mu--set-string-width sender length) sender) 'face 'consult-mu-sender-face))))
("t" (let ((receiver (consult-mu--contact-name-or-email (plist-get msg :to)))
(length (string-to-number (substring c 1 nil))))
(if receiver
(propertize (if (> length 0) (consult-mu--set-string-width receiver length) receiver) 'face 'consult-mu-sender-face))))
("s" (let ((subject (plist-get msg :subject))
(length (string-to-number (substring c 1 nil))))
(if subject
(propertize (if (> length 0) (consult-mu--set-string-width subject length) subject) 'face 'consult-mu-subject-face))))
("d" (let ((date (format-time-string "%a %d %b %y" (plist-get msg :date)))
(length (string-to-number (substring c 1 nil))))
(if date
(propertize (if (> length 0) (consult-mu--set-string-width date length) date) 'face 'consult-mu-date-face))))
("p" (let ((priority (plist-get msg :priority))
(length (string-to-number (substring c 1 nil))))
(if priority
(propertize (if (> length 0) (consult-mu--set-string-width (format "%s" priority) length) (format "%s" priority)) 'face 'consult-mu-size-face))))
("z" (let ((size (file-size-human-readable (plist-get msg :size)))
(length (string-to-number (substring c 1 nil))))
(if size
(propertize (if (> length 0) (consult-mu--set-string-width size length) size) 'face 'consult-mu-size-face))))
("i" (let ((id (plist-get msg :message-id))
(length (string-to-number (substring c 1 nil))))
(if id
(propertize (if (> length 0) (consult-mu--set-string-width id length) id) 'face 'consult-mu-default-face))))
("g" (let ((flags (plist-get msg :flags))
(length (string-to-number (substring c 1 nil))))
(if flags
(propertize (if (> length 0) (consult-mu--set-string-width (format "%s" flags) length) (format "%s" flags)) 'face 'consult-mu-flags-face))))
("G" (let ((flags (plist-get msg :flags))
(length (string-to-number (substring c 1 nil))))
(if flags
(propertize (if (> length 0) (consult-mu--set-string-width (format "%s" (mu4e~headers-flags-str flags)) length) (format "%s" (mu4e~headers-flags-str flags))) 'face 'consult-mu-flags-face))))
("x" (let ((tags (plist-get msg :tags))
(length (string-to-number (substring c 1 nil))))
(if tags
(propertize (if (> length 0) (consult-mu--set-string-width tags length) tags) 'face 'consult-mu-tags-face) nil)))
("c" (let ((cc (consult-mu--contact-name-or-email (plist-get msg :cc)))
(length (string-to-number (substring c 1 nil))))
(if cc
(propertize (if (> length 0) (consult-mu--set-string-width cc length) cc) 'face 'consult-mu-tags-face))))
("h" (let ((bcc (consult-mu--contact-name-or-email (plist-get msg :bcc)))
(length (string-to-number (substring c 1 nil))))
(if bcc
(propertize (if (> length 0) (consult-mu--set-string-width bcc length) bcc) 'face 'consult-mu-tags-face))))
("r" (let ((changed (format-time-string "%a %d %b %y" (plist-get msg :changed)))
(length (string-to-number (substring c 1 nil))))
(if changed
(propertize (if (> length 0) (consult-mu--set-string-width changed length) changed) 'face 'consult-mu-tags-face))))
(_ nil))
" ")))
(defun consult-mu--quit-header-buffer ()
"Quits `consult-mu-headers-buffer-name' buffer."
(save-mark-and-excursion
(when-let* ((buf (get-buffer consult-mu-headers-buffer-name)))
(with-current-buffer buf
(if (eq major-mode 'mu4e-headers-mode)
(mu4e-mark-handle-when-leaving)
(quit-window t)
;; clear the decks before going to the main-view
(mu4e--query-items-refresh 'reset-baseline))))))
(defun consult-mu--quit-view-buffer ()
"Quits `consult-mu-view-buffer-name' buffer."
(when-let* ((buf (get-buffer consult-mu-view-buffer-name)))
(with-current-buffer buf
(if (eq major-mode 'mu4e-view-mode)
(mu4e-view-quit)))))
(defun consult-mu--quit-main-buffer ()
"Quits 'mu4e-main-buffer-name' buffer."
(when-let* ((buf (get-buffer mu4e-main-buffer-name)))
(with-current-buffer buf
(if (eq major-mode 'mu4e-main-mode)
(mu4e-quit)))))
(defun consult-mu--lookup ()
"Lookup function for `consult-mu' or `consult-mu-async' minibuffer candidates.
This is passed as LOOKUP to `consult--read' on candidates and is used to format the output when a candidate is selected."
(lambda (sel cands &rest args)
(let* ((info (cdr (assoc sel cands)))
(msg (plist-get info :msg))
(subject (plist-get msg :subject)))
(cons subject info))))
(defun consult-mu--group-name (cand)
"Gets the group name of CAND using `consult-mu-group-by'
See `consult-mu-group-by' for details of grouping options.
"
(let* ((msg (get-text-property 0 :msg cand))
(group (or consult-mu--override-group consult-mu-group-by))
(field (if (not (keywordp group)) (intern (concat ":" (format "%s" group))) group)))
(pcase field
(:date (format-time-string "%a %d %b %y" (plist-get msg field)))
(:from (cond
((listp (plist-get msg field))
(mapconcat (lambda (item) (or (plist-get item :name) (plist-get item :email))) (plist-get msg field) ";"))
(stringp (plist-get msg field) (plist-get msg field))))
(:to (cond
((listp (plist-get msg field))
(mapconcat (lambda (item) (or (plist-get item :name) (plist-get item :email))) (plist-get msg field) ";"))
(stringp (plist-get msg field) (plist-get msg field))))
(:changed (format-time-string "%a %d %b %y" (plist-get msg field)))
(:datetime (format-time-string "%F %r" (plist-get msg :date)))
(:time (format-time-string "%X" (plist-get msg :date)))
(:year (format-time-string "%Y" (plist-get msg :date)))
(:month (format-time-string "%B" (plist-get msg :date)))
(:day-of-week (format-time-string "%A" (plist-get msg :date)))
(:day (format-time-string "%A" (plist-get msg :date)))
(:week (format-time-string "%V" (plist-get msg :date)))
(:size (file-size-human-readable (plist-get msg field)))
(:flags (format "%s" (plist-get msg field)))
(:tags (format "%s" (plist-get msg field)))