-
Notifications
You must be signed in to change notification settings - Fork 27
/
citre-ui-peek.el
1555 lines (1367 loc) · 57.1 KB
/
citre-ui-peek.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
;;; citre-ui-peek.el --- Go down the rabbit hole without leaving current buffer -*- lexical-binding: t -*-
;; Copyright (C) 2020 Hao Wang
;; Author: Hao Wang <[email protected]>
;; Maintainer: Hao Wang <[email protected]>
;; Created: 23 Nov 2020
;; Keywords: convenience, tools
;; Homepage: https://github.com/universal-ctags/citre
;; Version: 0.4.1
;; Package-Requires: ((emacs "26.1"))
;; This file is NOT part of GNU Emacs.
;; This program 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 program 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 program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; UI library for `citre-peek'.
;;; Code:
;; To see the outline of this file, run M-x outline-minor-mode and
;; then press C-c @ C-t. To also show the top-level functions and
;; variable declarations in each section, run M-x occur with the
;; following query: ^;;;;* \|^(
;;;; Libraries
(require 'citre-common-tag)
(require 'citre-common-util)
(require 'color)
(require 'fringe)
;; We use this function for integration with the package "clue". We don't
;; require it as it's not necessary for citre-peek to work.
(declare-function clue-copy-location "clue" (file line &optional project))
(declare-function clue-paste-location "clue" (file line &optional project))
;;;; User options
;;;;; Behavior
(defcustom citre-peek-auto-restore-after-jump t
"Non-nil means restore session after `citre-peek-jump'."
:type 'boolean
:group 'citre)
(defcustom citre-peek-backward-in-chain-after-jump nil
"Non-nil means move backward in the chain after `citre-peek-jump'.
This means after you jump to a tag, the peek window will show
where it's used/called/referenced.
This only works when `citre-peek-auto-restore-after-jump' is
non-nil."
:type 'boolean
:group 'citre)
;;;;; Size of peek window
(defcustom citre-peek-file-content-height 12
"Number of lines displaying file contents in the peek window."
:type 'integer
:group 'citre)
(defcustom citre-peek-tag-list-height 3
"Number of tags displayed in the peek window."
:type 'integer
:group 'citre)
(defalias 'citre-peek-definitions-height 'citre-peek-tag-list-height)
(make-obsolete 'citre-peek-definitions-height 'citre-peek-tag-list-height
"0.3")
;;;;; Keybindings
(defcustom citre-peek-ace-keys '(?a ?s ?d ?f ?j ?k ?l ?\;)
"Ace keys used for `citre-peek-through' and `citre-ace-peek'."
:type '(repeat :tag "Keys" character)
:group 'citre)
(defcustom citre-peek-ace-cancel-keys '(?\C-g ?q)
"Keys used for cancel an ace session."
:type '(repeat :tag "Keys" character)
:group 'citre)
(defcustom citre-peek-ace-pick-symbol-at-point-keys '(?\C-m)
"Keys used for pick symbol at point in `citre-ace-peek'."
:type '(repeat :tag "Keys" character)
:group 'citre)
(defcustom citre-peek-keymap
(let ((map (make-sparse-keymap)))
;; Browse file
(define-key map (kbd "M-n") 'citre-peek-next-line)
(define-key map (kbd "M-p") 'citre-peek-prev-line)
;; Browse in the tag list
(define-key map (kbd "M-N") 'citre-peek-next-tag)
(define-key map (kbd "M-P") 'citre-peek-prev-tag)
;; Browse in the history
(define-key map (kbd "<right>") 'citre-peek-chain-forward)
(define-key map (kbd "<left>") 'citre-peek-chain-backward)
(define-key map (kbd "<up>") 'citre-peek-prev-branch)
(define-key map (kbd "<down>") 'citre-peek-next-branch)
;; Modify history
(define-key map (kbd "M-l p") 'citre-peek-through)
(define-key map (kbd "M-l r") 'citre-peek-through-reference)
(define-key map (kbd "M-l d") 'citre-peek-delete-branch)
(define-key map (kbd "M-l D") 'citre-peek-delete-branches)
;; Rearrange tag list
(define-key map (kbd "S-<up>") 'citre-peek-move-current-tag-up)
(define-key map (kbd "S-<down>") 'citre-peek-move-current-tag-down)
(define-key map (kbd "M-l f") 'citre-peek-make-current-tag-first)
;; Jump
(define-key map (kbd "M-l j") 'citre-peek-jump)
;; Abort
(define-key map [remap keyboard-quit] 'citre-peek-abort)
map)
"Keymap used for `citre-peek' sessions."
:type 'keymap
:group 'citre)
;;;;; Appearance
(defcustom citre-peek-fill-fringe t
"Non-nil means to fill the fringes of the peek window with a vertical border.
Set this to nil if you have line numbers turned on for a better appearance."
:type 'boolean
:group 'citre)
(defcustom citre-peek-use-dashes-as-horizontal-border nil
"Non-nil means always use dashes as horizontal borders of the peek window.
On graphic display, Citre uses a thin line as horizontal borders,
but it will occupy a whole line height when line numbers are
displayed. In this situation, set this to t for a better
appearance."
:type 'boolean
:group 'citre)
;;;;; Faces
(defface citre-peek-border-face
'((((background light))
:height 15 :background "#ffcbd3" :extend t)
(t
:height 15 :background "#db8e93" :extend t))
"Face used for borders of peek windows.
You can customize the appearance of the borders by setting the
height and background properties of this face.
In terminal Emacs, a dashed pattern is used as the border, and
only the background property of this face is used, as the color
of the dashes."
:group 'citre)
(defface citre-peek-ace-str-face
'((((background light))
:foreground "#dddddd" :background "#666666")
(t
:foreground "#222222" :background "#c0c0c0"))
"Face used for ace strings."
:group 'citre)
;;;;; Annotations
(defcustom citre-peek-ellipsis
"…"
"Ellipsis used when truncating long definition lines."
:type 'string
:group 'citre)
(defcustom citre-peek-peeked-through-tag-prefix
(propertize "* " 'face 'warning)
"The prefix for tag nodes in which you peeked through."
:type 'string
:group 'citre)
(defalias 'citre-peek-peeked-through-definition-prefix
'citre-peek-peeked-through-tag-prefix)
(make-obsolete 'citre-peek-peeked-through-definition-prefix
'citre-peek-peeked-through-tag-prefix
"0.3")
(defcustom citre-peek-root-symbol-str
"·"
"The string used to represent root symbol in the chain."
:type 'string
:group 'citre)
(defcustom citre-peek-chain-separator
;; NOTE: In terminal Emacs, sometimes the chain is not updated properly when
;; there's unicode char in it. I think it's probably not a problem of Emacs
;; but the display update of the terminal itself. Put a `redraw-frame' call
;; in `citre-peek--update-display' solves the problem, but it creates a
;; visual flick. I believe unicode chars in the middle of a line cause the
;; problem, so this may also happen to the file content and tag list.
(propertize (if (display-graphic-p) " → " " - ")
'face 'font-lock-function-name-face)
"The separator in the chain where it doesn't branch."
:type 'string
:group 'citre)
(defcustom citre-peek-branch-separator
(propertize " < " 'face 'font-lock-function-name-face)
"The separator in the chain where it branches."
:type 'string
:group 'citre)
(defface citre-peek-current-symbol-face
'((t :inherit warning :bold t))
"The face used for the current symbol in the chain."
:group 'citre)
(defcustom citre-peek-current-symbol-prefix
"["
"The prefix for the current symbol in the chain."
:type 'string
:group 'citre)
(defcustom citre-peek-current-symbol-suffix
"]"
"The suffix for the current symbol in the chain."
:type 'string
:group 'citre)
(defface citre-peek-symbol-face
'((t :inherit default))
"The face used for non-current symbols in the chain."
:group 'citre)
;;;; Helpers
;;;;; Lists
(defun citre--delete-nth (n list)
"Delete Nth element in LIST and return the modified list."
(setf (nthcdr n list) (nthcdr (1+ n) list))
list)
(defun citre--insert-nth (newelt n list)
"Insert NEWELT to the Nth position in LIST.
The modified list is returned."
(setf (nthcdr n list) (push newelt (nthcdr n list)))
list)
;;;;; Ace jump
(defun citre--after-comment-or-str-p ()
"Non-nil if current position is after/in a comment or string."
(unless (bobp)
(let* ((pos (1- (point))))
;; `syntax-ppss' is not always reliable, so we only use it when font lock
;; mode is disabled.
(if font-lock-mode
(when-let* ((pos-faces (get-text-property pos 'face)))
(unless (listp pos-faces)
(setq pos-faces (list pos-faces)))
;; Use `cl-subsetp' rather than `cl-intersection', so that
;; highlighted symbols in docstrings/comments can be captured. For
;; example, symbols in Elisp comments/docstrings has both
;; `font-lock-constant-face' and `font-lock-comment/doc-face'.
(cl-subsetp pos-faces
'(font-lock-comment-face
font-lock-comment-delimiter-face
font-lock-doc-face
font-lock-string-face)))
(save-excursion
(or (nth 4 (syntax-ppss pos))
(nth 3 (syntax-ppss pos))))))))
(defun citre--search-symbols (line)
"Search for symbols from current position to LINEs after.
The search jumps over comments/strings.
The returned value is a list of cons pairs (START . END), the
start/end position of each symbol. Point will not be moved."
(let ((bound (save-excursion
(forward-line (1- line))
(line-end-position)))
(symbol-list))
(save-excursion
(cl-loop
while
(forward-symbol 1)
do
(when (> (point) bound)
(cl-return))
(unless (citre--after-comment-or-str-p)
(push (cons (save-excursion
(forward-symbol -1)
(point))
(point))
symbol-list))))
(nreverse symbol-list)))
(defun citre--ace-key-seqs (n)
"Make ace key sequences for N symbols.
N can be the length of the list returned by
`citre--search-symbols'. The keys used are
`citre-peek-ace-keys'."
(unless (and (listp citre-peek-ace-keys)
(null (cl-remove-if #'integerp citre-peek-ace-keys))
(eq (cl-remove-duplicates citre-peek-ace-keys)
citre-peek-ace-keys))
(user-error "Invalid `citre-peek-ace-keys'"))
(let* ((key-num (length citre-peek-ace-keys))
(key-seq-length (pcase n
(0 0)
(1 1)
;; Though `log' is a float-point operation, this is
;; accurate for sym-num in a huge range.
(_ (ceiling (log n key-num)))))
(key-seq (make-list n nil))
nth-ace-key)
(dotimes (nkey key-seq-length)
(setq nth-ace-key -1)
(dotimes (nsym n)
(when (eq (% nsym (expt key-num nkey)) 0)
(setq nth-ace-key (% (1+ nth-ace-key) key-num)))
(push (nth nth-ace-key citre-peek-ace-keys) (nth nsym key-seq))))
key-seq))
(defun citre--pop-ace-key-seqs (seqs char)
"Modify ace key sequences SEQS as CHAR is pressed.
This sets elements in SEQS which not begin with CHAR to nil, and
pop the element which begin with CHAR. When the only non-nil
element in seqs is poped, this returns its index, as the element
is hit by user input.
The modified SEQS is returned. When CHAR is not the car of any
element in SEQS, this does nothing, and returns the original
list."
(if (not (memq char (mapcar #'car seqs)))
seqs
(let (last-poped-idx)
(dotimes (n (length seqs))
(if (eq (car (nth n seqs)) char)
(progn
(pop (nth n seqs))
(setq last-poped-idx n))
(setf (nth n seqs) nil)))
(if (null (cl-remove-if #'null seqs))
last-poped-idx
seqs))))
(defun citre--attach-ace-str (str sym-bounds bound-offset ace-seqs)
"Return a copy of STR with ace strings attached.
SYM-BOUNDS specifies the symbols in STR, as returned by
`citre--search-symbols'. BOUND-OFFSET is the starting point of
STR in the buffer. ACE-SEQS is the ace key sequences, as
returned by `citre--ace-key-seqs' or `citre--pop-ace-key-seqs'.
The beginnings of each symbol are replaced by ace strings with
`citre-ace-string-face' attached."
(let* ((nsyms (length sym-bounds))
(new-str (copy-sequence str)))
(dotimes (n nsyms)
(when (nth n ace-seqs)
(let* ((beg (- (car (nth n sym-bounds)) bound-offset))
(end (- (cdr (nth n sym-bounds)) bound-offset))
(ace-seq (nth n ace-seqs))
(ace-str-len (min (length ace-seq) (- end beg))))
(dotimes (idx ace-str-len)
(aset new-str (+ beg idx) (nth idx ace-seq)))
(put-text-property beg (+ beg ace-str-len)
'face 'citre-peek-ace-str-face new-str))))
new-str))
(defvar citre--ace-ov nil
"Overlays for ace strings.")
(defun citre--clean-ace-ov ()
"Cleanup overlays for ace jump."
(dolist (ov citre--ace-ov)
(delete-overlay ov))
(setq citre--ace-ov nil))
(defun citre--attach-ace-overlay (sym-bounds ace-seqs)
"Setup overlay in current buffer for ace strings.
SYM-BOUNDS specifies the annotated symbols, as returned by
`citre--search-symbols'. ACE-SEQS is the ace key sequences, as
returned by `citre--ace-key-seqs' or `citre--pop-ace-key-seqs'."
(let* ((nsyms (length sym-bounds))
ov)
(citre--clean-ace-ov)
(dotimes (n nsyms)
(when (nth n ace-seqs)
(let* ((beg (car (nth n sym-bounds)))
(end (cdr (nth n sym-bounds)))
(ace-seq (nth n ace-seqs))
(end (min end (+ beg (length ace-seq)))))
(setq ov (make-overlay beg end))
(overlay-put ov 'window (selected-window))
(overlay-put ov 'face 'citre-peek-ace-str-face)
(overlay-put ov 'display (substring
(mapconcat #'char-to-string ace-seq "")
0 (- end beg)))
(push ov citre--ace-ov))))))
;;;;; Display
(defun citre--fit-line (str)
"Fit STR in current window.
When STR is too long, it will be truncated, and
`citre-peek-ellipsis' is added at the end."
(let ((limit (window-max-chars-per-line)))
(if (> (length str) limit)
(concat (truncate-string-to-width
str
(- limit (string-width citre-peek-ellipsis)))
citre-peek-ellipsis)
str)))
;; Ref: https://www.w3.org/TR/WCAG20/#relativeluminancedef
(defun citre--color-srgb-to-rgb (c)
"Convert an sRGB component C to an RGB one."
(if (<= c 0.03928)
(/ c 12.92)
(expt (/ (+ c 0.055) 1.055) 2.4)))
(defun citre--color-rgb-to-srgb (c)
"Convert an RGB component C to an sRGB one."
(if (<= c (/ 0.03928 12.92))
(* c 12.92)
(- (* 1.055 (expt c (/ 1 2.4))) 0.055)))
(defun citre--color-blend (c1 c2 alpha)
"Blend two colors C1 and C2 with ALPHA.
C1 and C2 are hexadecimal strings. ALPHA is a number between 0.0
and 1.0 which is the influence of C1 on the result.
The blending is done in the sRGB space, which should make ALPHA
feels more linear to human eyes."
(pcase-let ((`(,r1 ,g1 ,b1)
(mapcar #'citre--color-rgb-to-srgb
(color-name-to-rgb c1)))
(`(,r2 ,g2 ,b2)
(mapcar #'citre--color-rgb-to-srgb
(color-name-to-rgb c2)))
(blend-and-to-rgb
(lambda (x y)
(citre--color-srgb-to-rgb
(+ (* alpha x)
(* (- 1 alpha) y))))))
(color-rgb-to-hex
(funcall blend-and-to-rgb r1 r2)
(funcall blend-and-to-rgb g1 g2)
(funcall blend-and-to-rgb b1 b2)
2)))
(defun citre--add-face (str face)
"Add FACE to STR, and return it.
This is mainly for displaying STR in an overlay. For example, if
FACE specifies background color, then STR will have that
background color, with all other face attributes preserved.
`default' face is appended to make sure the display in overlay is
not affected by its surroundings."
(let ((len (length str)))
(add-face-text-property 0 len face nil str)
(add-face-text-property 0 len 'default 'append str)
str))
;;;; Internals
;;;;; Data structures
;; These are data structures that handles code reading history in citre-peek.
;; Let's have a brief description of the basic concepts first:
;; When you peek a symbol, you create a *tag list* of tags related to it (they
;; may be its definitions/references/etc.). Each element in a tag list is
;; called a *tag node*, which has 2 important slots: one is the tag itself, and
;; another is a list called *branches*, which we'll soon explain.
;; In a *peek session*, you are always browsing a tag node. When you peek
;; through a symbol, a new tag list is created. To keep a complete history of
;; your code reading session, this tag list is pushed into the branches of the
;; current browsed tag node.
;; The history of a peek session is a tree like this:
;; - tag list
;; - tag node 1
;; - tag list A
;; - tag list B
;; - tag node 2
;; - tag list C
;; - tag node 3
;; ...
(cl-defstruct (citre-peek--session
(:constructor nil)
(:constructor
citre-peek--session-create
(root-list
depth
&optional name))
(:copier nil))
"Citre-peek session."
(root-list
nil
:documentation
"The root tag list in this peek session."
:type "citre-peek--tag-list")
(depth
nil
:documentation
"The depth of currently browsed tag list in this session."
:type "integer")
(name
nil
:documentation
"The name of this session."
:type "nil or string"))
(cl-defstruct (citre-peek--tag-node
(:constructor nil)
(:constructor citre-peek--tag-node-create
(tag))
(:copier nil))
"Tag node in code reading history in citre-peek."
(tag
nil
:documentation
"The tag of this node."
:type "tag (a hash table)")
(branches
nil
:documentation
"A list of tag lists under this node.
We don't keep a record of current branch because we make sure
it's always the first one, by scrolling this list."
:type "list of citre-peek-tag-list")
(base-marker
nil
:documentation
"The marker at the start of the line of the tag location.
We use a marker to deal with possible buffer update (e.g., peek
the definition of a symbol, while writing code above its
position.)"
:type "marker")
(line-offset
0
:documentation
"The offset of current peeked position to base-marker."
:type "integer"))
(cl-defstruct (citre-peek--tag-list
(:constructor nil)
(:constructor
citre-peek--tag-list-create
(tags
&aux (nodes (mapcar #'citre-peek--tag-node-create tags))))
(:copier nil))
"List of tags used in citre-peek."
(index
0
:documentation
"The index of current browsed tag node in this list."
:type "integer")
(nodes
nil
:documentation
"A list of tag nodes in this tag list."
:type "list of citre-peek--tag-node"))
;;;;; State variables
;; NOTE: Here's a list of when should each state variable be changed. Keep
;; these in mind when you are developing citre-peek related commands.
;;
;; - `citre-peek--displayed-tags-interval': Set this for a new peek session,
;; when browsing the tag list, and when moving in the chain.
;;
;; - `citre-peek--symbol-bounds', `citre-peek--ace-seqs': Set these for ace
;; jump, and clean it up afterwards.
;;
;; - `citre-peek--content-update': Set this to t when the content in the peek
;; window is updated. This variable is for preventing recalculate the
;; content after every command.
;;
;; We know our currently browsed tag list in a session by the `depth' slot in
;; the `citre-peek--session'. It can be modified by
;; `citre-peek--session-depth-add':
;;
;; - Set it to 0 or 1 for a new peek session (see `citre-peek--make-session').
;;
;; - Modify it when moving forward/backward in the chain (including peeking
;; through). Make sure it's >= 0 and <= maximum possible depth.
;;
;; These variables are not going to change much, and newly added commands may
;; not need to care about them:
;;
;; - `citre-peek--session-root-list': Set this only for a new peek session.
;;
;; - `citre-peek--temp-buffer-alist': Add pairs to this when peeking a new
;; non-visiting file, and clean it up when abort current peek session (i.e.,
;; when disabling `citre-mode').
;;
;; - `citre-peek--ov', `citre-peek--bg'(-alt, -selected): You shouldn't use
;; them directly. These are controlled by `citre-peek--mode', and it makes
;; sure that the overlay is cleaned up correctly. When other state variables
;; are set up, enable `citre-peek--mode' sets up the UI, and disable
;; `citre-peek--mode' hides the UI.
(defvar citre-peek--current-session nil
"Current peek session.")
(defvar citre-peek--saved-sessions nil
"Saved peek sessions.")
(defvar citre-peek--displayed-tags-interval nil
"The interval of displayed tags in currently browsed tag list.
This is a cons pair, its car is the index of the first displayed
tag, and cdr the index of the last one.")
(defvar citre-peek--temp-buffer-alist nil
"Files and their temporary buffers that don't exist before peeking.
Its keys are file paths, values are buffers. The buffers will be
killed after disabling `citre-peek--mode'.")
(defvar citre-peek--symbol-bounds nil
"Symbol bounds for ace jump.
Its car is the bound offset, i.e., the starting point of the
region to perform ace jump on. Its cdr is a list of the symbol
bounds as returned by `citre--search-symbols'.")
(defvar citre-peek--ace-seqs nil
"Ace key sequences for ace jump.")
(defvar citre-peek--ov nil
"Overlay used to display the citre-peek UI.")
(defvar citre-peek--content-update nil
"Non-nil means the content in the peek window is updated.")
(defvar citre-peek--bg nil
"Background color used for file contents when peeking.")
(defvar citre-peek--bg-alt nil
"Background color for unselected tags when peeking.")
(defvar citre-peek--bg-selected nil
"Background color for selected tags when peeking.")
(define-minor-mode citre-peek--mode
"Mode for `citre-peek'.
This mode is created merely for handling the UI (display, keymap,
etc.), and is not for interactive use. Users should use commands
like `citre-peek', `citre-peek-abort', `citre-peek-restore',
which take care of setting up other things."
:keymap citre-peek-keymap
(cond
(citre-peek--mode
(when citre-peek--ov (delete-overlay citre-peek--ov))
(setq citre-peek--ov
(let ((ov-pos (line-end-position)))
(make-overlay ov-pos ov-pos)))
(overlay-put citre-peek--ov 'window (selected-window))
(let* ((bg-mode (frame-parameter nil 'background-mode))
(bg-unspecified-p (string= (face-background 'default)
"unspecified-bg"))
(bg (cond
((and bg-unspecified-p (eq bg-mode 'dark)) "#333333")
((and bg-unspecified-p (eq bg-mode 'light)) "#dddddd")
(t (face-background 'default)))))
(cond
((eq bg-mode 'dark)
(setq citre-peek--bg (citre--color-blend "#ffffff" bg 0.03))
(setq citre-peek--bg-alt (citre--color-blend "#ffffff" bg 0.2))
(setq citre-peek--bg-selected (citre--color-blend "#ffffff" bg 0.4)))
(t
(setq citre-peek--bg (citre--color-blend "#000000" bg 0.02))
(setq citre-peek--bg-alt (citre--color-blend "#000000" bg 0.12))
(setq citre-peek--bg-selected
(citre--color-blend "#000000" bg 0.06)))))
(setq citre-peek--content-update t)
(add-hook 'post-command-hook #'citre-peek--update-display nil 'local))
(t
(when citre-peek--ov (delete-overlay citre-peek--ov))
(mapc (lambda (pair)
(kill-buffer (cdr pair)))
citre-peek--temp-buffer-alist)
(setq citre-peek--temp-buffer-alist nil)
(setq citre-peek--ov nil)
(setq citre-peek--bg nil)
(setq citre-peek--bg-alt nil)
(setq citre-peek--bg-selected nil)
;; In case they are not cleaned up by `citre-peek-through'
(setq citre-peek--ace-seqs nil)
(setq citre-peek--symbol-bounds nil)
;; We don't clean up `citre-peek--session-root-list',
;; `citre-peek--depth-in-root-list' and
;; `citre-peek--displayed-tags-interval', so we can restore a session
;; later.
(remove-hook 'post-command-hook #'citre-peek--update-display 'local))))
(defun citre-peek--error-if-not-peeking ()
"Throw an error if not in a peek session."
(unless citre-peek--mode
(user-error "Not in a peek session")))
;;;;; Handle temp file buffer
(defun citre-peek--find-file-buffer (path)
"Return the buffer visiting file PATH.
PATH is an absolute path. This is like `find-buffer-visiting',
but it also searches `citre-peek--temp-buffer-alist', so it can
handle temporary buffers created during peeking.
When the file is not opened, this creates a temporary buffer for
it. These buffers will be killed afterwards by `citre-abort'.
When PATH doesn't exist, this returns nil."
(when (citre-non-dir-file-exists-p path)
(setq path (file-truename path))
(or (alist-get path citre-peek--temp-buffer-alist
nil nil #'equal)
(find-buffer-visiting path)
(let ((buf (citre-file-content-buffer path 'set-major-mode)))
(with-current-buffer buf
(setq default-directory (file-name-directory path)))
(push (cons path buf) citre-peek--temp-buffer-alist)
buf))))
;;;;; Methods for `citre-peek--tag-node'
(defun citre-peek--get-base-marker (node)
"Return the base marker of NODE.
NODE is an instance of `citre-peek--tag-node'. The value of
the `base-marker' slot is returned, or if it doesn't exist,
calculate the mark using the tag, write it to the `base-marker'
slot, then return it.
Nil is returned when the file in the tag doesn't exist."
(or (let ((marker (citre-peek--tag-node-base-marker node)))
;; When the buffer of the file is killed, `marker' could point to
;; nowhere, so we check it by `marker-position'.
(when (and marker (marker-position marker))
marker))
(let* ((tag (citre-peek--tag-node-tag node))
(buf (citre-peek--find-file-buffer
(citre-get-tag-field 'ext-abspath tag)))
(marker (when buf
(with-current-buffer buf
(save-excursion
(goto-char (citre-locate-tag tag))
(point-marker))))))
(when marker
(setf (citre-peek--tag-node-base-marker node) marker)
marker))))
(defun citre-peek--get-buf-and-pos (node)
"Get the buffer and position from NODE.
NODE is an instance of `citre-peek--tag-node'. Its
`base-marker' and `line-offset' slots are used, or initialized if
they are unset. `line-offset' is limited so it doesn't go beyond
the beginning/end of buffer.
A cons pair (BUF . POINT) is returned. If the file in the tag
doesn't exist, these 2 fields are all nil."
(let* ((path (citre-get-tag-field 'ext-abspath
(citre-peek--tag-node-tag node)))
(base-marker (citre-peek--get-base-marker node))
(line-offset (citre-peek--tag-node-line-offset node))
(buf (citre-peek--find-file-buffer path))
offset-overflow
point)
(when buf
(with-current-buffer buf
(save-excursion
(save-restriction
(widen)
;; If `buf' is non-nil, base-marker will be a valid marker, so we
;; don't check it.
(goto-char base-marker)
(setq offset-overflow
(forward-line line-offset))
;; If the buffer doesn't have trailing newline, `forward-line' in
;; the last line will take us to the end of line and count it as a
;; successful move. No, we want to always be at the beginning of
;; line.
(when (and (eolp) (not (bolp)))
(beginning-of-line)
(cl-incf offset-overflow))
(when (not (eq offset-overflow 0))
(setf (citre-peek--tag-node-line-offset node)
(+ line-offset (- offset-overflow))))
(setq point (point))))))
(cons buf point)))
(defun citre-peek--get-content (node)
"Get file contents for peeking NODE.
NODE is an instance of `citre-peek--tag-node'.
`citre-peek-file-content-height' specifies the number of lines to
get.
This also modifies the `line-offset' slot of NODE for letting it
not go beyond the start/end of the file."
(pcase-let ((`(,buf . ,pos) (citre-peek--get-buf-and-pos node)))
(if buf
(with-current-buffer buf
(save-excursion
(let ((beg nil)
(end nil))
(save-excursion
;; If `buf' is non-nil, base-marker will be a valid marker, so
;; we don't check it.
(goto-char pos)
(setq beg (point))
(forward-line (1- citre-peek-file-content-height))
(setq end (line-end-position))
(font-lock-fontify-region beg end)
(concat (buffer-substring beg end) "\n")))))
(propertize "This file doesn't exist.\n" 'face 'error))))
(defun citre-peek--line-forward (n &optional node)
"Scroll the current browsed position in NODE N lines forward.
NODE is an instance of `citre-peek--tag-node', N can be
negative. When NODE is nil, the currently browsed node is
used.
Note: `citre-peek--get-buf-and-pos' could further modify the
`citre-line-offset' property of current location. That function
is responsible for not letting it get beyond the start/end of the
file."
(let* ((node (or node (citre-peek--current-tag-node)))
(line-offset (citre-peek--tag-node-line-offset node)))
(setf (citre-peek--tag-node-line-offset node)
(+ line-offset n))
(setq citre-peek--content-update t)))
;;;;; Methods for `citre-peek--tag-list'
(defun citre-peek--tag-list-length (taglist)
"Return the number of nodes in TAGLIST.
TAGLIST is an instance of `citre-peek--tag-list'."
(length (citre-peek--tag-list-nodes taglist)))
(defun citre-peek--current-node-in-tag-list (taglist)
"Return the currently browsed tag node in TAGLIST.
TAGLIST is an instance of `citre-peek--tag-list'."
(nth (citre-peek--tag-list-index taglist)
(citre-peek--tag-list-nodes taglist)))
(defun citre-peek--current-symbol-in-tag-list (taglist)
"Return the name field of currently browsed tag node in TAGLIST.
TAGLIST is an instance of `citre-peek--tag-list'."
(citre-get-tag-field 'name
(citre-peek--tag-node-tag
(citre-peek--current-node-in-tag-list taglist))))
(defun citre-peek--push-branch-in-current-node-in-tag-list
(taglist branch)
"Push BRANCH into the `branches' slot of current browsed node in TAGLIST.
TAGLIST and BRANCH are instances of `citre-peek--tag-list'."
(push branch
(citre-peek--tag-node-branches
(citre-peek--current-node-in-tag-list taglist))))
;;;;; Methods for `citre-peek--session'
(defun citre-peek--session-depth-add (n &optional session)
"Offset the current depth of peek session SESSION by N.
If SESSION is nil, use the currently active session."
(let* ((session (or session citre-peek--current-session))
(depth (citre-peek--session-depth session)))
(setf (citre-peek--session-depth session) (+ depth n))))
;;;;; Find currently browsed item in the tree
;; NOTE: Find the current session using the variable
;; `citre-peek--current-session'.
(defun citre-peek--current-root-list (&optional session)
"Return the root list in a peek session SESSION.
If SESSION is nil, use the currently active session."
(let* ((session (or session citre-peek--current-session)))
(citre-peek--session-root-list session)))
(defun citre-peek--tag-list-at-depth (n &optional session)
"Return the browsed tag list in a peek session SESSION at depth N.
If SESSION is nil, use the currently active session."
(let* ((session (or session citre-peek--current-session))
(taglist (citre-peek--session-root-list session)))
(dotimes (_ n)
(let* ((node (citre-peek--current-node-in-tag-list taglist))
(branches (citre-peek--tag-node-branches node)))
(setq taglist (car branches))))
taglist))
(defun citre-peek--current-tag-list (&optional session)
"Return the currently browsed tag list in a peek session SESSION.
If SESSION is nil, use the currently active session."
(let ((session (or session citre-peek--current-session)))
(citre-peek--tag-list-at-depth
(citre-peek--session-depth session) session)))
(defun citre-peek--tag-node-at-depth (n &optional session)
"Return the browsed tag node in a peek session SESSION at depth N.
If SESSION is nil, use the currently active session."
(citre-peek--current-node-in-tag-list
(citre-peek--tag-list-at-depth n session)))
(defun citre-peek--current-tag-node (&optional session)
"Return the currently browsed tag node in a peek session SESSION.
If SESSION is nil, use the currently active session."
(citre-peek--current-node-in-tag-list
(citre-peek--current-tag-list session)))
;;;;; Create tag lists & sessions
(defun citre-peek--make-tag-list-of-current-location (name)
"Return a tag list of current location.
The tag list is an instance of `citre-peek--tag-list', with its
`nodes' slot only contains one def node pointing to the
current line, and NAME being the name field of the tag.
The returned tag list can be used as the root tag list of the
peek session."
(let* ((tag (citre-make-tag-of-current-location name))
(taglist (citre-peek--tag-list-create (list tag))))
taglist))
(defun citre-peek--make-branch (tags)
"Create a new branch in the peek history.
This maked TAGS a branch of the current tag node."
(unless tags (error "TAGS is nil"))
(let ((branch (citre-peek--tag-list-create tags)))
(citre-peek--push-branch-in-current-node-in-tag-list
(citre-peek--current-tag-list) branch)
(citre-peek--session-depth-add 1)
(citre-peek--setup-displayed-tags-interval branch)))
(defun citre-peek--make-session (tags &optional marker)
"Create a peek session from TAGS.
When MARKER is non-nil, and is in a file buffer, make a tag for
it using the name `citre-peek-root-symbol-str', and make it the
root tag list, then make TAGS a branch of it."
(let ((taglist (citre-peek--tag-list-create tags)))
(if (and marker (buffer-local-value 'buffer-file-name
(marker-buffer marker)))
(save-excursion
(goto-char marker)
(let ((root-list (citre-peek--make-tag-list-of-current-location
citre-peek-root-symbol-str)))
(if taglist
(progn
(citre-peek--push-branch-in-current-node-in-tag-list
root-list taglist)
(citre-peek--session-create root-list 1))
(citre-peek--session-create root-list 0))))
(if taglist (citre-peek--session-create taglist 0)
(error "TAGS is nil")))))
;;;;; Manage session state
(defun citre-peek--setup-displayed-tags-interval (&optional taglist)
"Set `citre-peek--displayed-tags-interval' based on TAGLIST.
TAGLIST is an instance of `citre-peek--tag-list'. The interval
is set so that it doesn't exceeds
`citre-peek-definitions-height', and also fits the number of
nodes in TAGLIST.
When TAGLIST is nil, the currently browsed taglist is used."
(let* ((taglist (or taglist (citre-peek--current-tag-list)))
(len (citre-peek--tag-list-length taglist))
(idx (citre-peek--tag-list-index taglist))
start end lines overflow)
(setq lines (min citre-peek-tag-list-height len))
(setq start idx)
(setq end (+ idx (1- lines)))
(setq overflow (max 0 (- end (1- len))))
(cl-incf start (- overflow))
(cl-incf end (- overflow))
(setq citre-peek--displayed-tags-interval
(cons start end))))
(defun citre-peek--setup-session (session)
"Set up state variables for browsing a peek session SESSION."
(setq citre-peek--current-session session)
(citre-peek--setup-displayed-tags-interval
(citre-peek--current-tag-list session))
(setq citre-peek--content-update t))
(defun citre-peek--def-index-forward (n)
"In a peek window, move N steps forward in the definition list.
N can be negative."
(let* ((taglist (citre-peek--current-tag-list))