Repository navigation
Expand file tree
/
Copy pathai-code-session-link.el
More file actions
2392 lines (2187 loc) · 107 KB
/
Copy pathai-code-session-link.el
File metadata and controls
2392 lines (2187 loc) · 107 KB
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
;;; ai-code-session-link.el --- Shared session link helpers -*- lexical-binding: t; -*-
;; Author: Kang Tu, realazy (cxa)
;; SPDX-License-Identifier: Apache-2.0
;;; Commentary:
;; Internal helpers shared by session linkification and navigation.
;;; Code:
(require 'cl-lib)
(require 'image)
(require 'project)
(require 'rx)
(require 'subr-x)
(require 'url-util)
(declare-function ai-code-session-navigate-link-at-mouse "ai-code-input" (event))
(declare-function ai-code-session-navigate-link-at-point "ai-code-input" ())
(declare-function helm-gtags-find-tag "helm-gtags" (tagname))
(declare-function xref-find-definitions "xref" (identifier))
(defvar ai-code-backends-infra--session-directory nil
"Session working directory set by ai-code-backends-infra buffers.")
(defvar ai-code-backends-infra--session-terminal-backend nil
"Terminal backend symbol set by ai-code-backends-infra buffers.")
(defcustom ai-code-session-link-enabled t
"When non-nil, make supported links clickable in AI session buffers.
Disable this if you prefer to avoid the extra linkification work on
terminal output redraw."
:type 'boolean
:group 'ai-code)
(defcustom ai-code-session-link-ghostel-image-preview-enabled t
"When non-nil, preview local image file links in Ghostel AI sessions.
This only affects AI session buffers managed by the Ghostel terminal backend.
It complements Ghostel's native Kitty graphics support by previewing image
files when an AI CLI prints a local image path such as screenshot.png."
:type 'boolean
:group 'ai-code)
(defcustom ai-code-session-link-ghostel-image-preview-max-bytes
(* 10 1024 1024)
"Maximum local image file size, in bytes, previewed in Ghostel sessions."
:type 'integer
:group 'ai-code)
(defcustom ai-code-session-link-ghostel-image-preview-max-width nil
"Maximum displayed image width for Ghostel previews, in logical pixels.
When nil, previews fit the session window's body width. Source images only
ever scale down; on HiDPI frames, one logical pixel may use multiple source
pixels. Set an integer to impose a fixed hard cap instead."
:type '(choice (const :tag "Fit session window" nil)
(integer :tag "Fixed pixel cap"))
:group 'ai-code)
(defcustom ai-code-session-link-ghostel-image-preview-max-height nil
"Maximum displayed image height for Ghostel previews, in logical pixels.
When nil, preview height is not capped; the width cap controls default
scaling and tall previews can be inspected by scrolling. Set an integer to
impose a fixed hard cap instead."
:type '(choice (const :tag "No height cap" nil)
(integer :tag "Fixed pixel cap"))
:group 'ai-code)
(defcustom ai-code-session-link-ghostel-image-preview-vertical-margin 'auto
"Vertical margin around Ghostel session image previews.
The default value `auto' uses 0.3 times the session window's line height, so
the spacing follows font-size changes. Set a non-negative integer to use a
fixed pixel margin instead; zero disables the margin."
:type '(choice (const :tag "Automatic (0.3 line height)" auto)
(natnum :tag "Fixed pixels"))
:group 'ai-code)
(defconst ai-code-session-link--image-preview-auto-margin-ratio 0.3
"Line-height fraction used for automatic image preview margins.")
(defconst ai-code-session-link--visible-image-preview-max-line-width 2048
"Maximum candidate width inspected by strict visible image preview scanning.")
(defconst ai-code-session-link--visible-image-preview-max-candidates 8
"Maximum image candidates inspected by one strict visible preview scan.")
(defconst ai-code-session-link--visible-image-preview-prefix-max-lines 8
"Maximum previous terminal rows used to rebuild a wrapped image path.")
(defvar ai-code-session-link--keymap
(let ((map (make-sparse-keymap)))
(define-key map [mouse-1] #'ai-code-session-navigate-link-at-mouse)
(define-key map [mouse-2] #'ai-code-session-navigate-link-at-mouse)
(define-key map (kbd "RET") #'ai-code-session-navigate-link-at-point)
map)
"Keymap used for clickable session links.")
(defvar ai-code-session-link--symbol-keymap
(let ((map (make-sparse-keymap)))
(define-key map [mouse-1] #'ai-code-session-link-navigate-symbol-at-mouse)
(define-key map [mouse-2] #'ai-code-session-link-navigate-symbol-at-mouse)
(define-key map (kbd "RET") #'ai-code-session-link-navigate-symbol-at-point)
map)
"Keymap used for clickable session symbols.")
(defconst ai-code-session-link--managed-properties
'(ai-code-session-link nil
ai-code-session-symbol-link nil
ai-code-session-symbol-file nil
ai-code-session-hover-link nil
mouse-face nil
help-echo nil
keymap nil
follow-link nil
font-lock-face nil
face nil)
"Text properties managed by AI Code session linkification.")
(defconst ai-code-session-link--linkify-rules-version 2
"Version of session linkification rules used by unchanged-region caching.")
(defconst ai-code-session-link--linkify-min-tail-width 512
"Minimum number of tail characters to rescan for session links.")
(defconst ai-code-session-link--linkify-redraw-delay 0
"Seconds to wait before relinkifying recent terminal output.")
(defconst ai-code-session-link--linkify-inhibited-retry-delay 0.05
"Seconds to wait before retrying linkification after inhibition.")
(defvar-local ai-code-session-link-inhibit-functions nil
"Abnormal hook run before delayed session linkification.
Each function is called with the current buffer. If any function
returns non-nil, delayed linkification is retried later instead of
touching text properties immediately.")
(defvar-local ai-code-session-link-after-linkify-functions nil
"Hook run after session links are applied to a buffer region.
Each function is called with START and END buffer positions, with the
session buffer current. Terminal backends can use this to preserve their
own display invariants without advising linkification internals.")
(defvar-local ai-code-session-link-image-preview-position-function nil
"Optional owner that decides whether a preview position is stable.
The function receives START and END buffer positions. A nil return suppresses
the preview while leaving the underlying file link intact.")
(defvar-local ai-code-session-link-image-preview-transaction-function nil
"Optional owner for an atomic image-preview update.
The function receives START, END, and a zero-argument FUNCTION. It must call
FUNCTION exactly once and return its result after preserving any external
display or window invariants.")
(defvar-local ai-code-session-link-image-preview-source-function nil
"Optional resolver for a previously captured image source.
The function receives LINK-TEXT and may return a plist containing `:file',
`:data', and `:signature'. This lets a terminal backend preserve temporary
image bytes before its renderer materializes the link in the Emacs buffer.")
(defconst ai-code-session-link--url-pattern-regexp
"\\(https?://[^][(){}<>\"' \t\n]+\\)"
"Regexp matching http/https URLs in session buffers.")
(defconst ai-code-session-link--url-fragment-regexp
"[^][(){}<>\"' \t\n\r]+"
"Regexp matching one terminal row fragment of a URL.")
(defconst ai-code-session-link--url-continuation-end-cue-regexp
"[?#&=._%+-]"
"Regexp matching URL punctuation that can end a wrapped row.")
(defconst ai-code-session-link--url-continuation-start-cue-regexp
"[/?#&=._%+-]"
"Regexp matching URL punctuation that can start a wrapped row.")
(defconst ai-code-session-link--url-query-fragment-regexp
"[?#&=]"
"Regexp matching query punctuation inside a wrapped URL fragment.")
(defconst ai-code-session-link--url-mid-token-cue-regexp
"[-._~%]"
"Regexp matching path token punctuation that suggests a URL wraps mid-token.")
(defconst ai-code-session-link--url-mid-token-fragment-regexp
"\\`[[:alnum:]][[:alnum:]._~%-]*\\'"
"Regexp matching a URL path token fragment split across terminal rows.")
(defconst ai-code-session-link--wrapped-url-max-lines 8
"Maximum number of terminal rows inspected for one wrapped URL.")
(defconst ai-code-session-link--symbol-neighborhood-max-width 168
"Maximum number of characters to scan for symbols near a file link.")
(defconst ai-code-session-link--symbol-neighborhood-max-lines 3
"Maximum number of lines to scan for symbols near a file link.")
(defconst ai-code-session-link--symbol-neighborhood-max-candidates 24
"Maximum number of raw symbol candidates to inspect near one file link.")
(defconst ai-code-session-link--symbol-neighborhood-max-links 12
"Maximum number of symbol links to apply near one file link.")
(defconst ai-code-session-link--path-base-regexp
"@?\\(?:file:\\(?://localhost\\|//\\)?\\)?[[:alnum:]_./~%+-]*[./][[:alnum:]_./~%+-]+"
"Regexp matching a local file-like or directory-like path.")
(defconst ai-code-session-link--path-fragment-regexp
"[-[:alnum:]_./~%+:\\\\]+"
"Regexp matching one terminal row fragment of a local path.")
(defconst ai-code-session-link--wrapped-path-seed-regexp
"@?\\(?:file:\\(?://localhost\\|//\\)?\\)?[-[:alnum:]_./~%+:\\\\]*[./][-[:alnum:]_./~%+:\\\\]*"
"Regexp matching a first-row path fragment that may wrap.
Unlike `ai-code-session-link--path-base-regexp', this accepts fragments
ending at a directory separator, such as \"src/\".")
(defconst ai-code-session-link--wrapped-path-max-lines 8
"Maximum number of terminal rows inspected for one wrapped path.")
(defconst ai-code-session-link--file-suffix-regexp
(concat
"\\(?:"
"#L[0-9]+\\(?:-L?[0-9]+\\)?"
"\\|"
":L[0-9]+\\(?:-L?[0-9]+\\)?"
"\\|"
":[0-9]+:[0-9]+\\>"
"\\|"
":[0-9]+-[0-9]+\\>"
"\\|"
":[0-9]+\\>"
"\\)")
"Regexp matching the optional line or column suffix of a file link.")
(defconst ai-code-session-link--symbol-identifier-regexp
"[[:alpha:]_][[:alnum:]_*!?]*"
"Regexp matching one conservative code identifier segment.")
(defconst ai-code-session-link--camel-case-symbol-regexp
"[[:upper:]][[:alnum:]]+"
"Regexp matching a bare CamelCase-style symbol candidate.")
(defconst ai-code-session-link--snake-case-symbol-regexp
"_*[[:lower:]][[:lower:][:digit:]]*\\(?:_[[:lower:][:digit:]]+\\)+"
"Regexp matching a bare snake_case-style symbol candidate.")
(defconst ai-code-session-link--symbol-candidate-regexp
(concat
"\\("
"\\(?:"
ai-code-session-link--symbol-identifier-regexp
"\\(?:\\.\\|::\\|#\\)"
ai-code-session-link--symbol-identifier-regexp
"\\(?:\\(?:\\.\\|::\\|#\\)"
ai-code-session-link--symbol-identifier-regexp
"\\)*"
"\\(?:()\\)?"
"\\|"
ai-code-session-link--symbol-identifier-regexp
"()"
"\\|"
ai-code-session-link--symbol-identifier-regexp
"\\(?:-[[:alnum:]_*!?]*\\)+"
"\\|"
ai-code-session-link--camel-case-symbol-regexp
"\\|"
ai-code-session-link--snake-case-symbol-regexp
"\\)"
"\\)")
"Regexp matching conservative symbol candidates near a file link.")
(defconst ai-code-session-link--recent-output-candidate-regexp
(concat
"\\(?:https?://"
"\\|"
ai-code-session-link--path-base-regexp
"\\(?:[#:(][[:alnum:],L-]+\\)?"
"\\|"
ai-code-session-link--symbol-identifier-regexp "()"
"\\|"
ai-code-session-link--symbol-identifier-regexp
"\\(?:\\.\\|::\\|#\\)"
ai-code-session-link--symbol-identifier-regexp
"\\|"
ai-code-session-link--snake-case-symbol-regexp
"\\|"
"[[:alpha:]_][[:alnum:]_*!?]*--[[:alpha:]_*!?-]+"
"\\|"
"[[:alpha:]_][[:alnum:]_*!?]*-\\(?:mode\\|hook\\|command\\|function\\|local\\|p\\)\\)")
"Regexp matching recent output that may contain complete session links.")
(defun ai-code-session-link--path-pattern (suffix)
"Return a session link regexp for path base plus SUFFIX."
(concat "\\(" ai-code-session-link--path-base-regexp "\\)" suffix))
(defconst ai-code-session-link--file-patterns
(list
(list (ai-code-session-link--path-pattern
"#L\\([0-9]+\\)\\(?:-L?\\([0-9]+\\)\\)?")
1 2 nil)
(list (ai-code-session-link--path-pattern
":L\\([0-9]+\\)\\(?:-L?\\([0-9]+\\)\\)?")
1 2 nil)
(list (ai-code-session-link--path-pattern
":\\([0-9]+\\):\\([0-9]+\\)\\>")
1 2 3)
(list (ai-code-session-link--path-pattern
":\\([0-9]+\\)-\\([0-9]+\\)\\>")
1 2 nil)
(list (ai-code-session-link--path-pattern
":\\([0-9]+\\)\\>")
1 2 nil)
(list (ai-code-session-link--path-pattern "\\>")
1 nil nil))
"Patterns used to detect file-like session links.")
(defconst ai-code-session-link--basename-file-extensions
'("bash" "c" "cc" "cjs" "clj" "cpp" "cs" "css" "cxx" "el" "erl" "ex"
"exs" "fish" "go" "h" "hh" "hpp" "hrl" "html" "java" "js" "json" "jsx"
"kt" "kts" "less" "lock" "m" "md" "mjs" "mm" "org" "php" "py" "rb" "rs"
"scala" "scss" "sh" "sql" "svelte" "swift" "toml" "ts" "tsx" "txt" "vue"
"xml" "yaml" "yml" "zsh")
"Lowercase extensions accepted for basename file links.")
(defconst ai-code-session-link--image-file-extensions
'("apng" "avif" "bmp" "gif" "heic" "heif" "jpeg" "jpg" "pbm" "pgm"
"png" "ppm" "svg" "tif" "tiff" "webp" "xbm" "xpm")
"Lowercase image extensions accepted for Ghostel session previews.")
(defconst ai-code-session-link--file-url-prefix-regexp
"file:\\(?://localhost\\|//\\)?"
"Regexp matching local file URL prefixes accepted in session output.")
(defconst ai-code-session-link--image-extension-regexp
(regexp-opt ai-code-session-link--image-file-extensions)
"Regexp matching image extensions accepted for Ghostel previews.")
(defconst ai-code-session-link--wrapped-path-continuation-regexp
"\\(?:\n[ \t]*[-[:alnum:]_./~%+:\\\\]+\\)*"
"Regexp matching terminal-wrapped continuation segments of a path.
Ghostel hard-wraps long lines, so a single file path can span several
terminal rows (a common case for tools, such as Claude, that print bare
paths rather than `file://' URLs). Each continuation row is glued back
together by `ai-code-session-link--normalize-file', which strips the
embedded newline and leading indentation.")
(defconst ai-code-session-link--file-url-image-regexp
(concat
"\\(" ai-code-session-link--file-url-prefix-regexp
"\\(?:\n[ \t]*\\)?[-[:alnum:]_./~%+:\\\\]+"
"\\(?:\n[ \t]*[-[:alnum:]_./~%+:\\\\]+\\)*"
"\\.\\(?:"
ai-code-session-link--image-extension-regexp
"\\)\\)")
"Regexp matching file URL image references, including terminal wrapping.")
(defconst ai-code-session-link--local-image-path-regexp
(concat
"\\(?:~\\|/\\|\\.\\.?/\\|[[:alnum:]_.~-]+/\\)"
"[^][(){}<>\"'\n\r]*"
ai-code-session-link--wrapped-path-continuation-regexp
"\\.\\(?:"
ai-code-session-link--image-extension-regexp
"\\)")
"Regexp matching local image paths that may contain spaces.
Tolerates Ghostel hard-wrapping via
`ai-code-session-link--wrapped-path-continuation-regexp'.")
(defconst ai-code-session-link--wrapped-image-reference-regexp
(concat
"[^][(){}<>\"'\n\r]*"
ai-code-session-link--wrapped-path-continuation-regexp
"\\.\\(?:"
ai-code-session-link--image-extension-regexp
"\\)")
"Regexp matching image references inside an explicit wrapper.
Tolerates Ghostel hard-wrapping via
`ai-code-session-link--wrapped-path-continuation-regexp'.")
(defconst ai-code-session-link--image-reference-patterns
(list
(list ai-code-session-link--file-url-image-regexp 1)
(list (concat "[\"'`]\\(" ai-code-session-link--wrapped-image-reference-regexp "\\)[\"'`]")
1)
(list (concat "[(<]\\(" ai-code-session-link--wrapped-image-reference-regexp "\\)[)>]")
1)
(list (concat "\\[\\[\\(file:[^]\n\r]*\\.\\(?:"
ai-code-session-link--image-extension-regexp
"\\)\\)\\(?:\\]\\[[^]\n\r]*\\)?\\]\\]")
1)
(list (concat "\\(?:^\\|[ \t:]\\)\\(" ai-code-session-link--local-image-path-regexp "\\)")
1))
"Patterns used to detect image file references with looser path syntax.")
(defconst ai-code-session-link--reference-wrapper-left-regexp
;; `in' rather than its synonym `any': package-lint reads the latter as a
;; call to the Emacs 31.1 function of that name and errors on our
;; (emacs "29.1") requirement.
(rx (+ (in "\"'`<([{")))
"Regexp matching wrapper characters before a session file reference.")
(defconst ai-code-session-link--reference-wrapper-right-regexp
(rx (+ (in "\"'`>)}],.;:!?")))
"Regexp matching wrapper characters after a session file reference.")
(defvar-local ai-code-session-link--linkify-timer nil
"Timer used to re-linkify recent terminal output after redraw settles.")
(defvar-local ai-code-session-link--pending-tail-width 0
"Pending tail width to rescan when delayed session linkification runs.")
(defvar-local ai-code-session-link--buffer-project-files-cache nil
"Buffer-local project file cache reused across session relinkify passes.")
(defvar-local ai-code-session-link--last-region-bounds nil
"Last relinkified region bounds used to skip unchanged property churn.")
(defvar-local ai-code-session-link--last-region-text nil
"Last relinkified region text used to skip unchanged property churn.")
(defvar-local ai-code-session-link--last-region-rules-version nil
"Linkification rules version used for the last relinkified region.")
(defvar-local ai-code-session-link--last-region-link-count nil
"Number of session link spans left by the last relinkified region pass.")
(defvar ai-code-session-link--project-files-cache nil
"Dynamic cache of project file lists used during one linkify pass.")
(defvar ai-code-session-link--resolved-path-cache nil
"Dynamic cache of resolved session paths used during one linkify pass.")
(defconst ai-code-session-link--cache-miss (make-symbol "cache-miss")
"Sentinel used by per-pass caches when no value has been stored yet.")
(defun ai-code-session-link--normalize-file (filename)
"Normalize session link FILENAME for project lookup."
(when (stringp filename)
(let* ((trimmed (string-trim filename))
(unwrapped (replace-regexp-in-string "[\n\r][ \t]*" "" trimmed))
(without-wrappers
(string-trim
unwrapped
ai-code-session-link--reference-wrapper-left-regexp
ai-code-session-link--reference-wrapper-right-regexp))
(without-at (string-remove-prefix "@" without-wrappers))
(file-url-p (string-match-p "\\`file:" without-at))
(without-file-prefix
(replace-regexp-in-string
(concat "\\`" ai-code-session-link--file-url-prefix-regexp)
"" without-at))
(without-shell-escaped-spaces
(replace-regexp-in-string "\\\\ " " " without-file-prefix))
(normalized (if file-url-p
(or (ignore-errors
(url-unhex-string without-shell-escaped-spaces))
without-shell-escaped-spaces)
without-shell-escaped-spaces)))
(unless (string-empty-p normalized)
normalized))))
(defun ai-code-session-link--normalize-link-text (text)
"Normalize visible session link TEXT for stored navigation data."
(when (stringp text)
(replace-regexp-in-string "[\n\r][ \t]*" "" text)))
(defun ai-code-session-link--normalize-url-link-text (text)
"Normalize visible URL TEXT across terminal-wrapped rows."
(when (stringp text)
(replace-regexp-in-string "[ \t]*[\n\r][ \t]*" "" text)))
(defun ai-code-session-link--cache-get-or-compute (cache key compute)
"Return cached value from CACHE for KEY, or call COMPUTE and store it."
(if cache
(let ((cached (gethash key cache ai-code-session-link--cache-miss)))
(if (eq cached ai-code-session-link--cache-miss)
(let ((value (funcall compute)))
(puthash key value cache)
value)
cached))
(funcall compute)))
(defun ai-code-session-link--buffer-project-files-cache ()
"Return the buffer-local cache of enumerated project files."
(or ai-code-session-link--buffer-project-files-cache
(setq ai-code-session-link--buffer-project-files-cache
(make-hash-table :test 'equal))))
(defun ai-code-session-link--count-link-spans (start end)
"Return the number of session link spans between START and END."
(let ((count 0)
(position start))
(while (< position end)
(when (get-text-property position 'ai-code-session-link)
(setq count (1+ count)))
(setq position (or (next-single-property-change
position 'ai-code-session-link nil end)
end)))
count))
(defun ai-code-session-link--unchanged-region-p (bounds region-text)
"Return non-nil when BOUNDS and REGION-TEXT match the last relinkified region.
The region must also still carry the links that pass applied: terminals
such as Ghostel repaint rows with identical text but no text properties."
(and (equal ai-code-session-link--last-region-bounds bounds)
(equal ai-code-session-link--last-region-rules-version
ai-code-session-link--linkify-rules-version)
(equal ai-code-session-link--last-region-text region-text)
(eql ai-code-session-link--last-region-link-count
(ai-code-session-link--count-link-spans (car bounds) (cdr bounds)))))
(defun ai-code-session-link--project-files (root)
"Return absolute project files for ROOT."
(when (file-directory-p root)
(ai-code-session-link--cache-get-or-compute
ai-code-session-link--project-files-cache
(expand-file-name root)
(lambda ()
(or (ignore-errors
(when-let* ((project (project-current nil root)))
(let ((project-root (expand-file-name (project-root project))))
(mapcar (lambda (file)
(if (file-name-absolute-p file)
(expand-file-name file)
(expand-file-name file project-root)))
(project-files project)))))
(directory-files-recursively root ".*" t))))))
(defun ai-code-session-link--in-project-file-p (file root &optional project-files)
"Return non-nil when FILE exists and belongs to ROOT.
Optional PROJECT-FILES supplies the project file list."
(let* ((project-root (and root (file-name-as-directory (expand-file-name root))))
(candidate (and file (expand-file-name file)))
(project-files (or project-files
(and project-root
(ai-code-session-link--project-files project-root)))))
(and project-root
candidate
(file-exists-p candidate)
(string-prefix-p project-root (file-name-directory candidate))
(member candidate project-files))))
(defun ai-code-session-link--matching-project-files (path root &optional project-files)
"Return project files in ROOT that match PATH exactly or by basename."
(when-let* ((project-root (and root (file-name-as-directory (expand-file-name root))))
(normalized (ai-code-session-link--normalize-file path)))
(let* ((relative-path (replace-regexp-in-string "\\`\\./" "" normalized))
(basename (file-name-nondirectory relative-path))
(project-files (or project-files
(ai-code-session-link--project-files project-root))))
(cl-remove-if-not
(lambda (file)
(or (string= (file-relative-name file project-root) relative-path)
(string= (file-name-nondirectory file) basename)))
project-files))))
(defun ai-code-session-link--project-root-for-paths ()
"Return the current session project root directory with trailing slash."
(let ((root (or ai-code-backends-infra--session-directory
(and (fboundp 'project-current)
(when-let* ((project (project-current nil default-directory)))
(expand-file-name (project-root project))))
default-directory)))
(and root (file-name-as-directory (expand-file-name root)))))
(defun ai-code-session-link--local-path-candidates (path root)
"Return local candidate paths for PATH using ROOT and `default-directory'."
(delete-dups
(delq nil
(list (and (file-name-absolute-p path)
(expand-file-name path))
(and root
(expand-file-name path root))
(expand-file-name path default-directory)))))
(defun ai-code-session-link--resolve-existing-local-path (path root)
"Resolve PATH to an existing local file or directory using ROOT."
(seq-find (lambda (candidate)
(and (not (file-remote-p candidate))
(file-exists-p candidate)))
(ai-code-session-link--local-path-candidates path root)))
(defun ai-code-session-link--syntactic-file-link-candidate-p (path)
"Return non-nil when PATH is syntactically file-like."
(when-let* ((normalized (ai-code-session-link--normalize-file path)))
(let ((extension (file-name-extension normalized)))
(or (string-match-p "\\`file:" normalized)
(file-name-absolute-p normalized)
(string-prefix-p "~/" normalized)
(string-prefix-p "./" normalized)
(string-prefix-p "../" normalized)
(string-match-p "[/\\\\]" normalized)
(and extension
(member (downcase extension)
ai-code-session-link--basename-file-extensions))))))
(defun ai-code-session-link--cheap-file-link-candidate-p
(path &optional root allow-local-probing line-reference)
"Return non-nil when PATH is worth linkifying without project scans.
Optional ROOT is the session project root used for bounded local existence
checks. When ALLOW-LOCAL-PROBING is nil, only syntactic checks are used.
LINE-REFERENCE non-nil means PATH was followed by a line number; status
lines never print one, so the name of ROOT is then not skipped.
Expensive project-wide resolution stays in
`ai-code-session-link--resolve-session-file' on activation."
(when-let* ((normalized (ai-code-session-link--normalize-file path)))
(let ((extension (file-name-extension normalized)))
(or (and allow-local-probing
(ai-code-session-link--resolve-existing-local-path
normalized root))
(and (or line-reference
(not (ai-code-session-link--root-directory-name-p
normalized root)))
(or (and (not (file-name-absolute-p normalized))
(or (string-prefix-p "./" normalized)
(string-prefix-p "../" normalized)
;; With probing, an existing path already
;; matched above; an extensionless one that
;; does not exist is prose or a git ref such
;; as and/or or origin/main.
(and (string-match-p "[/\\\\]" normalized)
(or extension (not allow-local-probing)))
(and extension
(member (downcase extension)
ai-code-session-link--basename-file-extensions))))
(and (not allow-local-probing)
(ai-code-session-link--syntactic-file-link-candidate-p
normalized))))))))
(defun ai-code-session-link--root-directory-name-p (path root)
"Return non-nil when PATH is just the name of the session ROOT directory.
Status lines such as Claude Code's footer print the working directory name,
which reads as a file name when the directory is named like one (foo.el)."
(and root
(string= path (file-name-nondirectory (directory-file-name root)))))
(defun ai-code-session-link--resolve-session-file (path)
"Resolve PATH to an existing local path or a matching project file."
(let* ((root (ai-code-session-link--project-root-for-paths))
(normalized (ai-code-session-link--normalize-file path))
(cache-key (and root normalized
(cons (expand-file-name root) normalized))))
(if cache-key
(ai-code-session-link--cache-get-or-compute
ai-code-session-link--resolved-path-cache
cache-key
(lambda ()
(or (ai-code-session-link--resolve-existing-local-path normalized root)
(let* ((project-files (ai-code-session-link--project-files root))
(candidate (if (file-name-absolute-p normalized)
(expand-file-name normalized)
(expand-file-name normalized root))))
(cond
((ai-code-session-link--in-project-file-p candidate root project-files) candidate)
((not (file-name-absolute-p normalized))
(car (ai-code-session-link--matching-project-files normalized root project-files)))
(t nil))))))
nil)))
(defun ai-code-session-link--ghostel-session-p ()
"Return non-nil when the current buffer is a Ghostel-managed AI session."
(and (boundp 'ai-code-backends-infra--session-terminal-backend)
(eq ai-code-backends-infra--session-terminal-backend 'ghostel)))
(defun ai-code-session-link--trusted-local-session-p ()
"Return non-nil when session file probing is safe for local preview."
(not (file-remote-p
(or ai-code-backends-infra--session-directory
default-directory))))
(defun ai-code-session-link--image-preview-enabled-p ()
"Return non-nil when image previews should be applied in this buffer."
(and ai-code-session-link-ghostel-image-preview-enabled
(ai-code-session-link--ghostel-session-p)
(ai-code-session-link--trusted-local-session-p)
(display-images-p)))
(defun ai-code-session-link--image-extension-p (file)
"Return non-nil when FILE has a known image file extension."
(when-let* ((extension (file-name-extension file)))
(member (downcase extension)
ai-code-session-link--image-file-extensions)))
(defun ai-code-session-link--safe-local-image-file-p (file)
"Return non-nil when FILE is a local image safe enough to preview."
(and (stringp file)
(ai-code-session-link--image-extension-p file)
(not (file-remote-p file))
(file-regular-p file)
(file-readable-p file)
(let ((attrs (file-attributes file 'integer)))
(and attrs
(<= (file-attribute-size attrs)
ai-code-session-link-ghostel-image-preview-max-bytes)))))
(defun ai-code-session-link--image-preview-file-signature (file)
"Return a size and modification-time signature for image FILE."
(when-let* ((attributes (file-attributes file 'integer)))
(cons (file-attribute-size attributes)
(file-attribute-modification-time attributes))))
(defun ai-code-session-link--parse-file-link-text (text)
"Parse file-like session link TEXT into a plist."
(when-let* ((text (ai-code-session-link--normalize-link-text text)))
(if (or (string-match-p "\\`file:" text)
(when-let* ((normalized (ai-code-session-link--normalize-file text)))
(ai-code-session-link--image-extension-p normalized)))
(list :file text)
(catch 'parsed
(dolist (pattern ai-code-session-link--file-patterns)
(let ((regexp (concat "\\`" (car pattern) "\\'")))
(when (string-match regexp text)
(throw
'parsed
(list :file (match-string (nth 1 pattern) text)
:line-start (when-let* ((group (nth 2 pattern))
(line (match-string group text)))
(string-to-number line))
:column-start (when-let* ((group (nth 3 pattern))
(column (match-string group text)))
(string-to-number column)))))))))))
(defun ai-code-session-link--image-preview-file (link-text)
"Return an absolute local image file resolved from LINK-TEXT, or nil."
(when-let* ((link (ai-code-session-link--parse-file-link-text link-text))
(file (plist-get link :file))
((ai-code-session-link--image-extension-p file))
(abs-file (ai-code-session-link--resolve-session-file file))
((ai-code-session-link--safe-local-image-file-p abs-file)))
abs-file))
(defun ai-code-session-link--delete-image-preview-overlays
(start end &optional stale-only)
"Delete image preview overlays touching START through END.
When STALE-ONLY is non-nil, preserve overlays still anchored to their image
link text."
(let* ((line-start (save-excursion
(goto-char start)
(line-beginning-position)))
(line-end (save-excursion
(goto-char end)
(line-end-position)))
(scan-end (min (point-max) (1+ line-end))))
(dolist (overlay (delete-dups
(append (overlays-in line-start scan-end)
(overlays-at line-start)
(overlays-at start)
(overlays-at end)
(overlays-at line-end)
(overlays-at scan-end))))
(when (and (overlay-get overlay 'ai-code-session-image-preview)
(or (not stale-only)
(not
(ai-code-session-link--live-image-preview-overlay-p
overlay))))
(ai-code-session-link--delete-image-preview-overlay overlay)))))
(defun ai-code-session-link--delete-image-preview-overlay (overlay)
"Delete image preview OVERLAY and its companion suffix overlay."
(when-let* ((suffix-overlay
(overlay-get overlay
'ai-code-session-image-preview-suffix-overlay))
((overlayp suffix-overlay)))
(delete-overlay suffix-overlay))
(delete-overlay overlay))
(defun ai-code-session-link--image-preview-tree-prefix-p (match-start)
"Return non-nil when MATCH-START follows a leading tree prefix.
The prefix may appear on the image link's row or on the immediately preceding
row, as it does in multiline tool-result output. Accept both `╰' and the
square-corner `└' emitted by terminal clients."
(save-excursion
(goto-char match-start)
(let* ((line-start (line-beginning-position))
(same-row-prefix
(buffer-substring-no-properties line-start match-start)))
(or (string-match-p "\\`[ \t]*[╰└][ \t]*\\'" same-row-prefix)
(and (> line-start (point-min))
(progn
(goto-char line-start)
(forward-line -1)
(string-match-p
"\\`[ \t]*[╰└][ \t]*\\'"
(buffer-substring-no-properties
(line-beginning-position) (line-end-position)))))))))
(defun ai-code-session-link--image-preview-layout (match-start)
"Return (SIZE-INDENT . BEFORE-STRING) for MATCH-START.
SIZE-INDENT preserves the width allowance for the path's leading gutter.
BEFORE-STRING starts the preview on its own row at the same indentation.
The source path remains visible on its original terminal row."
(save-excursion
(goto-char match-start)
(let* ((column (current-column))
(line-start (line-beginning-position))
(line-end (line-end-position))
(leading-indent
(progn
(goto-char line-start)
(skip-chars-forward " \t" line-end)
(buffer-substring-no-properties line-start (point)))))
(let ((indent
(if (ai-code-session-link--image-preview-tree-prefix-p match-start)
(make-string column ?\s)
leading-indent)))
(cons indent (concat "\n" indent))))))
(defun ai-code-session-link--image-preview-link-file (link-text)
"Return the local image file for previewable LINK-TEXT, or nil."
(when (ai-code-session-link--image-preview-enabled-p)
(ai-code-session-link--image-preview-file link-text)))
(defun ai-code-session-link--image-preview-vertical-margin ()
"Return the current image preview vertical margin in pixels."
(let ((setting ai-code-session-link-ghostel-image-preview-vertical-margin))
(cond
((integerp setting) (max 0 setting))
((eq setting 'auto)
(let* ((window (get-buffer-window (current-buffer) t))
(line-height
(ignore-errors
(if window
(with-selected-window window (default-line-height))
(default-line-height)))))
(if (and (numberp line-height) (> line-height 0))
(max 1
(round
(* ai-code-session-link--image-preview-auto-margin-ratio
line-height)))
6)))
(t 0))))
(defun ai-code-session-link--live-image-preview-overlay-p (overlay)
"Return non-nil when OVERLAY is still anchored to its image link text."
(and (overlayp overlay)
(eq (overlay-buffer overlay) (current-buffer))
(overlay-get overlay 'ai-code-session-image-preview)
(< (overlay-start overlay) (overlay-end overlay))
(let* ((link-start
(overlay-get overlay 'ai-code-session-image-link-start))
(link-text (overlay-get overlay 'ai-code-session-image-link-text))
(file (overlay-get overlay 'ai-code-session-image-file))
(file-signature
(overlay-get overlay 'ai-code-session-image-file-signature))
(current-file-signature
(and file
(ai-code-session-link--image-preview-file-signature file)))
(vertical-margin
(overlay-get overlay 'ai-code-session-image-vertical-margin))
(render-context
(overlay-get overlay 'ai-code-session-image-render-context))
(layout
(ai-code-session-link--image-preview-layout
link-start))
(before-string (cdr layout))
(display-text
(or (overlay-get overlay 'ai-code-session-image-display-text)
(overlay-get overlay 'ai-code-session-image-link-text)))
(display-end
(or (overlay-get overlay 'ai-code-session-image-display-end)
(overlay-end overlay))))
(and (integer-or-marker-p link-start)
(<= (point-min) link-start)
(< link-start (point-max))
link-text
file
file-signature
;; Previews contain decoded image data, so a vanished temporary
;; source does not invalidate an otherwise stable snapshot.
(or (not current-file-signature)
(equal file-signature current-file-signature))
(integerp vertical-margin)
(= vertical-margin
(ai-code-session-link--image-preview-vertical-margin))
render-context
(equal
render-context
(ai-code-session-link--image-preview-render-context
(ai-code-session-link--image-preview-max-dimensions
(car layout))))
(equal (overlay-get overlay 'before-string) before-string)
display-text
(integer-or-marker-p display-end)
(<= link-start display-end)
(<= display-end (point-max))
(= (overlay-start overlay) display-end)
(= (overlay-end overlay) (1+ display-end))
(eq (char-after display-end) ?\n)
(equal (overlay-get overlay 'after-string) "\n")
(equal (buffer-substring-no-properties
link-start display-end)
display-text)))))
(defun ai-code-session-link--live-image-preview-overlays-in-region (start end)
"Return live image preview overlays between START and END."
(cl-remove-if-not
#'ai-code-session-link--live-image-preview-overlay-p
(delete-dups
(append (overlays-in start end)
(overlays-at start)
(overlays-at end)))))
(defun ai-code-session-link--image-preview-overlay-at
(start end display-text)
"Return the live preview at START through END for DISPLAY-TEXT, or nil."
(let* ((line-start (save-excursion
(goto-char start)
(line-beginning-position)))
(line-end (save-excursion
(goto-char end)
(line-end-position)))
(scan-end (min (point-max) (1+ line-end))))
(cl-find-if
(lambda (overlay)
(and (ai-code-session-link--live-image-preview-overlay-p overlay)
(= (overlay-get overlay 'ai-code-session-image-link-start)
start)
(<= end
(overlay-get overlay 'ai-code-session-image-link-end))
(let ((overlay-link
(overlay-get overlay 'ai-code-session-image-link-text))
(overlay-display
(overlay-get overlay 'ai-code-session-image-display-text)))
(or (equal display-text overlay-link)
(equal display-text overlay-display)))))
(delete-dups
(append (overlays-in line-start scan-end)
(overlays-at line-start)
(overlays-at line-end)
(overlays-at scan-end))))))
(defun ai-code-session-link--image-preview-overlay-present-p
(start end display-text)
"Return non-nil when START to END already has a preview for DISPLAY-TEXT."
(and (ai-code-session-link--image-preview-overlay-at
start end display-text)
t))
(defun ai-code-session-link--image-preview-overlays-overlapping-row-span
(start end)
"Return live image previews whose owned row span overlaps START through END.
An image preview semantically owns its source row even though its display
overlay covers only the row's terminating newline."
(let ((line-start (save-excursion
(goto-char start)
(line-beginning-position)))
(line-end (save-excursion
(goto-char end)
(line-end-position))))
(cl-remove-if-not
(lambda (overlay)
(let ((link-start
(or (overlay-get overlay 'ai-code-session-image-link-start)
(overlay-start overlay)))
(display-end
(or (overlay-get overlay
'ai-code-session-image-display-end)
(overlay-end overlay))))
(and (ai-code-session-link--live-image-preview-overlay-p overlay)
(< link-start end)
(< start display-end))))
(overlays-in line-start (min (point-max) (1+ line-end))))))
(defun ai-code-session-link--text-may-contain-image-reference-p (text)
"Return non-nil when TEXT may contain an image reference."
(and (stringp text)
(string-match-p
(concat "\\(?:file:\\|\\.\\(?:" ai-code-session-link--image-extension-regexp "\\)\\)")
text)))
(defun ai-code-session-link--image-preview-refresh-needed-p (start end)
"Return non-nil when image previews between START and END need refreshing."
(catch 'missing-preview
(let ((ai-code-session-link--project-files-cache
(ai-code-session-link--buffer-project-files-cache))
(ai-code-session-link--resolved-path-cache
(make-hash-table :test 'equal)))
(dolist (file-link (ai-code-session-link--collect-file-links
start end t))
(let ((link-start (plist-get file-link :start))
(link-end (plist-get file-link :end))
(link-text (plist-get file-link :text)))
(when (and (ai-code-session-link--image-preview-link-file link-text)
(not (ai-code-session-link--image-preview-overlay-present-p
link-start link-end link-text)))
(throw 'missing-preview t)))))
nil))
(defun ai-code-session-link--image-preview-format-hint (file)
"Return an image MIME-style data hint for FILE, or nil."
(when-let* ((extension (file-name-extension file)))
(intern (format "image/%s"
(pcase (downcase extension)
("jpg" "jpeg")
("tif" "tiff")
(other other))))))