1 ;;; Sepia -- Simple Emacs-Perl InterAction: ugly, yet effective.
2 ;; (a.k.a. Septik -- Sean's Emacs-Perl Total Integration Kludge.)
4 ;; Author: Sean O'Rourke <seano@cpan.org>
5 ;; Keywords: Perl, languages
7 ;; Copyright (C) 2004-2010 Sean O'Rourke. All rights reserved, some
8 ;; wrongs reversed. This code is distributed under the same terms
13 ;; Sepia is a set of tools for Perl development in Emacs. Its goal is
14 ;; to extend CPerl mode with two contributions: fast code navigation
15 ;; and interactive development. It is inspired by Emacs' current
16 ;; support for a number of other languages, including Lisp, Python,
17 ;; Ruby, and Emacs Lisp.
19 ;; See sepia.texi, which comes with the distribution.
26 ;; try optional modules, but don't bitch if we fail:
27 (ignore-errors (require 'sepia-w3m
))
28 (ignore-errors (require 'sepia-tree
))
29 (ignore-errors (require 'sepia-ido
))
30 (ignore-errors (require 'sepia-snippet
))
31 ;; extensions that should always load (autoload later?)
34 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
35 ;;; Comint communication
37 (defvar sepia-perl5lib nil
38 "* List of extra PERL5LIB directories for `sepia-repl'.")
40 (defvar sepia-program-name
"perl"
41 "* Perl program name.")
43 (defvar sepia-view-pod-function
44 (if (featurep 'w3m
) 'sepia-w3m-view-pod
'sepia-perldoc-buffer
)
45 "* Function to view current buffer's documentation.
47 Useful values include `sepia-w3m-view-pod' and `sepia-perldoc-buffer'.")
49 (defvar sepia-module-list-function
50 (if (featurep 'w3m
) 'w3m-find-file
'browse-url-of-file
)
51 "* Function to view a list of installed modules.
53 Useful values include `w3m-find-file' and `browse-url-of-file'.")
55 (defvar sepia-complete-methods t
56 "* Non-nil if Sepia should try to complete methods for \"$x->\".
58 NOTE: this feature can be problematic, since it evaluates the
59 object in order to find its type. Currently completion is only
60 attempted for objects that are simple scalars.")
62 (defvar sepia-indent-expand-abbrev t
63 "* If non-NIL, `sepia-indent-or-complete' tries `expand-abbrev'.")
65 (defvar sepia-use-completion t
66 "* Use completion based on Xref database.
68 Turning this off may speed up some operations, if you don't mind
71 (defvar sepia-eval-defun-include-decls t
72 "* Generate and use a declaration list for `sepia-eval-defun'.
73 Without this, code often will not parse; with it, evaluation may
74 be a bit less responsive. Note that since this only includes
75 subs from the evaluation package, it may not always work.")
77 (defvar sepia-prefix-key
"\M-."
78 "* Prefix for functions in `sepia-keymap'.")
80 ;;; User options end here.
82 (defvar sepia-process nil
83 "The perl process with which we're interacting.")
84 (defvar sepia-output nil
85 "Current perl output for a response to `sepia-eval-raw', appended
86 to by `sepia-collect-output'.")
87 (defvar sepia-passive-output
""
88 "Current perl output for miscellaneous user interaction, used to
89 look for \";;;###\" lisp evaluation markers.")
91 (defvar sepia-perl-builtins nil
92 "List of Perl builtins for completion.")
94 (defun sepia-collect-output (string)
95 "Collect perl output for `sepia-eval-raw' into sepia-output."
96 (setq sepia-output
(concat sepia-output string
))
99 (defun sepia-eval-raw (str)
100 "Evaluate perl code STR, returning a pair (RESULT-STRING . OUTPUT)."
101 (sepia-ensure-process)
104 (let ((sepia-output "")
106 (with-current-buffer (process-buffer sepia-process
)
107 (setq ocpof comint-preoutput-filter-functions
108 comint-preoutput-filter-functions
109 '(sepia-collect-output)))
110 (setq str
(concat "local $Sepia::STOPDIE=0;"
111 "local $Sepia::STOPWARN=0;"
112 "{ package " (sepia-buffer-package) ";"
114 (comint-send-string sepia-process
115 (concat (format "<<%d\n" (length str
)) str
))
116 (while (not (and sepia-output
117 (string-match "> $" sepia-output
)))
118 (accept-process-output sepia-process
))
119 (if (string-match "^;;;[0-9]+\n" sepia-output
)
121 (let* ((x (read-from-string sepia-output
122 (+ (match-beginning 0) 3)))
125 (prog1 (substring sepia-output
(1+ pos
) (+ len pos
1))
126 (setq start
(+ pos len
1))))
127 (and (string-match ";;;[0-9]+\n" sepia-output start
)
128 (let* ((x (read-from-string
130 (+ (match-beginning 0) 3)))
133 (substring sepia-output
(1+ pos
) (+ len pos
1)))))
134 (cons sepia-output nil
)))
135 (with-current-buffer (process-buffer sepia-process
)
136 (setq comint-preoutput-filter-functions ocpof
)))))
138 (defun sepia-eval (str &optional context detailed
)
139 "Evaluate STR in CONTEXT (void by default), and return its result
140 as a Lisp object. If DETAILED is specified, return a
141 pair (RESULT . OUTPUT)."
142 (let* ((tmp (sepia-eval-raw
145 (concat "Sepia::tolisp([" str
"])"))
147 (concat "Sepia::tolisp(scalar(" str
"))"))
148 (t (concat str
";1")))))
151 (setq res
(if context
152 (if (string= res
"") "" (car (read-from-string res
)))
158 (defun sepia-call (fn context
&rest args
)
159 "Call perl function FN in CONTEXT with arguments ARGS, returning
160 its result as a Lisp value."
161 (sepia-eval (concat fn
"(" (mapconcat #'sepia-lisp-to-perl args
", ") ")")
164 (defun sepia-watch-for-eval (string)
165 "Monitor inferior Perl output looking for Lisp evaluation
166 requests. The format for these requests is
167 \"\\n;;;###LENGTH\\nDATA\". Only one such request can come from
168 each inferior Perl prompt."
169 (setq sepia-passive-output
(concat sepia-passive-output string
))
171 ((string-match "^;;;###[0-9]+" sepia-passive-output
)
172 (if (string-match "^;;;###\\([0-9]+\\)\n\\(?:.\\|\n\\)*\n\\(.*> \\)"
173 sepia-passive-output
)
174 (let* ((len (car (read-from-string
175 (match-string 1 sepia-passive-output
))))
176 (pos (1+ (match-end 1)))
177 (res (ignore-errors (eval (car (read-from-string
178 sepia-passive-output pos
181 (substring sepia-passive-output pos
(+ pos len
)) res
)
182 (goto-char (point-max))
183 (insert (substring sepia-passive-output
(+ 1 pos len
)))
184 (set-marker (process-mark (get-buffer-process (current-buffer)))
186 (setq sepia-passive-output
""))
188 (t (setq sepia-passive-output
"") string
)))
191 (defvar sepia-metapoint-map
192 (let ((map (make-sparse-keymap)))
193 (when (featurep 'ido
)
194 (define-key map
"j" 'sepia-jump-to-symbol
))
195 (dolist (kv '(("c" . sepia-callers
)
196 ("C" . sepia-callees
)
197 ("a" . sepia-apropos
)
198 ("A" . sepia-var-apropos
)
199 ("v" . sepia-var-uses
)
200 ("V" . sepia-var-defs
)
201 ;; ("V" . sepia-var-assigns)
202 ("\M-." . sepia-dwim
)
203 ;; ("\M-." . sepia-location)
204 ("d" . sepia-location
)
206 ("r" . sepia-rebuild
)
207 ("m" . sepia-module-find
)
210 ("p" . sepia-perldoc-this
)
211 ("l" . sepia-pod-follow-link-at-point
)
212 ("u" . sepia-describe-object
)))
213 (define-key map
(car kv
) (cdr kv
)))
215 "Keymap for Sepia functions. This is just an example of how you
216 might want to bind your keys, which works best when bound to
219 (defvar sepia-shared-map
220 (let ((map (make-sparse-keymap)))
221 (define-key map sepia-prefix-key sepia-metapoint-map
)
222 (define-key map
"\M-," 'sepia-next
)
223 (define-key map
"\C-\M-x" 'sepia-eval-defun
)
224 (define-key map
"\C-c\C-l" 'sepia-load-file
)
225 (define-key map
"\C-c\C-p" 'sepia-view-pod
) ;was cperl-pod-spell
226 (define-key map
"\C-c\C-d" 'cperl-perldoc
)
227 (define-key map
"\C-c\C-t" 'sepia-repl
)
228 (define-key map
"\C-c\C-r" 'sepia-eval-region
)
229 (define-key map
"\C-c\C-s" 'sepia-scratch
)
230 (define-key map
"\C-c\C-e" 'sepia-eval-expression
)
231 (define-key map
"\C-c!" 'sepia-set-cwd
)
232 (define-key map
(kbd "TAB") 'sepia-indent-or-complete
)
234 "Sepia bindings common to all modes.")
237 (defun sepia-eval-region (beg end
)
239 (sepia-eval (buffer-substring beg end
)))
242 (defun sepia-perldoc-this (name)
243 "View perldoc for module at point."
244 (interactive (list (sepia-interactive-arg 'module
)))
245 (let ((wc (current-window-configuration))
246 (old-pd (symbol-function 'w3m-about-perldoc
))
247 (old-pdb (symbol-function 'w3m-about-perldoc-buffer
))
249 (condition-case stuff
250 (flet ((w3m-about-perldoc (&rest args
)
251 (let ((res (apply old-pd args
)))
252 (or res
(error "lose: %s" args
))))
253 (w3m-about-perldoc-buffer (&rest args
)
254 (let ((res (apply old-pdb args
)))
255 (or res
(error "lose: %s" args
)))))
256 (funcall (if (featurep 'w3m
) 'w3m-perldoc
'cperl-perldoc
) name
)
257 (setq buf
(current-buffer)))
258 (error (set-window-configuration wc
)))
259 (set-window-configuration wc
)
260 (pop-to-buffer buf t
)))
262 (defun sepia-view-pod ()
263 "View POD for the current buffer."
265 (funcall sepia-view-pod-function
))
267 (defun sepia-module-list ()
268 "List installed modules with links to their documentation.
270 This lists not just top-level packages appearing in packlist
271 files, but all documented modules on the system, organized by
274 (let ((file "/tmp/modlist.html"))
275 ;; (unless (file-exists-p file)
276 (sepia-eval-raw (format "Sepia::html_module_list(\"%s\")" file
))
277 (funcall sepia-module-list-function file
)))
279 (defun sepia-package-list ()
280 "List installed packages with links to their documentation.
282 This lists only top-level packages appearing in packlist files.
283 For modules within packages, see `sepia-module-list'."
285 (let ((file "/tmp/packlist.html"))
286 ;; (unless (file-exists-p file)
287 (sepia-eval-raw (format "Sepia::html_package_list(\"%s\")" file
))
288 (funcall sepia-module-list-function file
)))
290 (defun sepia-perldoc-buffer ()
291 "View current buffer's POD using pod2html and `browse-url'.
293 Interactive users should call `sepia-view-pod'."
294 (let ((buffer (get-buffer-create "*sepia-pod*"))
295 (errs (get-buffer-create "*sepia-pod-errors*"))
296 (inhibit-read-only t
))
297 (with-current-buffer buffer
(erase-buffer))
298 (save-window-excursion
299 (shell-command-on-region (point-min) (point-max) "pod2html"
301 (with-current-buffer buffer
(browse-url-of-buffer))))
303 (defun sepia-perl-name (sym &optional mod
)
304 "Convert a Perl name to a Lisp name."
305 (setq sym
(substitute ?_ ?-
(if (symbolp sym
) (symbol-name sym
) sym
)))
307 (concat mod
"::" sym
)
310 (defun sepia-live-p ()
311 (and (processp sepia-process
)
312 (eq (process-status sepia-process
) 'run
)))
314 (defun sepia-ensure-process (&optional remote-host
)
315 (unless (sepia-live-p)
316 (with-current-buffer (get-buffer-create "*sepia-repl*")
318 (set (make-local-variable 'sepia-passive-output
) ""))
320 (comint-exec (get-buffer-create "*sepia-repl*")
321 "attachtty" "attachtty" nil
323 (let ((stuff (split-string sepia-program-name nil t
)))
324 (comint-exec (get-buffer-create "*sepia-repl*")
325 "perl" (car stuff
) nil
328 (mapcar (lambda (x) (concat "-I" x
)) sepia-perl5lib
)
329 '("-MSepia" "-MSepia::Xref"
330 "-e" "Sepia::repl")))))
331 (setq sepia-process
(get-buffer-process "*sepia-repl*"))
332 (accept-process-output sepia-process
1)
333 ;; Steal a bit from gud-common-init:
335 (setq gud-last-last-frame nil
)
336 (set-process-filter sepia-process
'gud-filter
)
337 (set-process-sentinel sepia-process
'gud-sentinel
)))
340 (defun sepia-repl (&optional remote-host
)
341 "Start the Sepia REPL."
342 (interactive (list (and current-prefix-arg
343 (read-string "Host: "))))
344 (sepia-init) ;; set up keymaps, etc.
345 (sepia-ensure-process remote-host
)
346 (pop-to-buffer (get-buffer "*sepia-repl*")))
348 (defun sepia-cont-or-restart ()
350 (if (get-buffer-process (current-buffer))
351 (gud-cont current-prefix-arg
)
354 (defvar sepia-repl-mode-map
355 (let ((map (copy-keymap sepia-shared-map
)))
356 (set-keymap-parent map gud-mode-map
)
357 (define-key map
(kbd "<tab>") 'comint-dynamic-complete
)
358 (define-key map
"\C-a" 'comint-bol
)
359 (define-key map
"\C-c\C-r" 'sepia-cont-or-restart
)
362 "Keymap for Sepia interactive mode.")
364 (define-derived-mode sepia-repl-mode gud-mode
"Sepia REPL"
365 "Major mode for the Sepia REPL.
367 \\{sepia-repl-mode-map}"
368 ;; (set (make-local-variable 'comint-use-prompt-regexp) t)
369 (modify-syntax-entry ?
: "_")
370 (modify-syntax-entry ?
> ".")
371 (set (make-local-variable 'comint-prompt-regexp
) "^[^>\n]*> *")
372 (set (make-local-variable 'gud-target-name
) "sepia")
373 (set (make-local-variable 'gud-marker-filter
) 'sepia-gud-marker-filter
)
374 (set (make-local-variable 'gud-minor-mode
) 'sepia
)
375 (sepia-install-eldoc)
377 (setq gud-comint-buffer
(current-buffer))
378 (setq gud-last-last-frame nil
)
379 (setq gud-sepia-acc nil
)
381 (gud-def gud-break
",break %f:%l" "\C-b" "Set breakpoint at current line.")
382 (gud-def gud-step
",step %p" "\C-s" "Step one line.")
383 (gud-def gud-next
",next %p" "\C-n" "Step one line, skipping calls.")
384 (gud-def gud-cont
",continue" "\C-r" "Continue.")
385 (gud-def gud-print
"%e" "\C-p" "Evaluate something.")
386 (gud-def gud-remove
",delete %l %f" "\C-d" "Delete current breakpoint.")
387 ;; Sadly, this hoses our keybindings.
388 (compilation-shell-minor-mode 1)
389 (set (make-local-variable 'comint-dynamic-complete-functions
)
390 '(sepia-complete-symbol comint-dynamic-complete-filename
))
391 (set (make-local-variable 'comint-preoutput-filter-functions
)
392 '(sepia-watch-for-eval))
393 (run-hooks 'sepia-repl-mode-hook
)
396 (defvar gud-sepia-acc nil
397 "Accumulator for `sepia-gud-marker-filter'.")
399 (defun sepia-gud-marker-filter (str)
402 (concat gud-sepia-acc str
)
404 (while (string-match "_<\\([^:>]+\\):\\([0-9]+\\)>\\(.*\\)" gud-sepia-acc
)
405 (setq gud-last-last-frame gud-last-frame
407 (match-string 1 gud-sepia-acc
)
408 (string-to-number (match-string 2 gud-sepia-acc
)))
409 gud-sepia-acc
(match-string 3 gud-sepia-acc
)))
411 (if (string-match "\\(_<.*\\)" gud-sepia-acc
)
412 (match-string 1 gud-sepia-acc
)
416 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
419 (defun define-xref-function (package name doc
)
420 "Define a lisp mirror for a low-level Sepia function."
421 (let ((lisp-name (intern (format "xref-%s" name
)))
422 (pl-name (sepia-perl-name name package
)))
423 (fmakunbound lisp-name
)
424 (eval `(defun ,lisp-name
(&rest args
)
426 (apply #'sepia-call
,pl-name
'list-context args
)))))
428 (defun define-modinfo-function (name &optional doc context
)
429 "Define a lisp mirror for a function from Module::Info."
430 (let ((name (intern (format "sepia-module-%s" name
)))
431 (pl-func (sepia-perl-name name
))
432 (full-doc (concat (or doc
"") "
434 This function uses Module::Info, so it does not require that the
435 module in question be loaded.")))
436 (when (fboundp name
) (fmakunbound name
))
437 (eval `(defun ,name
(mod)
439 (interactive (list (sepia-interactive-arg 'module
)))
441 (sepia-call "Sepia::module_info" ',(or context
'scalar-context
)
445 (defun sepia-thing-at-point (what)
446 "Like `thing-at-point', but hacked to avoid REPL prompt."
447 (let ((th (thing-at-point what
)))
448 (and th
(not (string-match "[ >]$" th
)) th
)))
450 (defvar sepia-sub-re
"^ *sub\\s +\\(.+\\_>\\)")
452 (defvar sepia-history nil
)
454 (defun sepia-interactive-arg (&optional sepia-arg-type
)
455 "Default argument for most Sepia functions. TYPE is a symbol --
456 either 'file to look for a file, or anything else to use the
458 (let* ((default (case sepia-arg-type
459 (file (or (thing-at-point 'file
) (buffer-file-name)))
460 (t (sepia-thing-at-point 'symbol
))))
461 (text (capitalize (symbol-name sepia-arg-type
)))
463 (lambda (str &rest blah
)
464 (let ((completions (xref-completions
467 (variable "VARIABLE")
471 (when (eq sepia-arg-type
'module
)
473 (remove-if (lambda (x) (string-match "::$" x
)) completions
)))
476 (format "%s [%s]: " text default
)
477 (format "%s: " text
)))
478 (ret (if sepia-use-completion
479 (completing-read prompt
'blah-choices nil nil nil
'sepia-history
481 (read-string prompt nil
'sepia-history default
))))
482 (push ret sepia-history
)
485 (defun sepia-interactive-module ()
486 "Guess which module we should look things up in. Prompting for a
487 module all the time is a PITA, but I don't think this (choosing
488 the current file's module) is a good alternative, either. Best
489 would be to choose the module based on what we know about the
491 (let ((xs (xref-file-modules (buffer-file-name))))
492 (if (= (length xs
) 1)
496 (defun sepia-maybe-echo (result &optional print-message
)
498 (message "%s" result
))
501 (defun sepia-find-module-file (mod)
502 (or (sepia-module-file mod
)
503 (car (xref-guess-module-file mod
))))
505 (defun sepia-module-find (mod)
506 "Find the file defining module MOD."
507 (interactive (list (sepia-interactive-arg 'module
)))
508 (let ((fn (sepia-find-module-file mod
)))
511 (message "Module %s in %s." mod fn
)
512 (pop-to-buffer (find-file-noselect (expand-file-name fn
))))
513 (message "Can't find module %s." mod
))))
515 (defmacro ifa
(test then
&rest else
)
517 (if it
,then
,@else
)))
519 (defvar sepia-found-refiner nil
)
521 (defun sepia-show-locations (locs &optional unobtrusive
)
522 (setq locs
(remove nil locs
)) ; XXX where's nil from?
524 (with-current-buffer (get-buffer-create "*sepia-places*")
525 (let ((inhibit-read-only t
))
527 (insert (format "-*- mode: grep; default-directory: %S -*-\n\n"
529 (dolist (loc (sort locs
531 (or (string< (car a
) (car b
))
532 (and (string= (car a
) (car b
))
533 (< (second a
) (second b
)))))))
534 (destructuring-bind (file line name
&rest blah
) loc
535 (let ((str (ifa (find-buffer-visiting file
)
536 (with-current-buffer it
537 (ifa sepia-found-refiner
538 (funcall it line name
)
540 (unless (= (line-number-at-pos) line
)
541 (message "line for %s was %d, now %d" name line
542 (line-number-at-pos)))
543 (setq line
(line-number-at-pos))
545 (buffer-substring (sepia-bol-from (point))
546 (sepia-eol-from (point)))))
547 (if (> (length tmpstr
) 60)
548 (concat "\n " tmpstr
)
551 (insert (format "%s:%d:%s\n" (abbreviate-file-name file
) line str
)))))
552 (insert "\nGrep finished (matches found).\n")
555 (save-window-excursion (next-error nil t
))
557 (message "No matches found.")))
559 (defmacro define-sepia-query
(name doc
&optional gen test prompt
)
560 "Define a sepia querying function."
561 `(defun ,name
(ident &optional module file line display-p
)
564 With prefix arg, display matches in a `grep-mode' buffer.
565 Without, go to the first match; calling `sepia-next' will cycle
566 through subsequent matches.
568 Depending on the query, MODULE, FILE, and LINE may be used to
569 narrow the results, as long as doing so leaves some matches.
570 When called interactively, they are taken from the current
573 (interactive (list (sepia-interactive-arg ,(or prompt
''function
))
574 (sepia-interactive-module)
576 (line-number-at-pos (point))
581 `(let ((tmp (,gen ident module file line
)))
582 (or (mapcan #',test tmp
) tmp
))
583 `(,gen ident module file line
))))
584 (sepia-show-locations ret
(not display-p
)))))
586 (define-sepia-query sepia-defs
587 "Find all definitions of sub."
591 (define-sepia-query sepia-callers
592 "Find callers of FUNC."
596 (define-sepia-query sepia-callees
597 "Find a sub's callees."
601 (define-sepia-query sepia-var-defs
602 "Find a var's definitions."
604 (lambda (x) (setf (third x
) ident
) (list x
))
607 (define-sepia-query sepia-var-uses
610 (lambda (x) (setf (third x
) ident
) (list x
))
613 (define-sepia-query sepia-var-assigns
614 "Find/list assignments to a variable."
616 (lambda (x) (setf (third x
) ident
) (list x
))
619 (defalias 'sepia-package-defs
'sepia-module-describe
)
621 (define-sepia-query sepia-apropos
622 "Find/list subroutines matching regexp."
623 (lambda (name &rest blah
) (xref-apropos name
1))
627 (define-sepia-query sepia-var-apropos
628 "Find/list variables matching regexp."
633 (defun sepia-location (name &optional jump-to
)
634 "Find the definition of NAME.
636 When called interactively (or with JUMP-TO true), go directly
638 (interactive (list (sepia-interactive-arg 'function
) t
))
639 (let* ((fl (or (car (xref-location name
))
640 (car (remove-if #'null
641 (apply #'xref-location
(xref-apropos name
)))))))
642 (when (and (car fl
) (string-match "^(eval " (car fl
)))
643 (message "Can't find definition of %s in %s." name
(car fl
))
647 (sepia-set-found (list fl
) 'function
)
649 (message "No definition for %s." name
))
653 (defun sepia-dwim (&optional display-p
)
654 "Try to do the right thing with identifier at point.
655 * Find all definitions, if thing-at-point is a function
656 * Find all uses, if thing-at-point is a variable
657 * Find documentation, if thing-at-point is a module
661 (multiple-value-bind (type obj
) (sepia-ident-at-point)
662 (let* ((module-doc-p nil
)
665 ((member type
'(?% ?$ ?
@)) (xref-var-defs obj
))
667 (let (case-fold-search)
668 (string-match "^[^A-Z]" obj
)))
669 (list (sepia-location obj
)))
670 ((sepia-looks-like-module obj
)
671 (setq module-doc-p t
)
672 `((,(sepia-perldoc-this obj
) 1 nil nil
)))
673 (t (setq module-doc-p t
)
674 (call-interactively 'sepia-defs
)))))
676 (sepia-show-locations ret
(not display-p
))))))
678 (defun sepia-rebuild ()
679 "Rebuild the Xref database."
683 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
684 ;;; Perl motion commands.
686 ;;; XXX -- these are a hack to prevent infinite recursion calling
687 ;;; e.g. beginning-of-defun from beginning-of-defun-function.
688 ;;; `beginning-of-defun' should handle this.
689 (defmacro sepia-safe-bodf
(&optional n
)
690 `(let ((beginning-of-defun-function
691 (if (and (boundp 'beginning-of-defun-function
)
692 (eq beginning-of-defun-function
'sepia-beginning-of-defun
))
694 beginning-of-defun-function
)))
695 (beginning-of-defun ,n
)))
697 (defmacro sepia-safe-eodf
(&optional n
)
698 `(let ((end-of-defun-function
699 (if (and (boundp 'end-of-defun-function
)
700 (eq end-of-defun-function
'sepia-end-of-defun
))
702 end-of-defun-function
)))
705 (defun sepia-beginning-of-defun (&optional n
)
706 "Move to beginning of current function.
708 The prefix argument is the same as for `beginning-of-defun'."
713 (sepia-end-of-defun (- n
))
715 (re-search-backward sepia-sub-re nil nil n
)))
717 (defun sepia-inside-defun ()
718 "True if point is inside a sub."
722 (re-search-backward sepia-sub-re
)
723 (when (< (point) cur
)
730 (defun sepia-end-of-defun (&optional n
)
731 "Move to end of current function.
733 The prefix argument is the same as for `end-of-defun'."
737 (sepia-beginning-of-defun (- n
))
739 ;; If we're outside a defun, skip to the next
741 (unless (sepia-inside-defun)
742 (re-search-forward sepia-sub-re
)
745 (re-search-backward sepia-sub-re
)
751 (defun sepia-rename-lexical (old new
&optional prompt
)
752 "Replace lexical variable OLD with NEW in the current function.
754 With prefix argument, query for each replacement. It is an error
755 to call this outside a function."
757 (let ((old (sepia-thing-at-point 'symbol
)))
758 (list (read-string "Old name: " old nil old
)
759 (read-string "New name: ")
760 current-prefix-arg
)))
761 (message "(%s %s)" old new
)
762 (unless (sepia-inside-defun)
763 (error "Can't rename %s outside a defun." old
))
764 (setq old
(concat "\\([$%@]\\)\\_<" (regexp-quote old
) "\\_>")
767 (let ((bod (sepia-beginning-of-defun))
768 (eod (sepia-end-of-defun)))
770 (query-replace-regexp old new nil bod eod
)
771 ;; (replace-regexp old new nil bod eod)
773 (while (re-search-forward old eod t
)
774 (replace-match new
)))))
776 (defun sepia-defun-around-point (&optional where
)
777 "Return the text of function around point."
779 (setq where
(point)))
782 (and (sepia-beginning-of-defun)
783 (match-string-no-properties 1))))
785 (defun sepia-lexicals-at-point (&optional where
)
786 "Find lexicals in scope at point."
789 (setq where
(point)))
790 (let ((subname (sepia-defun-around-point where
))
791 (mod (sepia-buffer-package)))
792 (xref-lexicals (sepia-perl-name subname mod
))))
795 (defun sepia-load-file (file &optional rebuild-p collect-warnings
)
796 "Reload a file (interactively, the current buffer's file).
798 With REBUILD-P (or a prefix argument when called interactively),
799 also rebuild the xref database."
800 (interactive (list (expand-file-name (buffer-file-name))
802 (format "*%s errors*" (buffer-file-name))))
804 (when collect-warnings
805 (let (kill-buffer-query-functions)
807 (kill-buffer collect-warnings
))))
808 (let* ((tmp (sepia-eval (format "do '%s' || ($@ && do { local $Sepia::Debug::STOPDIE; die $@ })" file
)
812 (message "sepia: %s returned %s" (abbreviate-file-name file
)
813 (if (equal res
"") "undef" res
))
814 (when (and collect-warnings
816 (with-current-buffer (get-buffer-create collect-warnings
)
817 (let ((inhibit-read-only t
))
818 (delete-region (point-min) (point-max))
820 (sepia-display-errors (point-min) (point-max))
821 (pop-to-buffer (current-buffer))))))
827 (defun sepia-set-found (list &optional type
)
829 (remove-if (lambda (x)
831 (and (not (car x
)) (string= (fourth x
) "main"))))
833 (setq sepia-found
(cons -
1 list
))
834 (setq sepia-found-refiner
(sepia-refiner type
)))
836 (defun sepia-refiner (type)
840 (let ((sub-re (concat "^\\s *sub\\s +.*" ident
"\\_>")))
841 ;; Test this because sometimes we get lucky and get the line
842 ;; just right, in which case beginning-of-defun goes to the
848 (looking-at sub-re
)))
849 (progn (goto-char (point-min))
850 (re-search-forward sub-re nil t
)))
851 (beginning-of-line))))
852 ;; Old version -- this may actually work better if
853 ;; beginning-of-defun goes flaky on us.
854 ;; (or (re-search-backward sub-re
855 ;; (sepia-bol-from (point) -20) t)
856 ;; (re-search-forward sub-re
857 ;; (sepia-bol-from (point) 10) t))
858 ;; (beginning-of-line)
861 (let ((var-re (concat "\\_<" ident
"\\_>")))
863 (line (goto-line line
)
864 (or (re-search-backward var-re
(sepia-bol-from (point) -
5) t
)
865 (re-search-forward var-re
(sepia-bol-from (point) 5) t
)))
866 (t (goto-char (point-min))
867 (re-search-forward var-re nil t
))))))
868 (t (lambda (line ident
) (and line
(goto-line line
))))))
870 (defun sepia-next (&optional arg
)
871 "Go to the next thing (e.g. def, use) found by sepia."
873 (save-window-excursion (next-error arg
)))
875 (defun sepia-previous (&optional arg
)
876 "Go to the previous thing (e.g. def, use) found by sepia."
878 (or arg
(setq arg
1))
879 (sepia-next (- arg
)))
881 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
884 (defun sepia-ident-before-point ()
885 "Find the Perl identifier at or preceding point."
887 (skip-syntax-backward " ")
889 (sepia-ident-at-point)))
891 (defun sepia-simple-method-before-point ()
892 "Find the \"simple\" method call before point.
894 Looks for a simple method called on a variable before point and
895 returns the list (OBJECT METHOD). For example, \"$x->blah\"
896 returns '(\"$x\" \"blah\"). Only simple methods are recognized,
897 because completing anything evaluates it, so completing complex
898 expressions would lead to disaster."
899 (when sepia-complete-methods
901 (bound (max (- (point) 100) (point-min)))
904 ;; XXX - can't do this because COMINT's syntax table is weird.
905 ;; (skip-syntax-backward "_w")
906 (skip-chars-backward "a-zA-Z0-9_")
907 (when (looking-back "->\\s *" bound
)
908 (setq arrow
(search-backward "->" bound
))
909 (skip-chars-backward "a-zA-Z0-9_:")
912 ((char-equal (char-before (point)) ?$
)
913 (setq beg
(1- (point))))
915 ((multiple-value-bind (type obj
) (sepia-ident-at-point)
917 (sepia-looks-like-module obj
)))
920 (list (buffer-substring-no-properties beg arrow
)
921 (buffer-substring-no-properties (+ 2 arrow
) end
)
922 (buffer-substring-no-properties beg end
))))))))
924 (defun sepia-ident-at-point ()
925 "Find the Perl identifier at point."
927 (let ((orig (point)))
928 (when (looking-at "[%$@*&]")
931 (when (re-search-backward "[^A-Za-z_0-9:]" nil
'mu
)
934 (sigil (if (= beg
(point-min))
936 (char-before (point))))
938 (when (re-search-forward "[^A-Za-z_0-9:]" nil
'mu
)
942 ;; try special variables
943 (if (and (member (char-before orig
) '(?$ ?
@ ?%
))
944 (member (car (syntax-after orig
)) '(1 4 5 7 9)))
945 (list (char-before orig
)
946 (buffer-substring-no-properties orig
(1+ orig
)))
949 (list (when (member sigil
'(?$ ?
@ ?% ?
* ?
&)) sigil
)
950 (buffer-substring-no-properties beg end
)))))))
952 (defun sepia-function-at-point ()
953 "Find the Perl function called at point."
958 (sepia-beginning-of-defun)
962 (when (and (>= pt bof
) (< pt
(point)))
963 (sepia-beginning-of-defun)
964 (when (and (= (point) bof
) (looking-at "\\s *sub\\s +"))
965 (forward-char (length (match-string 0)))
966 (concat (or (sepia-buffer-package) "")
968 (cadr (sepia-ident-at-point)))))))
971 (defun sepia-repl-complete ()
972 "Try to complete the word at point in the REPL.
973 Just like `sepia-complete-symbol', except that it also completes
978 (defvar sepia-shortcuts
980 "break" "eval" "lsbreak" "quit" "size" "wantarray"
981 "cd" "format" "methods" "reload" "strict" "who"
982 "debug" "freload" "package" "restart" "test"
983 "define" "help" "pdl" "save" "time"
984 "delete" "load" "pwd" "shell" "undef"
986 "List of currently-defined REPL shortcuts.
988 XXX: this needs to be updated whenever you add one on the Perl side.")
990 (defun sepia-complete-symbol ()
991 "Try to complete the word at point.
992 The word may be either a global or lexical variable if it has a
993 sigil, a module, or a function. The function currently ignores
994 module qualifiers, which may be annoying in larger programs.
996 The function is intended to be bound to \\M-TAB, like
997 `lisp-complete-symbol'."
999 (let ((win (get-buffer-window "*Completions*" 0))
1004 (if (and (eq last-command this-command
)
1005 win
(window-live-p win
) (window-buffer win
)
1006 (buffer-name (window-buffer win
)))
1008 ;; If this command was repeated, and
1009 ;; there's a fresh completion window with a live buffer,
1010 ;; and this command is repeated, scroll that window.
1011 (with-current-buffer (window-buffer win
)
1012 (if (pos-visible-in-window-p (point-max) win
)
1013 (set-window-start win
(point-min))
1014 (save-selected-window
1018 ;; Otherwise actually do completion:
1019 ;; 0 - try a shortcut
1020 (when (eq major-mode
'sepia-repl-mode
)
1023 (when (looking-at ",\\([a-z]+\\)$")
1024 (let ((str (match-string 1)))
1025 (setq len
(length str
)
1026 completions
(all-completions str sepia-shortcuts
))))))
1027 ;; 1 - Look for a method call:
1029 (setq meth
(sepia-simple-method-before-point))
1031 (setq len
(length (caddr meth
))
1032 completions
(xref-method-completions
1033 (cons 'expr
(format "'%s'" (car meth
)))
1036 type
(format "%s->" (car meth
)))))
1037 ;; 1.x - look for a module
1040 (and (looking-back " *\\(?:use\\|require\\|package\\|no\\)\\s +[^ ]*" (sepia-bol-from (point)))
1041 (xref-apropos-module
1042 (multiple-value-bind (typ name
)
1043 (sepia-ident-before-point)
1044 (setq len
(length name
))
1048 (multiple-value-bind (typ name
) (sepia-ident-before-point)
1050 ;; 2 - look for a regular function/variable/whatever
1052 len
(+ (if type
1 0) (length name
))
1058 (format "%c%s" type x
)))
1068 (and (eq major-mode
'sepia-mode
)
1069 (sepia-function-at-point))))))
1070 ;; 3 - try a Perl built-in
1071 (when (and (not completions
)
1072 (or (not type
) (eq type ?
&)))
1073 (when (string-match ".*::([^:]+)$" name
)
1074 (setq name
(match-string 1 name
)))
1075 (setq completions
(all-completions name sepia-perl-builtins
)))
1076 (case (length completions
)
1077 (0 (message "No completions.") nil
)
1078 (1 ;; XXX - skip sigil to match s-i-before-point
1079 (delete-region (- (point) len
) (point))
1080 (insert (car completions
))
1081 ;; Hide stale completions buffer (stolen from lisp.el).
1082 (if win
(with-selected-window win
(bury-buffer))) t
)
1084 (new (try-completion "" completions
)))
1085 (if (<= (length new
) (+ (length old
) (if type
1 0)))
1086 (with-output-to-temp-buffer "*Completions*"
1087 (display-completion-list completions
))
1088 (let ((win (get-buffer-window "*Completions*" 0)))
1089 (if win
(with-selected-window win
(bury-buffer))))
1090 (delete-region (- (point) len
) (point))
1094 (defun sepia-indent-or-complete ()
1095 "Indent the current line or complete the symbol around point.
1097 Specifically, try completion when indentation doesn't move point.
1098 This function is intended to be bound to TAB."
1100 (let ((pos (point)))
1101 (let (beginning-of-defun-function
1102 end-of-defun-function
)
1103 (cperl-indent-command))
1104 (when (and (= pos
(point))
1106 (or (eq last-command
'sepia-indent-or-complete
)
1107 (looking-at "\\_>")))
1108 (when (or (not sepia-indent-expand-abbrev
)
1109 (and (not (expand-abbrev))
1110 ;; XXX this shouldn't be necessary, but
1111 ;; expand-abbrev returns NIL for e.g. the "else"
1114 (sepia-complete-symbol)))))
1116 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1119 (defvar sepia-mode-map
1120 (let ((map (copy-keymap sepia-shared-map
)))
1121 (set-keymap-parent map cperl-mode-map
)
1122 (define-key map
"\C-c\C-h" nil
)
1124 "Keymap for Sepia mode.")
1127 (define-derived-mode sepia-mode cperl-mode
"Sepia"
1128 "Major mode for Perl editing, derived from cperl mode.
1131 (sepia-install-eldoc)
1133 (set (make-local-variable 'beginning-of-defun-function
)
1134 'sepia-beginning-of-defun
)
1135 (set (make-local-variable 'end-of-defun-function
)
1136 'sepia-end-of-defun
)
1137 (setq indent-line-function
'sepia-indent-line
))
1139 (defun sepia-init ()
1140 "Perform the initialization necessary to start Sepia."
1142 ;; Create glue wrappers for Module::Info funcs.
1143 (unless (fboundp 'xref-completions
)
1144 (dolist (x '((name "Find module name.\n\nDoes not require loading.")
1145 (version "Find module version.\n\nDoes not require loading.")
1146 (inc-dir "Find directory in which this module was found.\n\nDoes not require loading.")
1147 (file "Absolute path of file defining this module.\n\nDoes not require loading.")
1148 (is-core "Guess whether or not a module is part of the core distribution.
1149 Does not require loading.")
1150 (modules-used "List modules used by this module.\n\nRequires loading." list-context
)
1151 (packages-inside "List sub-packages in this module.\n\nRequires loading." list-context
)
1152 (superclasses "List module's superclasses.\n\nRequires loading." list-context
)))
1153 (apply #'define-modinfo-function x
))
1154 ;; Create low-level wrappers for Sepia
1155 (dolist (x '((completions "Find completions in the symbol table.")
1156 (method-completions "Complete on an object's methods.")
1157 (location "Find an identifier's location.")
1158 (mod-subs "Find all subs defined in a package.")
1159 (mod-decls "Generate declarations for subs in a package.")
1160 (mod-file "Find the file defining a package.")
1161 (apropos "Find subnames matching RE.")
1162 (lexicals "Find lexicals for a sub.")
1163 (apropos-module "Find installed modules matching RE.")
1165 (apply #'define-xref-function
"Sepia" x
))
1167 (dolist (x '((rebuild "Build Xref database for current Perl process.")
1168 (redefined "Rebuild Xref information for a given sub.")
1170 (callers "Find all callers of a function.")
1171 (callees "Find all functions called by a function.")
1173 (var-apropos "Find varnames matching RE.")
1174 (mod-apropos "Find modules matching RE.")
1175 (file-apropos "Find files matching RE.")
1177 (var-defs "Find all definitions of a variable.")
1178 (var-assigns "Find all assignments to a variable.")
1179 (var-uses "Find all uses of a variable.")
1181 (mod-redefined "Rebuild Xref information for a given package.")
1182 (guess-module-file "Guess file corresponding to module.")
1183 (file-modules "List the modules defined in a file.")))
1184 (apply #'define-xref-function
"Sepia::Xref" x
))
1185 ;; Initialize built hash
1186 (sepia-init-perl-builtins)))
1188 (defvar sepia-scratchpad-mode-map
1189 (let ((map (make-sparse-keymap)))
1190 (set-keymap-parent map sepia-mode-map
)
1191 (define-key map
"\C-j" 'sepia-scratch-send-line
)
1195 (define-derived-mode sepia-scratchpad-mode sepia-mode
"Sepia-Scratch"
1196 "Major mode for the Perl scratchpad, derived from Sepia mode."
1200 (defun sepia-scratch ()
1201 "Switch to the sepia scratchpad."
1204 (or (get-buffer "*sepia-scratch*")
1205 (with-current-buffer (get-buffer-create "*sepia-scratch*")
1206 (sepia-scratchpad-mode)
1207 (current-buffer)))))
1209 (defun sepia-scratch-send-line (&optional scalarp
)
1210 "Send the current line to perl, and display the result."
1216 (concat "$Sepia::REPL{eval}->(q#"
1217 (buffer-substring (sepia-bol-from (point))
1218 (sepia-eol-from (point))) "#)"))))))
1220 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1223 (defun sepia-indent-line (&rest args
)
1224 "Unbind `beginning-of-defun-function' to not confuse `cperl-indent-line'."
1225 (let (beginning-of-defun-function)
1226 (apply #'cperl-indent-line args
)))
1228 (defun sepia-string-count-matches (reg str
)
1231 (while (setq pos
(string-match reg str
(1+ pos
)))
1235 (defun sepia-perlize-region-internal (pre post beg end replace-p
)
1236 "Pass buffer text from BEG to END through a Perl command."
1237 (let* ((exp (concat pre
"<<'SEPIA_END_REGION';\n"
1238 (buffer-substring-no-properties beg end
)
1239 (if (= (char-before end
) ?
\n) "" "\n")
1240 "SEPIA_END_REGION\n" post
))
1241 (new-str (car (sepia-eval-raw exp
))))
1243 (progn (delete-region beg end
)
1246 (if (> (sepia-string-count-matches "\n" new-str
) 2)
1247 (with-current-buffer (get-buffer-create "*sepia-filter*")
1248 (let ((inhibit-read-only t
))
1251 (goto-char (point-min))
1252 (pop-to-buffer (current-buffer))))
1253 (message "%s" new-str
)))))
1255 (defun sepia-eol-from (pt &optional n
)
1261 (defun sepia-bol-from (pt &optional n
)
1264 (beginning-of-line n
)
1267 (defun sepia-perl-pe-region (expr beg end
&optional replace-p
)
1268 "Do the equivalent of perl -pe on region
1270 \(i.e. evaluate an expression on each line of region). With
1271 prefix arg, replace the region with the result."
1272 (interactive "MExpression: \nr\nP")
1273 (sepia-perlize-region-internal
1274 "do { my $ret=''; local $_; local $/ = \"\\n\"; my $region = "
1275 (concat "; for (split /(?<=\\n)/, $region, -1) { " expr
1276 "} continue { $ret.=$_}; $ret}")
1277 (sepia-bol-from beg
) (sepia-eol-from end
) replace-p
))
1279 (defun sepia-perl-ne-region (expr beg end
&optional replace-p
)
1280 "Do the moral equivalent of perl -ne on region
1282 \(i.e. evaluate an expression on each line of region). With
1283 prefix arg, replace the region with the result."
1284 (interactive "MExpression: \nr\nP")
1285 (sepia-perlize-region-internal
1286 "do { my $ret='';my $region = "
1287 (concat "; for (split /(?<=\\n)/, $region, -1) { $ret .= do { " expr
1289 (sepia-bol-from beg
) (sepia-eol-from end
) replace-p
))
1291 (defun sepia-perlize-region (expr beg end
&optional replace-p
)
1292 "Evaluate a Perl expression on the region as a whole.
1294 With prefix arg, replace the region with the result."
1295 (interactive "MExpression: \nr\nP")
1296 (sepia-perlize-region-internal
1297 "do { local $_ = " (concat "; do { " expr
";}; $_ }") beg end replace-p
))
1299 (defun sepia-core-version (module &optional message
)
1300 "Report the first version of Perl shipping with MODULE."
1301 (interactive (list (sepia-interactive-arg 'module
) t
))
1304 (format "eval { Sepia::core_version('%s') }" module
)
1307 (format "%s was first released in %s." module version
)
1308 (format "%s is not in core." module
))))
1309 (when message
(message "%s" res
))
1312 (defun sepia-guess-package (sub &optional file
)
1313 "Guess which package SUB is defined in."
1314 (let ((defs (xref-location (xref-apropos sub
))))
1315 (or (and (= (length defs
) 1)
1316 (or (not file
) (equal (caar defs
) file
))
1317 (fourth (car defs
)))
1319 (fourth (find-if (lambda (x) (equal (car x
) file
)) defs
)))
1320 ;; (car (xref-file-modules file))
1321 (sepia-buffer-package))))
1324 (defun sepia-apropos-module (name)
1325 "List installed modules matching a regexp."
1326 (interactive "MList modules matching regexp: ")
1327 (let ((res (xref-apropos-module name
)))
1329 (with-output-to-temp-buffer "*Modules*"
1330 (display-completion-list res
))
1331 (message "No modules matching %s." name
))))
1334 (defun sepia-eval-defun ()
1335 "Re-evaluate the current function and rebuild its Xrefs."
1337 (let (pt end beg sub res
1343 end
(progn (end-of-defun) (point))
1344 beg
(progn (beginning-of-defun) (point)))
1346 (when (looking-at "^sub\\s +\\(.+\\_>\\)")
1347 (setq sub
(match-string 1))
1348 (let ((body (buffer-substring-no-properties beg end
)))
1350 (setq sepia-eval-package
(sepia-guess-package sub
(buffer-file-name))
1351 sepia-eval-file
(buffer-file-name)
1352 sepia-eval-line
(line-number-at-pos beg
)
1355 (if sepia-eval-defun-include-decls
1357 (apply #'concat
(xref-mod-decls sepia-eval-package
))
1362 (when (string-match " line \\([0-9]+\\), near \"\\([^\"]*\\)\""
1365 (beginning-of-line (string-to-number (match-string 1 (cdr res
))))
1366 (search-forward (match-string 2 (cdr res
))
1367 (sepia-eol-from (point)) t
))
1368 (message "Error: %s" (cdr res
)))
1369 (xref-redefined sub sepia-eval-package
)
1370 (message "Defined %s" sub
))))
1373 (defun sepia-eval-expression (expr &optional list-p message-p
)
1374 "Evaluate EXPR in scalar context."
1375 (interactive (list (read-string "Expression: ") current-prefix-arg t
))
1376 (let ((res (sepia-eval expr
(if list-p
'list-context
'scalar-context
))))
1377 (when message-p
(message "%s" res
))
1380 (defun sepia-extract-def (file line obj
)
1381 (with-current-buffer (find-file-noselect (expand-file-name file
))
1383 (funcall (sepia-refiner 'function
) line obj
)
1385 (when (looking-at (concat "^\\s *sub\\_>.*\\_<" obj
"\\_>"))
1386 (buffer-substring (point)
1387 (progn (end-of-defun) (point)))))))
1389 (defun sepia-eval-no-run (string)
1390 (let ((res (sepia-eval-raw
1391 (concat "eval q#{ BEGIN { use B; B::minus_c(); $^C=1; } do { "
1393 " };BEGIN { die \"ok\\n\" }#, $@"))))
1394 (if (string-match "^ok\n" (car res
))
1398 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1401 (defvar sepia-eval-file nil
1402 "File in which `sepia-eval' evaluates perl expressions.")
1403 (defvar sepia-eval-line nil
1404 "Line at which `sepia-eval' evaluates perl expressions.")
1406 (defun sepia-set-cwd (dir)
1407 "Set the inferior Perl process's working directory to DIR.
1409 When called interactively, the current buffer's
1410 `default-directory' is used."
1411 (interactive (list (expand-file-name default-directory
)))
1412 (sepia-call "Cwd::chdir" 'list-context dir
))
1414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1417 (defvar sepia-doc-map
(make-hash-table :test
#'equal
))
1418 (defvar sepia-var-doc-map
(make-hash-table :test
#'equal
))
1419 (defvar sepia-module-doc-map
(make-hash-table :test
#'equal
))
1420 (defvar sepia-skip-doc-scan nil
)
1422 (defun sepia-doc-scan-buffer ()
1423 ;; too many confusing things in perldiag, so just give up.
1424 (when (or sepia-skip-doc-scan
1425 (and (buffer-file-name)
1426 (string-match "perldiag\\.pod$" (buffer-file-name))))
1429 (goto-char (point-min))
1431 while
(re-search-forward
1432 "^=\\(item\\|head[2-9]\\)\\s +\\([%$&@A-Za-z_].*\\)" nil t
)
1435 (let ((short (match-string 2)) longdoc
)
1437 (let ((case-fold-search nil
))
1438 (replace-regexp-in-string
1440 (replace-regexp-in-string
1442 (replace-regexp-in-string
1443 "[A-DF-Z]<\\([^<>]+\\)>" "\\1" short
)))))
1444 (while (string-match "^\\s *[A-Z]<\\(.*\\)>\\s *$" short
)
1445 (setq short
(match-string 1 short
)))
1447 (let ((beg (progn (forward-line 2) (point)))
1448 (end (1- (re-search-forward "^=" nil t
))))
1451 (if (re-search-forward "^\\(.+\\)$" end t
)
1453 (substring-no-properties
1455 0 (position ?.
(match-string 1))))
1458 ;; e.g. "$x -- this is x"
1459 ((string-match "^[%$@]\\([A-Za-z0-9_:]+\\)\\s *--\\s *\\(.*\\)"
1461 (list 'variable
(match-string-no-properties 1 short
)
1462 (or (and (equal short
(match-string 1 short
)) longdoc
)
1464 ;; e.g. "C<foo(BLAH)>" or "$x = $y->foo()"
1465 ((string-match "^\\([A-Za-z0-9_:]+\\)\\s *\\(\\$\\|(\\)" short
)
1466 (list 'function
(match-string-no-properties 1 short
)
1467 (or (and (equal short
(match-string 1 short
)) longdoc
)
1469 ;; e.g. "C<$result = foo $args...>"
1470 ((string-match "^[%@$*][A-Za-z0-9_:]+\\s *=\\s *\\([A-Za-z0-9_:]+\\)" short
)
1471 (list 'function
(match-string-no-properties 1 short
)
1472 (or (and (equal short
(match-string 1 short
)) longdoc
)
1474 ;; e.g. "$x this is x" (note: this has to come last)
1475 ((string-match "^[%$@]\\([^( ]+\\)" short
)
1476 (list 'variable
(match-string-no-properties 1 short
) longdoc
)))))
1479 (defun sepia-buffer-package ()
1481 (or (and (re-search-backward "^\\s *package\\s +\\([^ ;]+\\)\\s *;" nil t
)
1482 (match-string-no-properties 1))
1485 (defun sepia-doc-update ()
1486 "Update documentation for a file.
1488 This documentation, taken from \"=item\" entries in the POD, is
1489 used for eldoc feedback. Set the file variable
1490 `sepia-skip-doc-scan' to non-nil to skip scanning this buffer.
1491 This can be used to avoid generating bogus documentation from
1492 files like perldiag.pod."
1494 (let ((pack (ifa (sepia-buffer-package) (concat it
"::") "")))
1495 (dolist (x (sepia-doc-scan-buffer))
1496 (let ((map (ecase (car x
)
1497 (function sepia-doc-map
)
1498 (variable sepia-var-doc-map
))))
1499 (puthash (second x
) (third x
) map
)
1500 (puthash (concat pack
(second x
)) (third x
) map
)))))
1502 (defun sepia-looks-like-module (obj)
1503 (let (case-fold-search)
1505 (eval-when-compile (regexp-opt '("strict" "vars" "warnings" "lib")))
1508 (string-match "^\\([A-Z][A-Za-z0-9]*::\\)*[A-Z]+[A-Za-z0-9]+\\sw*$" obj
)))))
1510 (defun sepia-describe-object (thing)
1511 "Display documentation for `thing', like ``describe-function'' for elisp."
1513 (let ((id (sepia-ident-at-point)))
1514 (when (string= (cadr id
) "")
1515 (setq id
(sepia-ident-before-point)))
1521 (setq thing
(format "%c%s" (car thing
) (cadr thing
)))
1522 (with-current-buffer (get-buffer-create "*sepia-help*")
1523 (let ((inhibit-read-only t
))
1525 (shell-command (concat "perldoc -v " (shell-quote-argument thing
))
1528 (goto-char (point-min)))
1529 (unless (looking-at "No documentation for")
1530 (pop-to-buffer "*sepia-help*" t
))))
1531 ((gethash thing sepia-perl-builtins
)
1532 (with-current-buffer (get-buffer-create "*sepia-help*")
1533 (let ((inhibit-read-only t
))
1535 (shell-command (concat "perldoc -f " thing
) (current-buffer))
1537 (goto-char (point-min))))
1538 (pop-to-buffer "*sepia-help*" t
))))
1540 (defun sepia-symbol-info (&optional obj type
)
1541 "Eldoc function for `sepia-mode'.
1543 Looks in `sepia-doc-map' and `sepia-var-doc-map', then tries
1544 calling `cperl-describe-perl-symbol'."
1546 (multiple-value-bind (ty ob
) (sepia-ident-at-point)
1547 (setq obj
(if (consp ob
) (car ob
) ob
)
1550 (or (gethash obj
(ecase (or type ?
&)
1552 ((?$ ?
@ ?%
) sepia-var-doc-map
)
1553 (nil sepia-module-doc-map
)
1554 (?
* sepia-module-doc-map
)
1555 (t (error "sepia-symbol-info: %s" type
))))
1556 ;; Loathe cperl a bit.
1557 (flet ((message (&rest blah
) (apply #'format blah
)))
1558 (let* (case-fold-search
1559 (cperl-message-on-help-error nil
)
1560 (hlp (car (save-excursion
1561 (cperl-describe-perl-symbol
1562 (if (member type
'(?$ ?
@ ?%
))
1563 (format "%c%s" type obj
)
1567 ;; cperl's docstrings are too long.
1568 (setq hlp
(replace-regexp-in-string "\\s \\{2,\\}\\|\t" " " hlp
))
1569 (if (> (length hlp
) 75)
1570 (concat (substring hlp
0 72) "...")
1572 ;; Try to see if it's a module
1574 (let ((bol (save-excursion (beginning-of-line)
1576 (looking-back " *\\(?:use\\|require\\|package\\|no\\)\\s +[^ ]*" bol
))
1577 (sepia-looks-like-module obj
))
1578 (sepia-core-version obj
)
1582 (defun sepia-install-eldoc ()
1583 "Install Sepia hooks for eldoc support.
1585 This automatically disables `cperl-lazy-installed', the
1586 `cperl-mode' reimplementation of eldoc."
1589 (set-variable 'eldoc-documentation-function
'sepia-symbol-info t
)
1590 (if cperl-lazy-installed
(cperl-lazy-unstall))
1592 (set-variable 'eldoc-idle-delay
1.0 t
))
1594 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1597 (defun sepia-extract-next-warning (pos &optional end
)
1599 (while (re-search-forward "^\\(.+\\) at \\(.+?\\) line \\([0-9]+\\)"
1601 (unless (string= "(eval " (substring (match-string 2) 0 6))
1602 (throw 'foo
(list (match-string 2)
1603 (string-to-number (match-string 3))
1604 (match-string 1)))))))
1606 (defun sepia-goto-error-at (pos)
1607 "Visit the source of the error on line at point."
1609 (ifa (sepia-extract-next-warning (sepia-bol-from pos
) (sepia-eol-from pos
))
1610 (destructuring-bind (file line msg
) it
1614 (error "No error to find.")))
1616 (defun sepia-display-errors (beg end
)
1617 "Display source causing errors in current buffer from BEG to END."
1621 (loop for w
= (sepia-extract-next-warning (sepia-bol-from (point)) end
)
1623 do
(destructuring-bind (file line msg
) w
1624 (push (format "%s:%d:%s\n" (abbreviate-file-name file
) line msg
)
1627 (goto-char (point-min))
1628 (mapc #'insert
(nreverse msgs
))
1629 (goto-char (point-min))
1632 (defun sepia-lisp-to-perl (thing)
1633 "Convert elisp data structure to Perl."
1635 ((null thing
) "undef")
1637 (let ((pname (substitute ?_ ?-
(symbol-name thing
)))
1638 (type (string-to-char (symbol-name thing
))))
1639 (if (member type
'(?% ?$ ?
@ ?
*))
1641 (concat "\\*" pname
))))
1642 ((stringp thing
) (format "%S" (substring-no-properties thing
0)))
1643 ((integerp thing
) (format "%d" thing
))
1644 ((numberp thing
) (format "%g" thing
))
1646 ((and (consp thing
) (eq (car thing
) 'expr
))
1647 (cdr thing
)) ; XXX -- need quoting??
1648 ((and (consp thing
) (not (consp (cdr thing
))))
1649 (concat (sepia-lisp-to-perl (car thing
)) " => "
1650 (sepia-lisp-to-perl (cdr thing
))))
1652 ((or (not (consp (car thing
)))
1653 (listp (cdar thing
)))
1654 (concat "[" (mapconcat #'sepia-lisp-to-perl thing
", ") "]"))
1657 (concat "{" (mapconcat #'sepia-lisp-to-perl thing
", ") "}"))))
1659 (defun sepia-find-loaded-modules ()
1661 "Visit all source files loaded by the currently-running Perl.
1663 Currently, this means any value of %INC matching /.p[lm]$/."
1664 (dolist (file (sepia-eval "values %INC" 'list-context
))
1665 (when (string-match "\\.p[lm]$" file
)
1666 (find-file-noselect file t
))))
1668 (defun sepia-dired-package (package)
1669 (interactive "sPackage: ")
1670 "Browse files installed by `package'.
1672 Create a `dired-mode' buffer listing all flies installed by `package'."
1673 ;; XXX group by common prefix and use /^ DIRECTORY:$/ format
1674 (let ((ls (sort #'string
<
1675 (sepia-call "Sepia::file_list" 'list-context package
)))
1678 (setq maxlen
(apply #'max
(mapcar #'length ls
)))
1679 (with-current-buffer (get-buffer-create (format "*Package %s*" package
))
1680 (let ((inhibit-read-only t
)
1682 ;; Start with a clean slate
1684 (setq marker
(point-min-marker))
1685 (set (make-local-variable 'dired-subdir-alist
) nil
)
1686 ;; Build up the contents
1688 ;; Find a decent prefix
1689 (setq pfx
(try-completion "" ls
))
1690 (unless (file-exists-p pfx
)
1691 (string-match "^\\(.*/\\)" pfx
)
1692 (setq pfx
(match-string 1 pfx
)))
1693 ;; If we found a lousy prefix, chew off the first few paths and
1694 ;; try again. XXX not done.
1695 (insert (format " %s:\n" pfx
))
1696 (setq default-directory pfx
)
1697 (apply 'call-process
"/bin/ls" nil
(current-buffer) t
1700 (replace-regexp-in-string
1701 (concat pfx
"?") "" x
))
1703 (push `((,default-directory .
,marker
)) dired-subdir-alist
)
1706 (pop-to-buffer (current-buffer))))))
1708 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1709 ;;; Follow POD links from source
1711 (defun sepia-pod-follow-link-at-point (str src
)
1712 "Follow a POD-style link.
1714 If called interactively, follow link at point, or prompt if no
1715 such link exists. With prefix argument, view formatted
1716 documentation with `sepia-perldoc-this'; otherwise, view raw
1717 documentation source."
1719 (or (sepia-pod-link-at-point (point))
1720 (read-string "Link: "))
1721 (not current-prefix-arg
)))
1722 (sepia-pod-follow-link str src
))
1724 (defun sepia-pod-follow-link (str &optional src
)
1725 "Follow link STR to documentation, or to source of documentation if SRC."
1727 (when (string-match "^L<\\(.*\\)>$" str
)
1728 (setq str
(match-string 1 str
)))
1729 ;; strip out text|...
1730 (when (string-match "[^/\"|]+|\\(.*\\)" str
)
1731 (setq str
(match-string 1 str
)))
1733 ;; URL -- no way to "jump to source"
1734 ((string-match "^[a-z]+:.+" str
)
1735 ;; view the URL -- there's no "source"
1739 ((string-match "^\\([^/\"]+\\)/\"?\\([^\"]+\\)\"?$" str
)
1740 ;; open the POD, then go to the section
1741 ;; -- M-. M-d or M-. M-m, plus jump
1742 (let ((page (match-string 1 str
))
1743 (sec (match-string 2 str
)))
1746 (sepia-module-find page
)
1748 (goto-char (point-min))
1749 (unless (search-forward (concat "^=.*" sec
) nil t
)
1750 (error "Can't find anchor for %s." str
))
1751 (setq target
(match-beginning)))
1752 (and target
(goto-char target
)))
1753 (sepia-perldoc-this page
)
1754 (w3m-search-name-anchor sec
))))
1756 ;; /"sec" or /sec or "sec"
1757 ((or (string-match "^/\"?\\([^\"]+\\)\"?$" str
)
1758 (string-match "^\"\\([^\"]+\\)\"$" str
))
1759 ;; jump to POD header in current file or in displayed POD
1760 (let ((sec (match-string 1 str
)))
1764 (goto-char (point-min))
1765 (unless (search-forward (concat "^=.*" sec
) nil t
)
1766 (error "Can't find anchor for %s." str
))
1767 (setq target
(match-beginning)))
1768 (and target
(goto-char target
)))
1770 (w3m-search-name-anchor (match-string 1 str
)))))
1773 ((string-match "^[^/\"]+$" str
)
1775 ;; -- M-. M-d or M-. M-m
1777 (sepia-module-find str
)
1778 (sepia-perldoc-this str
)))
1779 (t (error "Can't understand POD link %s." str
))))
1781 (defun sepia-pod-link-at-point (p)
1782 "Extract POD link at point, or nil."
1783 (let* ((bol (save-excursion (forward-line 0) (point)))
1784 (eol (save-excursion (forward-line 1) (backward-char 1) (point)))
1785 (beg (or (save-excursion
1786 (forward-char 1) ;in case we're on < of L<
1787 (search-backward "L<" bol t
)) p
))
1788 (end (save-excursion (search-forward ">" eol t
))))
1789 (if end
(buffer-substring-no-properties (+ beg
2) (1- end
))
1792 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1793 ;;; Fight CPerl a bit -- it can be opinionated
1795 (defadvice cperl-imenu--create-perl-index
(after simplify compile activate
)
1796 "Make cperl's imenu index simpler."
1797 (flet ((annoying (x)
1798 (dolist (y '("Rescan" "^\\+Unsorted" "^\\+Packages"))
1799 (when (string-match y
(car x
))
1800 (return-from annoying t
)))
1802 (setq ad-return-value
(remove-if #'annoying ad-return-value
))))
1804 ;; (defun sepia-view-mode-hook ()
1805 ;; "Let backspace scroll again.
1807 ;; XXX Unused, yet."
1808 ;; (local-unset-key (kbd "<backspace>")))
1810 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1813 (defun sepia-init-perl-builtins ()
1814 (setq sepia-perl-builtins
(make-hash-table :test
#'equal
))
2017 (puthash s t sepia-perl-builtins
)))
2020 ;;; sepia.el ends here