-
Notifications
You must be signed in to change notification settings - Fork 0
/
sepia.el
1899 lines (1726 loc) · 64.7 KB
/
sepia.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
;;; Sepia -- Simple Emacs-Perl InterAction: ugly, yet effective.
;; (a.k.a. Septik -- Sean's Emacs-Perl Total Integration Kludge.)
;; Author: Sean O'Rourke <[email protected]>
;; Keywords: Perl, languages
;; Copyright (C) 2004-2009 Sean O'Rourke. All rights reserved, some
;; wrongs reversed. This code is distributed under the same terms
;; as Perl itself.
;;; Commentary:
;; Sepia is a set of tools for Perl development in Emacs. Its goal is
;; to extend CPerl mode with two contributions: fast code navigation
;; and interactive development. It is inspired by Emacs' current
;; support for a number of other languages, including Lisp, Python,
;; Ruby, and Emacs Lisp.
;;
;; See sepia.texi, which comes with the distribution.
;;; Code:
(require 'cperl-mode)
(require 'gud)
(require 'cl)
;; try optional modules, but don't bitch if we fail:
(ignore-errors (require 'sepia-w3m))
(ignore-errors (require 'sepia-tree))
(ignore-errors (require 'sepia-ido))
(ignore-errors (require 'sepia-snippet))
;; extensions that should always load (autoload later?)
(require 'sepia-cpan)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Comint communication
(defvar sepia-perl5lib nil
"* List of extra PERL5LIB directories for `sepia-repl'.")
(defvar sepia-program-name "perl"
"* Perl program name.")
(defvar sepia-view-pod-function
(if (featurep 'w3m) 'sepia-w3m-view-pod 'sepia-perldoc-buffer)
"* Function to view current buffer's documentation.
Useful values include `sepia-w3m-view-pod' and `sepia-perldoc-buffer'.")
(defvar sepia-module-list-function
(if (featurep 'w3m) 'w3m-find-file 'browse-url-of-file)
"* Function to view a list of installed modules.
Useful values include `w3m-find-file' and `browse-url-of-buffer'.")
(defvar sepia-complete-methods t
"* Non-nil if Sepia should try to complete methods for \"$x->\".
NOTE: this feature can be problematic, since it evaluates the
object in order to find its type. Currently completion is only
attempted for objects that are simple scalars.")
(defvar sepia-indent-expand-abbrev t
"* If non-NIL, `sepia-indent-or-complete' tries `expand-abbrev'.")
(defvar sepia-use-completion t
"* Use completion based on Xref database.
Turning this off may speed up some operations, if you don't mind
losing completion.")
(defvar sepia-eval-defun-include-decls t
"* Generate and use a declaration list for `sepia-eval-defun'.
Without this, code often will not parse; with it, evaluation may
be a bit less responsive. Note that since this only includes
subs from the evaluation package, it may not always work.")
(defvar sepia-prefix-key "\M-."
"* Prefix for functions in `sepia-keymap'.")
;;; User options end here.
(defvar sepia-process nil
"The perl process with which we're interacting.")
(defvar sepia-output nil
"Current perl output for a response to `sepia-eval-raw', appended
to by `perl-collect-output'.")
(defvar sepia-passive-output ""
"Current perl output for miscellaneous user interaction, used to
look for \";;;###\" lisp evaluation markers.")
(defvar sepia-perl-builtins nil
"List of Perl builtins for completion.")
(defun sepia-collect-output (string)
"Collect perl output for `sepia-eval-raw' into sepia-output."
(setq sepia-output (concat sepia-output string))
"")
(defun sepia-eval-raw (str)
"Evaluate perl code STR, returning a pair (RESULT-STRING . OUTPUT)."
(sepia-ensure-process)
(let (ocpof)
(unwind-protect
(let ((sepia-output "")
(start 0))
(with-current-buffer (process-buffer sepia-process)
(setq ocpof comint-preoutput-filter-functions
comint-preoutput-filter-functions
'(sepia-collect-output)))
(setq str (concat "local $Sepia::STOPDIE=0;"
"local $Sepia::STOPWARN=0;"
"{ package " (sepia-buffer-package) ";"
str " }\n"))
(comint-send-string sepia-process
(concat (format "<<%d\n" (length str)) str))
(while (not (and sepia-output
(string-match "> $" sepia-output)))
(accept-process-output sepia-process))
(if (string-match "^;;;[0-9]+\n" sepia-output)
(cons
(let* ((x (read-from-string sepia-output
(+ (match-beginning 0) 3)))
(len (car x))
(pos (cdr x)))
(prog1 (substring sepia-output (1+ pos) (+ len pos 1))
(setq start (+ pos len 1))))
(and (string-match ";;;[0-9]+\n" sepia-output start)
(let* ((x (read-from-string
sepia-output
(+ (match-beginning 0) 3)))
(len (car x))
(pos (cdr x)))
(substring sepia-output (1+ pos) (+ len pos 1)))))
(cons sepia-output nil)))
(with-current-buffer (process-buffer sepia-process)
(setq comint-preoutput-filter-functions ocpof)))))
(defun sepia-eval (str &optional context detailed)
"Evaluate STR in CONTEXT (void by default), and return its result
as a Lisp object. If DETAILED is specified, return a
pair (RESULT . OUTPUT)."
(let* ((tmp (sepia-eval-raw
(case context
(list-context
(concat "Sepia::tolisp([" str "])"))
(scalar-context
(concat "Sepia::tolisp(scalar(" str "))"))
(t (concat str ";1")))))
(res (car tmp))
(errs (cdr tmp)))
(setq res (if context
(if (string= res "") "" (car (read-from-string res)))
1))
(if detailed
(cons res errs)
res)))
(defun sepia-call (fn context &rest args)
"Call perl function FN in CONTEXT with arguments ARGS, returning
its result as a Lisp value."
(sepia-eval (concat fn "(" (mapconcat #'sepia-lisp-to-perl args ", ") ")")
context))
(defun sepia-watch-for-eval (string)
"Monitor inferior Perl output looking for Lisp evaluation
requests. The format for these requests is
\"\\n;;;###LENGTH\\nDATA\". Only one such request can come from
each inferior Perl prompt."
(setq sepia-passive-output (concat sepia-passive-output string))
(cond
((string-match "^;;;###[0-9]+" sepia-passive-output)
(if (string-match "^;;;###\\([0-9]+\\)\n\\(?:.\\|\n\\)*\n\\(.*> \\)"
sepia-passive-output)
(let* ((len (car (read-from-string
(match-string 1 sepia-passive-output))))
(pos (1+ (match-end 1)))
(res (ignore-errors (eval (car (read-from-string
sepia-passive-output pos
(+ pos len)))))))
(message "%s => %s"
(substring sepia-passive-output pos (+ pos len)) res)
(goto-char (point-max))
(insert (substring sepia-passive-output (+ 1 pos len)))
(set-marker (process-mark (get-buffer-process (current-buffer)))
(point))
(setq sepia-passive-output ""))
""))
(t (setq sepia-passive-output "") string)))
(defvar sepia-metapoint-map
(let ((map (make-sparse-keymap)))
(when (featurep 'ido)
(define-key map "j" 'sepia-jump-to-symbol))
(dolist (kv '(("c" . sepia-callers)
("C" . sepia-callees)
("a" . sepia-apropos)
("A" . sepia-var-apropos)
("v" . sepia-var-uses)
("V" . sepia-var-defs)
;; ("V" . sepia-var-assigns)
("\M-." . sepia-dwim)
;; ("\M-." . sepia-location)
("l" . sepia-location)
("f" . sepia-defs)
("r" . sepia-rebuild)
("m" . sepia-module-find)
("n" . sepia-next)
("t" . find-tag)
("d" . sepia-perldoc-this)
("u" . sepia-describe-object)))
(define-key map (car kv) (cdr kv)))
map)
"Keymap for Sepia functions. This is just an example of how you
might want to bind your keys, which works best when bound to
`\\M-.'.")
(defvar sepia-shared-map
(let ((map (make-sparse-keymap)))
(define-key map sepia-prefix-key sepia-metapoint-map)
(define-key map "\M-," 'sepia-next)
(define-key map "\C-\M-x" 'sepia-eval-defun)
(define-key map "\C-c\C-l" 'sepia-load-file)
(define-key map "\C-c\C-p" 'sepia-view-pod) ;was cperl-pod-spell
(define-key map "\C-c\C-d" 'cperl-perldoc)
(define-key map "\C-c\C-r" 'sepia-repl)
(define-key map "\C-c\C-s" 'sepia-scratch)
(define-key map "\C-c\C-e" 'sepia-eval-expression)
(define-key map "\C-c!" 'sepia-set-cwd)
(define-key map (kbd "TAB") 'sepia-indent-or-complete)
map)
"Sepia bindings common to all modes.")
;;;###autoload
(defun sepia-perldoc-this (name)
"View perldoc for module at point."
(interactive (list (sepia-interactive-arg 'module)))
(let ((wc (current-window-configuration))
(old-pd (symbol-function 'w3m-about-perldoc))
(old-pdb (symbol-function 'w3m-about-perldoc-buffer)))
(condition-case stuff
(flet ((w3m-about-perldoc (&rest args)
(let ((res (apply old-pd args)))
(or res (error "lose: %s" args))))
(w3m-about-perldoc-buffer (&rest args)
(let ((res (apply old-pdb args)))
(or res (error "lose: %s" args)))))
(funcall (if (featurep 'w3m) 'w3m-perldoc 'cperl-perldoc) name))
(error (set-window-configuration wc)))))
(defun sepia-view-pod ()
"View POD for the current buffer."
(interactive)
(funcall sepia-view-pod-function))
(defun sepia-module-list ()
"List installed modules with links to their documentation.
This lists not just top-level packages appearing in packlist
files, but all documented modules on the system, organized by
package."
(interactive)
(let ((file "/tmp/modlist.html"))
;; (unless (file-exists-p file)
(sepia-eval-raw (format "Sepia::html_module_list(\"%s\")" file))
(funcall sepia-module-list-function file)))
(defun sepia-package-list ()
"List installed packages with links to their documentation.
This lists only top-level packages appearing in packlist files.
For modules within packages, see `sepia-module-list'."
(interactive)
(let ((file "/tmp/packlist.html"))
;; (unless (file-exists-p file)
(sepia-eval-raw (format "Sepia::html_package_list(\"%s\")" file))
(funcall sepia-module-list-function file)))
(defun sepia-perldoc-buffer ()
"View current buffer's POD using pod2html and `browse-url'.
Interactive users should call `sepia-view-pod'."
(let ((buffer (get-buffer-create "*sepia-pod*"))
(errs (get-buffer-create "*sepia-pod-errors*"))
(inhibit-read-only t))
(with-current-buffer buffer (erase-buffer))
(save-window-excursion
(shell-command-on-region (point-min) (point-max) "pod2html"
buffer nil errs))
(with-current-buffer buffer (browse-url-of-buffer))))
(defun sepia-perl-name (sym &optional mod)
"Convert a Perl name to a Lisp name."
(setq sym (substitute ?_ ?- (if (symbolp sym) (symbol-name sym) sym)))
(if mod
(concat mod "::" sym)
sym))
(defun sepia-live-p ()
(and (processp sepia-process)
(eq (process-status sepia-process) 'run)))
(defun sepia-ensure-process (&optional remote-host)
(unless (sepia-live-p)
(with-current-buffer (get-buffer-create "*sepia-repl*")
(sepia-repl-mode)
(set (make-local-variable 'sepia-passive-output) ""))
(if remote-host
(comint-exec (get-buffer-create "*sepia-repl*")
"attachtty" "attachtty" nil
(list remote-host))
(let ((stuff (split-string sepia-program-name nil t)))
(comint-exec (get-buffer-create "*sepia-repl*")
"perl" (car stuff) nil
(append
(cdr stuff)
(mapcar (lambda (x) (concat "-I" x)) sepia-perl5lib)
'("-MSepia" "-MSepia::Xref"
"-e" "Sepia::repl")))))
(setq sepia-process (get-buffer-process "*sepia-repl*"))
(accept-process-output sepia-process 1)
;; Steal a bit from gud-common-init:
(setq gud-running t)
(setq gud-last-last-frame nil)
(set-process-filter sepia-process 'gud-filter)
(set-process-sentinel sepia-process 'gud-sentinel)))
;;;###autoload
(defun sepia-repl (&optional remote-host)
"Start the Sepia REPL."
(interactive (list (and current-prefix-arg
(read-string "Host: "))))
(sepia-init) ;; set up keymaps, etc.
(sepia-ensure-process remote-host)
(pop-to-buffer (get-buffer "*sepia-repl*")))
(defun sepia-cont-or-restart ()
(interactive)
(if (get-buffer-process (current-buffer))
(gud-cont current-prefix-arg)
(sepia-repl)))
(defvar sepia-repl-mode-map
(let ((map (copy-keymap sepia-shared-map)))
(set-keymap-parent map gud-mode-map)
(define-key map (kbd "<tab>") 'comint-dynamic-complete)
(define-key map "\C-a" 'comint-bol)
(define-key map "\C-c\C-r" 'sepia-cont-or-restart)
map)
"Keymap for Sepia interactive mode.")
(define-derived-mode sepia-repl-mode gud-mode "Sepia REPL"
"Major mode for the Sepia REPL.
\\{sepia-repl-mode-map}"
;; (set (make-local-variable 'comint-use-prompt-regexp) t)
(modify-syntax-entry ?: "_")
(modify-syntax-entry ?> ".")
(set (make-local-variable 'comint-prompt-regexp) "^[^>\n]*> *")
(set (make-local-variable 'gud-target-name) "sepia")
(set (make-local-variable 'gud-marker-filter) 'sepia-gud-marker-filter)
(set (make-local-variable 'gud-minor-mode) 'sepia)
(sepia-install-eldoc)
(setq gud-comint-buffer (current-buffer))
(setq gud-last-last-frame nil)
(setq gud-sepia-acc nil)
(gud-def gud-break ",break %f:%l" "\C-b" "Set breakpoint at current line.")
(gud-def gud-step ",step %p" "\C-s" "Step one line.")
(gud-def gud-next ",next %p" "\C-n" "Step one line, skipping calls.")
(gud-def gud-cont ",continue" "\C-r" "Continue.")
(gud-def gud-print "%e" "\C-p" "Evaluate something.")
(gud-def gud-remove ",delete %l %f" "\C-d" "Delete current breakpoint.")
;; Sadly, this hoses our keybindings.
(compilation-shell-minor-mode 1)
(set (make-local-variable 'comint-dynamic-complete-functions)
'(sepia-complete-symbol comint-dynamic-complete-filename))
(set (make-local-variable 'comint-preoutput-filter-functions)
'(sepia-watch-for-eval))
(run-hooks 'sepia-repl-mode-hook)
)
(defvar gud-sepia-acc nil
"Accumulator for `sepia-gud-marker-filter'.")
(defun sepia-gud-marker-filter (str)
(setq gud-sepia-acc
(if gud-sepia-acc
(concat gud-sepia-acc str)
str))
(while (string-match "_<\\([^:>]+\\):\\([0-9]+\\)>\\(.*\\)" gud-sepia-acc)
(setq gud-last-last-frame gud-last-frame
gud-last-frame (cons
(match-string 1 gud-sepia-acc)
(string-to-number (match-string 2 gud-sepia-acc)))
gud-sepia-acc (match-string 3 gud-sepia-acc)))
(setq gud-sepia-acc
(if (string-match "\\(_<.*\\)" gud-sepia-acc)
(match-string 1 gud-sepia-acc)
nil))
str)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Xref
(defun define-xref-function (package name doc)
"Define a lisp mirror for a low-level Sepia function."
(let ((lisp-name (intern (format "xref-%s" name)))
(pl-name (sepia-perl-name name package)))
(fmakunbound lisp-name)
(eval `(defun ,lisp-name (&rest args)
,doc
(apply #'sepia-call ,pl-name 'list-context args)))))
(defun define-modinfo-function (name &optional doc context)
"Define a lisp mirror for a function from Module::Info."
(let ((name (intern (format "sepia-module-%s" name)))
(pl-func (sepia-perl-name name))
(full-doc (concat (or doc "") "
This function uses Module::Info, so it does not require that the
module in question be loaded.")))
(when (fboundp name) (fmakunbound name))
(eval `(defun ,name (mod)
,full-doc
(interactive (list (sepia-interactive-arg 'module)))
(sepia-maybe-echo
(sepia-call "Sepia::module_info" ',(or context 'scalar-context)
mod ,pl-func)
(interactive-p))))))
(defun sepia-thing-at-point (what)
"Like `thing-at-point', but hacked to avoid REPL prompt."
(let ((th (thing-at-point what)))
(and th (not (string-match "[ >]$" th)) th)))
(defvar sepia-sub-re "^ *sub\\s +\\(.+\\_>\\)")
(defvar sepia-history nil)
(defun sepia-interactive-arg (&optional sepia-arg-type)
"Default argument for most Sepia functions. TYPE is a symbol --
either 'file to look for a file, or anything else to use the
symbol at point."
(let* ((default (case sepia-arg-type
(file (or (thing-at-point 'file) (buffer-file-name)))
(t (sepia-thing-at-point 'symbol))))
(text (capitalize (symbol-name sepia-arg-type)))
(choices
(lambda (str &rest blah)
(let ((completions (xref-completions
(case sepia-arg-type
(module nil)
(variable "VARIABLE")
(function "CODE")
(t nil))
str)))
(when (eq sepia-arg-type 'module)
(setq completions
(remove-if (lambda (x) (string-match "::$" x)) completions)))
completions)))
(prompt (if default
(format "%s [%s]: " text default)
(format "%s: " text)))
(ret (if sepia-use-completion
(completing-read prompt 'blah-choices nil nil nil 'sepia-history
default)
(read-string prompt nil 'sepia-history default))))
(push ret sepia-history)
ret))
(defun sepia-interactive-module ()
"Guess which module we should look things up in. Prompting for a
module all the time is a PITA, but I don't think this (choosing
the current file's module) is a good alternative, either. Best
would be to choose the module based on what we know about the
symbol at point."
(let ((xs (xref-file-modules (buffer-file-name))))
(if (= (length xs) 1)
(car xs)
nil)))
(defun sepia-maybe-echo (result &optional print-message)
(when print-message
(message "%s" result))
result)
(defun sepia-find-module-file (mod)
(or (sepia-module-file mod)
(car (xref-guess-module-file mod))))
(defun sepia-module-find (mod)
"Find the file defining module MOD."
(interactive (list (sepia-interactive-arg 'module)))
(let ((fn (sepia-find-module-file mod)))
(if fn
(progn
(message "Module %s in %s." mod fn)
(pop-to-buffer (find-file-noselect (expand-file-name fn))))
(message "Can't find module %s." mod))))
(defmacro ifa (test then &rest else)
`(let ((it ,test))
(if it ,then ,@else)))
(defvar sepia-found-refiner)
(defun sepia-show-locations (locs)
(when locs
(pop-to-buffer (get-buffer-create "*sepia-places*"))
(let ((inhibit-read-only t))
(erase-buffer)
(dolist (loc (sort (remove nil locs) ; XXX where's nil from?
(lambda (a b)
(or (string< (car a) (car b))
(and (string= (car a) (car b))
(< (second a) (second b)))))))
(destructuring-bind (file line name &rest blah) loc
(let ((str (ifa (find-buffer-visiting file)
(with-current-buffer it
(ifa sepia-found-refiner
(funcall it line name)
(goto-line line))
(message "line for %s was %d, now %d" name line
(line-number-at-pos))
(setq line (line-number-at-pos))
(let ((tmpstr
(buffer-substring (sepia-bol-from (point))
(sepia-eol-from (point)))))
(if (> (length tmpstr) 60)
(concat "\n " tmpstr)
tmpstr)))
"...")))
(insert (format "%s:%d:%s\n" (abbreviate-file-name file) line str)))))
(grep-mode)
(goto-char (point-min)))))
(defmacro define-sepia-query (name doc &optional gen test prompt)
"Define a sepia querying function."
`(defun ,name (ident &optional module file line display-p)
,(concat doc "
With prefix arg, list occurences in a `grep-mode' buffer.
Without, place the occurrences on `sepia-found', so that
calling `sepia-next' will cycle through them.
Depending on the query, MODULE, FILE, and LINE may be used to
narrow the results, as long as doing so leaves some matches.
When called interactively, they are taken from the current
buffer.
")
(interactive (list (sepia-interactive-arg ,(or prompt ''function))
(sepia-interactive-module)
(buffer-file-name)
(line-number-at-pos (point))
current-prefix-arg
))
(let ((ret
,(if test
`(let ((tmp (,gen ident module file line)))
(or (mapcan #',test tmp) tmp))
`(,gen ident module file line))))
;; Always clear out the last found ring, because it's confusing
;; otherwise.
(sepia-set-found nil ,(or prompt ''function))
(if display-p
(sepia-show-locations ret)
(sepia-set-found ret ,(or prompt ''function))
(sepia-next)))))
(define-sepia-query sepia-defs
"Find all definitions of sub."
xref-apropos
xref-location)
(define-sepia-query sepia-callers
"Find callers of FUNC."
xref-callers
xref-location)
(define-sepia-query sepia-callees
"Find a sub's callees."
xref-callees
xref-location)
(define-sepia-query sepia-var-defs
"Find a var's definitions."
xref-var-defs
(lambda (x) (setf (third x) ident) (list x))
'variable)
(define-sepia-query sepia-var-uses
"Find a var's uses."
xref-var-uses
(lambda (x) (setf (third x) ident) (list x))
'variable)
(define-sepia-query sepia-var-assigns
"Find/list assignments to a variable."
xref-var-assigns
(lambda (x) (setf (third x) ident) (list x))
'variable)
(defalias 'sepia-package-defs 'sepia-module-describe)
(define-sepia-query sepia-apropos
"Find/list subroutines matching regexp."
(lambda (name &rest blah) (xref-apropos name 1))
xref-location
'function)
(define-sepia-query sepia-var-apropos
"Find/list variables matching regexp."
xref-var-apropos
xref-var-defs
'variable)
(defun sepia-location (name &optional jump-to)
"Find the definition of NAME.
When called interactively (or with JUMP-TO true), go directly
to this location."
(interactive (list (sepia-interactive-arg 'function) t))
(let* ((fl (or (car (xref-location name))
(car (remove-if #'null
(apply #'xref-location (xref-apropos name)))))))
(when (and (car fl) (string-match "^(eval " (car fl)))
(message "Can't find definition of %s in %s." name (car fl))
(setq fl nil))
(if jump-to
(if fl (progn
(sepia-set-found (list fl) 'function)
(sepia-next))
(message "No definition for %s." name))
fl)))
;;;###autoload
(defun sepia-dwim (&optional display-p)
"Try to do the right thing with identifier at point.
* Find all definitions, if thing-at-point is a function
* Find all uses, if thing-at-point is a variable
* Find documentation, if thing-at-point is a module
* Prompt otherwise
"
(interactive "P")
(multiple-value-bind (type obj) (sepia-ident-at-point)
(sepia-set-found nil type)
(let* ((module-doc-p nil)
(ret
(cond
((member type '(?% ?$ ?@)) (xref-var-defs obj))
((or (equal type ?&)
(let (case-fold-search)
(string-match "^[^A-Z]" obj)))
(list (sepia-location obj)))
((sepia-looks-like-module obj)
(setq module-doc-p t)
`((,(sepia-perldoc-this obj) 1 nil nil)))
(t (setq module-doc-p t)
(call-interactively 'sepia-defs)))))
(unless module-doc-p
(if display-p
(sepia-show-locations ret)
(sepia-set-found ret type)
(sepia-next))))))
(defun sepia-rebuild ()
"Rebuild the Xref database."
(interactive)
(xref-rebuild))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Perl motion commands.
;;; XXX -- these are a hack to prevent infinite recursion calling
;;; e.g. beginning-of-defun from beginning-of-defun-function.
;;; `beginning-of-defun' should handle this.
(defmacro sepia-safe-bodf (&optional n)
`(let ((beginning-of-defun-function
(if (and (boundp 'beginning-of-defun-function)
(eq beginning-of-defun-function 'sepia-beginning-of-defun))
nil
beginning-of-defun-function)))
(beginning-of-defun ,n)))
(defmacro sepia-safe-eodf (&optional n)
`(let ((end-of-defun-function
(if (and (boundp 'end-of-defun-function)
(eq end-of-defun-function 'sepia-end-of-defun))
nil
end-of-defun-function)))
(end-of-defun ,n)))
(defun sepia-beginning-of-defun (&optional n)
"Move to beginning of current function.
The prefix argument is the same as for `beginning-of-defun'."
(interactive "p")
(setq n (or n 1))
(ignore-errors
(when (< n 0)
(sepia-end-of-defun (- n))
(setq n 1))
(re-search-backward sepia-sub-re nil nil n)))
(defun sepia-inside-defun ()
"True if point is inside a sub."
(condition-case nil
(save-excursion
(let ((cur (point)))
(re-search-backward sepia-sub-re)
(when (< (point) cur)
(search-forward "{")
(backward-char 1)
(forward-sexp)
(> (point) cur))))
(error nil)))
(defun sepia-end-of-defun (&optional n)
"Move to end of current function.
The prefix argument is the same as for `end-of-defun'."
(interactive "p")
(setq n (or n 1))
(when (< n 0)
(sepia-beginning-of-defun (- n))
(setq n 1))
;; If we're outside a defun, skip to the next
(ignore-errors
(unless (sepia-inside-defun)
(re-search-forward sepia-sub-re)
(forward-char 1))
(dotimes (i n)
(re-search-backward sepia-sub-re)
(search-forward "{")
(backward-char 1)
(forward-sexp))
(point)))
(defun sepia-rename-lexical (old new &optional prompt)
"Replace lexical variable OLD with NEW in the current function.
With prefix argument, query for each replacement. It is an error
to call this outside a function."
(interactive
(let ((old (sepia-thing-at-point 'symbol)))
(list (read-string "Old name: " old nil old)
(read-string "New name: ")
current-prefix-arg)))
(message "(%s %s)" old new)
(unless (sepia-inside-defun)
(error "Can't rename %s outside a defun." old))
(setq old (concat "\\([$%@]\\)\\_<" (regexp-quote old) "\\_>")
new
(concat "\\1" new))
(let ((bod (sepia-beginning-of-defun))
(eod (sepia-end-of-defun)))
(if prompt
(query-replace-regexp old new nil bod eod)
;; (replace-regexp old new nil bod eod)
(goto-char bod)
(while (re-search-forward old eod t)
(replace-match new)))))
(defun sepia-defun-around-point (&optional where)
"Return the text of function around point."
(unless where
(setq where (point)))
(save-excursion
(goto-char where)
(and (sepia-beginning-of-defun)
(match-string-no-properties 1))))
(defun sepia-lexicals-at-point (&optional where)
"Find lexicals in scope at point."
(interactive "d")
(unless where
(setq where (point)))
(let ((subname (sepia-defun-around-point where))
(mod (sepia-buffer-package)))
(xref-lexicals (sepia-perl-name subname mod))))
;;;###autoload
(defun sepia-load-file (file &optional rebuild-p collect-warnings)
"Reload a file (interactively, the current buffer's file).
With REBUILD-P (or a prefix argument when called interactively),
also rebuild the xref database."
(interactive (list (expand-file-name (buffer-file-name))
prefix-arg
(format "*%s errors*" (buffer-file-name))))
(save-buffer)
(when collect-warnings
(let (kill-buffer-query-functions)
(ignore-errors
(kill-buffer collect-warnings))))
(let* ((tmp (sepia-eval (format "do '%s' || ($@ && do { local $Sepia::Debug::STOPDIE; die $@ })" file)
'scalar-context t))
(res (car tmp))
(errs (cdr tmp)))
(message "sepia: %s returned %s" (abbreviate-file-name file)
(if (equal res "") "undef" res))
(when (and collect-warnings
(> (length errs) 1))
(with-current-buffer (get-buffer-create collect-warnings)
(let ((inhibit-read-only t))
(delete-region (point-min) (point-max))
(insert errs)
(sepia-display-errors (point-min) (point-max))
(pop-to-buffer (current-buffer))))))
(when rebuild-p
(xref-rebuild)))
(defvar sepia-found)
(defun sepia-set-found (list &optional type)
(setq list
(remove-if (lambda (x)
(or (not x)
(and (not (car x)) (string= (fourth x) "main"))))
list))
(setq sepia-found (cons -1 list))
(setq sepia-found-refiner (sepia-refiner type)))
(defun sepia-refiner (type)
(case type
(function
(lambda (line ident)
(let ((sub-re (concat "^\\s *sub\\s +.*" ident "\\_>")))
;; Test this because sometimes we get lucky and get the line
;; just right, in which case beginning-of-defun goes to the
;; previous defun.
(or (and line
(progn
(goto-line line)
(beginning-of-defun)
(looking-at sub-re)))
(progn (goto-char (point-min))
(re-search-forward sub-re nil t)))
(beginning-of-line))))
;; Old version -- this may actually work better if
;; beginning-of-defun goes flaky on us.
;; (or (re-search-backward sub-re
;; (sepia-bol-from (point) -20) t)
;; (re-search-forward sub-re
;; (sepia-bol-from (point) 10) t))
;; (beginning-of-line)
(variable
(lambda (line ident)
(let ((var-re (concat "\\_<" ident "\\_>")))
(cond
(line (goto-line line)
(or (re-search-backward var-re (sepia-bol-from (point) -5) t)
(re-search-forward var-re (sepia-bol-from (point) 5) t)))
(t (goto-char (point-min))
(re-search-forward var-re nil t))))))
(t (lambda (line ident) (and line (goto-line line))))))
(defun sepia-next (&optional arg)
"Go to the next thing (e.g. def, use) found by sepia."
(interactive "p")
(or arg (setq arg 1))
(if (cdr sepia-found)
(let ((i (car sepia-found))
(list (cdr sepia-found))
(len (length (cdr sepia-found)))
(next (+ (car sepia-found) arg))
(prompt ""))
(if (and (= len 1) (>= i 0))
(message "No more definitions.")
;; if stepwise found next or previous item, it can cycle
;; around the `sepia-found'. When at first or last item, get
;; a warning
(if (= (abs arg) 1)
(progn
(setq i next)
(if (< i 0)
(setq i (1- len))
(if (>= i len)
(setq i 0)))
(if (= i (1- len))
(setq prompt "Last one! ")
(if (= i 0)
(setq prompt "First one! "))))
;; if we skip several item, when arrive the first or last
;; item, we will stop at the one. But if we already at last
;; item, then keep going
(if (< next 0)
(if (= i 0)
(setq i (mod next len))
(setq i 0
prompt "First one!"))
(if (> next len)
(if (= i (1- len))
(setq i (mod next len))
(setq i (1- len)
prompt "Last one!")))))
(setcar sepia-found i)
(setq next (nth i list))
(let ((file (car next))
(line (cadr next))
(short (nth 2 next))
(mod (nth 3 next)))
(unless file
(setq file (and mod (sepia-find-module-file mod)))
(if file
(setcar next file)
(error "No file for %s." (car next))))
(message "%s at %s:%s. %s" short file line prompt)
(when (file-exists-p file)
(find-file (or file (sepia-find-module-file mod)))
(when sepia-found-refiner
(funcall sepia-found-refiner line short))
(beginning-of-line)
(recenter)))))
(message "No more definitions.")))
(defun sepia-previous (&optional arg)
(interactive "p")
(or arg (setq arg 1))
(sepia-next (- arg)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Completion
(defun sepia-ident-before-point ()
"Find the Perl identifier at or preceding point."
(save-excursion
(skip-syntax-backward " ")
(backward-char 1)
(sepia-ident-at-point)))
(defun sepia-simple-method-before-point ()
"Find the \"simple\" method call before point.
Looks for a simple method called on a variable before point and
returns the list (OBJECT METHOD). For example, \"$x->blah\"
returns '(\"$x\" \"blah\"). Only simple methods are recognized,
because completing anything evaluates it, so completing complex
expressions would lead to disaster."
(when sepia-complete-methods
(let ((end (point))
(bound (max (- (point) 100) (point-min)))
arrow beg)
(save-excursion
;; XXX - can't do this because COMINT's syntax table is weird.
;; (skip-syntax-backward "_w")
(skip-chars-backward "a-zA-Z0-9_")
(when (looking-back "->\\s *" bound)
(setq arrow (search-backward "->" bound))
(skip-chars-backward "a-zA-Z0-9_:")
(cond
;; $x->method
((char-equal (char-before (point)) ?$)
(setq beg (1- (point))))
;; X::Class->method
((multiple-value-bind (type obj) (sepia-ident-at-point)
(and (not type)
(sepia-looks-like-module obj)))
(setq beg (point))))
(when beg
(list (buffer-substring-no-properties beg arrow)
(buffer-substring-no-properties (+ 2 arrow) end)
(buffer-substring-no-properties beg end))))))))
(defun sepia-ident-at-point ()
"Find the Perl identifier at point."
(save-excursion
(let ((orig (point)))
(when (looking-at "[%$@*&]")
(forward-char 1))
(let* ((beg (progn
(when (re-search-backward "[^A-Za-z_0-9:]" nil 'mu)
(forward-char 1))
(point)))
(sigil (if (= beg (point-min))
nil
(char-before (point))))
(end (progn
(when (re-search-forward "[^A-Za-z_0-9:]" nil 'mu)
(forward-char -1))
(point))))
(if (= beg end)
;; try special variables
(if (and (member (char-before orig) '(?$ ?@ ?%))
(member (car (syntax-after orig)) '(1 4 5 7 9)))
(list (char-before orig)
(buffer-substring-no-properties orig (1+ orig)))
'(nil ""))
;; actual thing
(list (when (member sigil '(?$ ?@ ?% ?* ?&)) sigil)
(buffer-substring-no-properties beg end)))))))
(defun sepia-function-at-point ()
"Find the Perl function called at point."
(condition-case nil
(save-excursion
(let ((pt (point))