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-2011 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-cn" 'sepia-perl-ne-region
)
226 (define-key map
"\C-c\C-p" 'sepia-view-pod
) ;was cperl-pod-spell
227 (define-key map
"\C-cp" 'sepia-perl-pe-region
)
228 (define-key map
"\C-c\C-d" 'cperl-perldoc
)
229 ;; (define-key map "\C-c\C-t" 'sepia-repl)
230 (define-key map
"\C-c\C-t" 'cperl-invert-if-unless
)
231 (define-key map
"\C-c\C-r" 'sepia-eval-region
)
232 (define-key map
"\C-c\C-s" 'sepia-scratch
)
233 (define-key map
"\C-c\C-e" 'sepia-eval-expression
)
234 (define-key map
"\C-c!" 'sepia-set-cwd
)
235 (define-key map
(kbd "TAB") 'sepia-indent-or-complete
)
237 "Sepia bindings common to all modes.")
240 (defun sepia-eval-region (beg end
)
241 "Evaluate region using current Sepia process."
243 (sepia-eval (buffer-substring beg end
)))
246 (defun sepia-perldoc-this (name)
247 "View perldoc for module at point."
248 (interactive (list (sepia-interactive-arg 'module
)))
249 (let ((wc (current-window-configuration))
250 (old-pd (symbol-function 'w3m-about-perldoc
))
251 (old-pdb (symbol-function 'w3m-about-perldoc-buffer
))
253 (condition-case stuff
254 (flet ((w3m-about-perldoc (&rest args
)
255 (let ((res (apply old-pd args
)))
256 (or res
(error "lose: %s" args
))))
257 (w3m-about-perldoc-buffer (&rest args
)
258 (let ((res (apply old-pdb args
)))
259 (or res
(error "lose: %s" args
)))))
260 (funcall (if (featurep 'w3m
) 'w3m-perldoc
'cperl-perldoc
) name
)
261 (setq buf
(current-buffer)))
262 (error (set-window-configuration wc
)))
263 (set-window-configuration wc
)
264 (pop-to-buffer buf t
)))
266 (defun sepia-view-pod ()
267 "View POD for the current buffer."
269 (funcall sepia-view-pod-function
))
271 (defun sepia-module-list ()
272 "List installed modules with links to their documentation.
274 This lists not just top-level packages appearing in packlist
275 files, but all documented modules on the system, organized by
278 (let ((file "/tmp/modlist.html"))
279 ;; (unless (file-exists-p file)
280 (sepia-eval-raw (format "Sepia::html_module_list(\"%s\")" file
))
281 (funcall sepia-module-list-function file
)))
283 (defun sepia-package-list ()
284 "List installed packages with links to their documentation.
286 This lists only top-level packages appearing in packlist files.
287 For modules within packages, see `sepia-module-list'."
289 (let ((file "/tmp/packlist.html"))
290 ;; (unless (file-exists-p file)
291 (sepia-eval-raw (format "Sepia::html_package_list(\"%s\")" file
))
292 (funcall sepia-module-list-function file
)))
294 (defun sepia-perldoc-buffer ()
295 "View current buffer's POD using pod2html and `browse-url'.
297 Interactive users should call `sepia-view-pod'."
298 (let ((buffer (get-buffer-create "*sepia-pod*"))
299 (errs (get-buffer-create "*sepia-pod-errors*"))
300 (inhibit-read-only t
))
301 (with-current-buffer buffer
(erase-buffer))
302 (save-window-excursion
303 (shell-command-on-region (point-min) (point-max) "pod2html"
305 (with-current-buffer buffer
(browse-url-of-buffer))))
307 (defun sepia-perl-name (sym &optional mod
)
308 "Convert a Perl name to a Lisp name."
309 (setq sym
(substitute ?_ ?-
(if (symbolp sym
) (symbol-name sym
) sym
)))
311 (concat mod
"::" sym
)
314 (defun sepia-live-p ()
315 (and (processp sepia-process
)
316 (eq (process-status sepia-process
) 'run
)))
318 (defun sepia-ensure-process (&optional remote-host
)
319 (unless (sepia-live-p)
320 (with-current-buffer (get-buffer-create "*sepia-repl*")
322 (set (make-local-variable 'sepia-passive-output
) ""))
324 (comint-exec (get-buffer-create "*sepia-repl*")
325 "attachtty" "attachtty" nil
327 (let ((stuff (split-string sepia-program-name nil t
)))
328 (comint-exec (get-buffer-create "*sepia-repl*")
329 "perl" (car stuff
) nil
332 (mapcar (lambda (x) (concat "-I" x
)) sepia-perl5lib
)
333 '("-MSepia" "-MSepia::Xref"
334 "-e" "Sepia::repl")))))
335 (setq sepia-process
(get-buffer-process "*sepia-repl*"))
336 (accept-process-output sepia-process
1)
337 ;; Steal a bit from gud-common-init:
339 (setq gud-last-last-frame nil
)
340 (set-process-filter sepia-process
'gud-filter
)
341 (set-process-sentinel sepia-process
'gud-sentinel
)))
344 (defun sepia-repl (&optional remote-host
)
345 "Start the Sepia REPL."
346 (interactive (list (and current-prefix-arg
347 (read-string "Host: "))))
348 (sepia-init) ;; set up keymaps, etc.
349 (sepia-ensure-process remote-host
)
350 (pop-to-buffer (get-buffer "*sepia-repl*")))
352 (defun sepia-cont-or-restart ()
354 (if (get-buffer-process (current-buffer))
355 (gud-cont current-prefix-arg
)
358 (defvar sepia-repl-mode-map
359 (let ((map (copy-keymap sepia-shared-map
)))
360 (set-keymap-parent map gud-mode-map
)
361 (define-key map
(kbd "<tab>") 'comint-dynamic-complete
)
362 (define-key map
"\C-a" 'comint-bol
)
363 (define-key map
"\C-c\C-r" 'sepia-cont-or-restart
)
366 "Keymap for Sepia interactive mode.")
368 (define-derived-mode sepia-repl-mode gud-mode
"Sepia REPL"
369 "Major mode for the Sepia REPL.
371 \\{sepia-repl-mode-map}"
372 ;; (set (make-local-variable 'comint-use-prompt-regexp) t)
373 (modify-syntax-entry ?
: "_")
374 (modify-syntax-entry ?
> ".")
375 (set (make-local-variable 'comint-prompt-regexp
) "^[^>\n]*> *")
376 (set (make-local-variable 'gud-target-name
) "sepia")
377 (set (make-local-variable 'gud-marker-filter
) 'sepia-gud-marker-filter
)
378 (set (make-local-variable 'gud-minor-mode
) 'sepia
)
379 (sepia-install-eldoc)
381 (setq gud-comint-buffer
(current-buffer))
382 (setq gud-last-last-frame nil
)
383 (setq gud-sepia-acc nil
)
385 (gud-def gud-break
",break %f:%l" "\C-b" "Set breakpoint at current line.")
386 (gud-def gud-step
",step %p" "\C-s" "Step one line.")
387 (gud-def gud-next
",next %p" "\C-n" "Step one line, skipping calls.")
388 (gud-def gud-cont
",continue" "\C-r" "Continue.")
389 (gud-def gud-print
"%e" "\C-p" "Evaluate something.")
390 (gud-def gud-remove
",delete %l %f" "\C-d" "Delete current breakpoint.")
391 ;; Sadly, this hoses our keybindings.
392 (compilation-shell-minor-mode 1)
393 (set (make-local-variable 'comint-dynamic-complete-functions
)
394 '(sepia-complete-symbol comint-dynamic-complete-filename
))
395 (set (make-local-variable 'comint-preoutput-filter-functions
)
396 '(sepia-watch-for-eval))
397 (run-hooks 'sepia-repl-mode-hook
)
400 (defvar gud-sepia-acc nil
401 "Accumulator for `sepia-gud-marker-filter'.")
403 (defun sepia-gud-marker-filter (str)
406 (concat gud-sepia-acc str
)
408 (while (string-match "_<\\([^:>]+\\):\\([0-9]+\\)>\\(.*\\)" gud-sepia-acc
)
409 (setq gud-last-last-frame gud-last-frame
411 (match-string 1 gud-sepia-acc
)
412 (string-to-number (match-string 2 gud-sepia-acc
)))
413 gud-sepia-acc
(match-string 3 gud-sepia-acc
)))
415 (if (string-match "\\(_<.*\\)" gud-sepia-acc
)
416 (match-string 1 gud-sepia-acc
)
420 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
423 (defun define-xref-function (package name doc
)
424 "Define a lisp mirror for a low-level Sepia function."
425 (let ((lisp-name (intern (format "xref-%s" name
)))
426 (pl-name (sepia-perl-name name package
)))
427 (fmakunbound lisp-name
)
428 (eval `(defun ,lisp-name
(&rest args
)
430 (apply #'sepia-call
,pl-name
'list-context args
)))))
432 (defun define-modinfo-function (name &optional doc context
)
433 "Define a lisp mirror for a function from Module::Info."
434 (let ((name (intern (format "sepia-module-%s" name
)))
435 (pl-func (sepia-perl-name name
))
436 (full-doc (concat (or doc
"") "
438 This function uses Module::Info, so it does not require that the
439 module in question be loaded.")))
440 (when (fboundp name
) (fmakunbound name
))
441 (eval `(defun ,name
(mod)
443 (interactive (list (sepia-interactive-arg 'module
)))
445 (sepia-call "Sepia::module_info" ',(or context
'scalar-context
)
449 (defun sepia-thing-at-point (what)
450 "Like `thing-at-point', but hacked to avoid REPL prompt."
451 (let ((th (thing-at-point what
)))
452 (and th
(not (string-match "[ >]$" th
)) th
)))
454 (defvar sepia-sub-re
"^ *sub\\s +\\(.+\\_>\\)")
456 (defvar sepia-history nil
)
458 (defun sepia-arg-choices (str &rest blah
)
459 (let ((completions (xref-completions
462 (variable "VARIABLE")
466 (when (eq sepia-arg-type
'module
)
468 (remove-if (lambda (x) (string-match "::$" x
)) completions
)))
471 (defun sepia-interactive-arg (&optional sepia-arg-type
)
472 "Default argument for most Sepia functions. TYPE is a symbol --
473 either 'file to look for a file, or anything else to use the
475 (let* ((default (case sepia-arg-type
476 (file (or (thing-at-point 'file
) (buffer-file-name)))
477 (t (sepia-thing-at-point 'symbol
))))
478 (text (capitalize (symbol-name sepia-arg-type
)))
480 (format "%s [%s]: " text default
)
481 (format "%s: " text
)))
482 (ret (if sepia-use-completion
483 (completing-read prompt
'sepia-arg-choices nil nil nil
484 'sepia-history default
)
485 (read-string prompt nil
'sepia-history default
))))
486 (push ret sepia-history
)
489 (defun sepia-interactive-module ()
490 "Guess which module we should look things up in. Prompting for a
491 module all the time is a PITA, but I don't think this (choosing
492 the current file's module) is a good alternative, either. Best
493 would be to choose the module based on what we know about the
495 (let ((xs (xref-file-modules (buffer-file-name))))
496 (if (= (length xs
) 1)
500 (defun sepia-maybe-echo (result &optional print-message
)
502 (message "%s" result
))
505 (defun sepia-find-module-file (mod)
506 (or (sepia-module-file mod
)
507 (car (xref-guess-module-file mod
))))
509 (defun sepia-module-find (mod)
510 "Find the file defining module MOD."
511 (interactive (list (sepia-interactive-arg 'module
)))
512 (let ((fn (sepia-find-module-file mod
)))
515 (message "Module %s in %s." mod fn
)
516 (pop-to-buffer (find-file-noselect (expand-file-name fn
))))
517 (message "Can't find module %s." mod
))))
519 (defmacro ifa
(test then
&rest else
)
521 (if it
,then
,@else
)))
523 (defvar sepia-found-refiner nil
)
525 (defun sepia-show-locations (locs &optional unobtrusive
)
526 (setq locs
(remove nil locs
)) ; XXX where's nil from?
528 (with-current-buffer (get-buffer-create "*sepia-places*")
529 (let ((inhibit-read-only t
))
531 (insert (format "-*- mode: grep; default-directory: %S -*-\n\n"
533 (dolist (loc (sort locs
535 (or (string< (car a
) (car b
))
536 (and (string= (car a
) (car b
))
537 (< (second a
) (second b
)))))))
538 (destructuring-bind (file line name
&rest blah
) loc
539 (let ((str (ifa (find-buffer-visiting file
)
540 (with-current-buffer it
541 (ifa sepia-found-refiner
542 (funcall it line name
)
544 (unless (= (line-number-at-pos) line
)
545 (message "line for %s was %d, now %d" name line
546 (line-number-at-pos)))
547 (setq line
(line-number-at-pos))
549 (buffer-substring (sepia-bol-from)
551 (if (> (length tmpstr
) 60)
552 (concat "\n " tmpstr
)
555 (insert (format "%s:%d:%s\n" (abbreviate-file-name file
) line str
)))))
556 (insert "\nGrep finished (matches found).\n")
559 (save-window-excursion (next-error nil t
))
561 (message "No matches found.")))
563 (defmacro define-sepia-query
(name doc
&optional gen test prompt
)
564 "Define a sepia querying function."
565 `(defun ,name
(ident &optional module file line display-p
)
568 With prefix arg, display matches in a `grep-mode' buffer.
569 Without, go to the first match; calling `sepia-next' will cycle
570 through subsequent matches.
572 Depending on the query, MODULE, FILE, and LINE may be used to
573 narrow the results, as long as doing so leaves some matches.
574 When called interactively, they are taken from the current
577 (interactive (list (sepia-interactive-arg ,(or prompt
''function
))
578 (sepia-interactive-module)
580 (line-number-at-pos (point))
585 `(let ((tmp (,gen ident module file line
)))
586 (or (mapcan #',test tmp
) tmp
))
587 `(,gen ident module file line
))))
588 (sepia-show-locations ret
(not display-p
)))))
590 (define-sepia-query sepia-defs
591 "Find all definitions of sub."
595 (define-sepia-query sepia-callers
596 "Find callers of FUNC."
600 (define-sepia-query sepia-callees
601 "Find a sub's callees."
605 (define-sepia-query sepia-var-defs
606 "Find a var's definitions."
608 (lambda (x) (setf (third x
) ident
) (list x
))
611 (define-sepia-query sepia-var-uses
614 (lambda (x) (setf (third x
) ident
) (list x
))
617 (define-sepia-query sepia-var-assigns
618 "Find/list assignments to a variable."
620 (lambda (x) (setf (third x
) ident
) (list x
))
623 (defalias 'sepia-package-defs
'sepia-module-describe
)
625 (define-sepia-query sepia-apropos
626 "Find/list subroutines matching regexp."
627 (lambda (name &rest blah
) (xref-apropos name
1))
631 (define-sepia-query sepia-var-apropos
632 "Find/list variables matching regexp."
637 (defun sepia-location (name &optional jump-to
)
638 "Find the definition of NAME.
640 When called interactively (or with JUMP-TO true), go directly
642 (interactive (list (sepia-interactive-arg 'function
) t
))
643 (let* ((fl (or (car (xref-location name
))
644 (car (remove-if #'null
645 (apply #'xref-location
(xref-apropos name
)))))))
646 (when (and (car fl
) (string-match "^(eval " (car fl
)))
647 (message "Can't find definition of %s in %s." name
(car fl
))
651 (sepia-set-found (list fl
) 'function
)
653 (message "No definition for %s." name
))
657 (defun sepia-dwim (&optional display-p
)
658 "Try to do the right thing with identifier at point.
659 * Find all definitions, if thing-at-point is a function
660 * Find all uses, if thing-at-point is a variable
661 * Find documentation, if thing-at-point is a module
665 (multiple-value-bind (type obj
) (sepia-ident-at-point)
666 (let* ((module-doc-p nil
)
669 ((member type
'(?% ?$ ?
@)) (xref-var-defs obj
))
671 (let (case-fold-search)
672 (string-match "^[^A-Z]" obj
)))
673 (list (sepia-location obj
)))
674 ((sepia-looks-like-module obj
)
675 (setq module-doc-p t
)
676 `((,(sepia-perldoc-this obj
) 1 nil nil
)))
677 (t (setq module-doc-p t
)
678 (call-interactively 'sepia-defs
)))))
680 (sepia-show-locations ret
(not display-p
))))))
682 (defun sepia-rebuild ()
683 "Rebuild the Xref database."
687 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
688 ;;; Perl motion commands.
690 ;;; XXX -- these are a hack to prevent infinite recursion calling
691 ;;; e.g. beginning-of-defun from beginning-of-defun-function.
692 ;;; `beginning-of-defun' should handle this.
693 (defmacro sepia-safe-bodf
(&optional n
)
694 `(let ((beginning-of-defun-function
695 (if (and (boundp 'beginning-of-defun-function
)
696 (eq beginning-of-defun-function
'sepia-beginning-of-defun
))
698 beginning-of-defun-function
)))
699 (beginning-of-defun ,n
)))
701 (defmacro sepia-safe-eodf
(&optional n
)
702 `(let ((end-of-defun-function
703 (if (and (boundp 'end-of-defun-function
)
704 (eq end-of-defun-function
'sepia-end-of-defun
))
706 end-of-defun-function
)))
709 (defun sepia-beginning-of-defun (&optional n
)
710 "Move to beginning of current function.
712 The prefix argument is the same as for `beginning-of-defun'."
717 (sepia-end-of-defun (- n
))
719 (re-search-backward sepia-sub-re nil nil n
)))
721 (defun sepia-inside-defun ()
722 "True if point is inside a sub."
726 (re-search-backward sepia-sub-re
)
727 (when (< (point) cur
)
734 (defun sepia-end-of-defun (&optional n
)
735 "Move to end of current function.
737 The prefix argument is the same as for `end-of-defun'."
741 (sepia-beginning-of-defun (- n
))
743 ;; If we're outside a defun, skip to the next
745 (unless (sepia-inside-defun)
746 (re-search-forward sepia-sub-re
)
749 (re-search-backward sepia-sub-re
)
755 (defun sepia-rename-lexical (old new
&optional prompt
)
756 "Replace lexical variable OLD with NEW in the current function.
758 With prefix argument, query for each replacement. It is an error
759 to call this outside a function."
761 (let ((old (sepia-thing-at-point 'symbol
)))
762 (list (read-string "Old name: " old nil old
)
763 (read-string "New name: ")
764 current-prefix-arg
)))
765 (message "(%s %s)" old new
)
766 (unless (sepia-inside-defun)
767 (error "Can't rename %s outside a defun." old
))
768 (setq old
(concat "\\([$%@]\\)\\_<" (regexp-quote old
) "\\_>")
771 (let ((bod (sepia-beginning-of-defun))
772 (eod (sepia-end-of-defun)))
774 (query-replace-regexp old new nil bod eod
)
775 ;; (replace-regexp old new nil bod eod)
777 (while (re-search-forward old eod t
)
778 (replace-match new
)))))
780 (defun sepia-defun-around-point (&optional where
)
781 "Return the text of function around point."
783 (setq where
(point)))
786 (and (sepia-beginning-of-defun)
787 (match-string-no-properties 1))))
789 (defun sepia-lexicals-at-point (&optional where
)
790 "Find lexicals in scope at point."
793 (setq where
(point)))
794 (let ((subname (sepia-defun-around-point where
))
795 (mod (sepia-buffer-package)))
796 (xref-lexicals (sepia-perl-name subname mod
))))
799 (defun sepia-load-file (file &optional rebuild-p collect-warnings
)
800 "Reload a file (interactively, the current buffer's file).
802 With REBUILD-P (or a prefix argument when called interactively),
803 also rebuild the xref database."
804 (interactive (list (expand-file-name (buffer-file-name))
806 (format "*%s errors*" (buffer-file-name))))
808 (when collect-warnings
809 (let (kill-buffer-query-functions)
811 (kill-buffer collect-warnings
))))
812 (let* ((tmp (sepia-eval (format "do '%s' || ($@ && do { local $Sepia::Debug::STOPDIE; die $@ })" file
)
816 (message "sepia: %s returned %s" (abbreviate-file-name file
)
817 (if (equal res
"") "undef" res
))
818 (when (and collect-warnings
820 (with-current-buffer (get-buffer-create collect-warnings
)
821 (let ((inhibit-read-only t
))
822 (delete-region (point-min) (point-max))
824 (sepia-display-errors (point-min) (point-max))
825 (pop-to-buffer (current-buffer))))))
831 (defun sepia-set-found (list &optional type
)
833 (remove-if (lambda (x)
835 (and (not (car x
)) (string= (fourth x
) "main"))))
837 (setq sepia-found
(cons -
1 list
))
838 (setq sepia-found-refiner
(sepia-refiner type
)))
840 (defun sepia-refiner (type)
844 (let ((sub-re (concat "^\\s *sub\\s +.*" ident
"\\_>")))
845 ;; Test this because sometimes we get lucky and get the line
846 ;; just right, in which case beginning-of-defun goes to the
852 (looking-at sub-re
)))
853 (progn (goto-char (point-min))
854 (re-search-forward sub-re nil t
)))
855 (beginning-of-line))))
856 ;; Old version -- this may actually work better if
857 ;; beginning-of-defun goes flaky on us.
858 ;; (or (re-search-backward sub-re
859 ;; (sepia-bol-from (point) -20) t)
860 ;; (re-search-forward sub-re
861 ;; (sepia-bol-from (point) 10) t))
862 ;; (beginning-of-line)
865 (let ((var-re (concat "\\_<" ident
"\\_>")))
867 (line (goto-line line
)
868 (or (re-search-backward var-re
(sepia-bol-from nil -
5) t
)
869 (re-search-forward var-re
(sepia-bol-from nil
5) t
)))
870 (t (goto-char (point-min))
871 (re-search-forward var-re nil t
))))))
872 (t (lambda (line ident
) (and line
(goto-line line
))))))
874 (defun sepia-next (&optional arg
)
875 "Go to the next thing (e.g. def, use) found by sepia."
877 (save-window-excursion (next-error arg
)))
879 (defun sepia-previous (&optional arg
)
880 "Go to the previous thing (e.g. def, use) found by sepia."
882 (or arg
(setq arg
1))
883 (sepia-next (- arg
)))
885 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
888 (defun sepia-ident-before-point ()
889 "Find the Perl identifier at or preceding point."
891 (skip-syntax-backward " ")
893 (sepia-ident-at-point)))
895 (defun sepia-simple-method-before-point ()
896 "Find the \"simple\" method call before point.
898 Looks for a simple method called on a variable before point and
899 returns the list (OBJECT METHOD). For example, \"$x->blah\"
900 returns '(\"$x\" \"blah\"). Only simple methods are recognized,
901 because completing anything evaluates it, so completing complex
902 expressions would lead to disaster."
903 (when sepia-complete-methods
905 (bound (max (- (point) 100) (point-min)))
908 ;; XXX - can't do this because COMINT's syntax table is weird.
909 ;; (skip-syntax-backward "_w")
910 (skip-chars-backward "a-zA-Z0-9_")
911 (when (looking-back "->\\s *" bound
)
912 (setq arrow
(search-backward "->" bound
))
913 (skip-chars-backward "a-zA-Z0-9_:")
916 ((char-equal (char-before (point)) ?$
)
917 (setq beg
(1- (point))))
919 ((multiple-value-bind (type obj
) (sepia-ident-at-point)
921 (sepia-looks-like-module obj
)))
924 (list (buffer-substring-no-properties beg arrow
)
925 (buffer-substring-no-properties (+ 2 arrow
) end
)
926 (buffer-substring-no-properties beg end
))))))))
928 (defun sepia-ident-at-point ()
929 "Find the Perl identifier at point."
931 (let ((orig (point)))
932 (when (looking-at "[%$@*&]")
935 (when (re-search-backward "[^A-Za-z_0-9:]" nil
'mu
)
938 (sigil (if (= beg
(point-min))
940 (char-before (point))))
942 (when (re-search-forward "[^A-Za-z_0-9:]" nil
'mu
)
946 ;; try special variables
947 (if (and (member (char-before orig
) '(?$ ?
@ ?%
))
948 (member (car (syntax-after orig
)) '(1 4 5 7 9)))
949 (list (char-before orig
)
950 (buffer-substring-no-properties orig
(1+ orig
)))
953 (list (when (member sigil
'(?$ ?
@ ?% ?
* ?
&)) sigil
)
954 (buffer-substring-no-properties beg end
)))))))
956 (defun sepia-function-at-point ()
957 "Find the Perl function called at point."
962 (sepia-beginning-of-defun)
966 (when (and (>= pt bof
) (< pt
(point)))
967 (sepia-beginning-of-defun)
968 (when (and (= (point) bof
) (looking-at "\\s *sub\\s +"))
969 (forward-char (length (match-string 0)))
970 (concat (or (sepia-buffer-package) "")
972 (cadr (sepia-ident-at-point)))))))
975 (defun sepia-repl-complete ()
976 "Try to complete the word at point in the REPL.
977 Just like `sepia-complete-symbol', except that it also completes
982 (defun sepia-shortcuts ()
983 "Return a list of current Sepia shortcuts."
984 (sepia-eval "sort keys %Sepia::REPL" 'list-context
))
986 (defun sepia-complete-symbol ()
987 "Try to complete the word at point.
988 The word may be either a global or lexical variable if it has a
989 sigil, a module, or a function. The function currently ignores
990 module qualifiers, which may be annoying in larger programs.
992 The function is intended to be bound to \\M-TAB, like
993 `lisp-complete-symbol'."
995 (let ((win (get-buffer-window "*Completions*" 0))
1000 (if (and (eq last-command this-command
)
1001 win
(window-live-p win
) (window-buffer win
)
1002 (buffer-name (window-buffer win
)))
1004 ;; If this command was repeated, and
1005 ;; there's a fresh completion window with a live buffer,
1006 ;; and this command is repeated, scroll that window.
1007 (with-current-buffer (window-buffer win
)
1008 (if (pos-visible-in-window-p (point-max) win
)
1009 (set-window-start win
(point-min))
1010 (save-selected-window
1014 ;; Otherwise actually do completion:
1015 ;; 0 - try a shortcut
1016 (multiple-value-bind (typ name
) (sepia-ident-before-point)
1017 (when (eq major-mode
'sepia-repl-mode
)
1020 (when (looking-at ",\\([a-z]*\\)$")
1021 (let ((str (match-string 1)))
1022 (setq len
(length str
)
1023 completions
(all-completions str
(sepia-shortcuts)))))))
1024 ;; 1 - Look for a method call:
1026 (setq meth
(sepia-simple-method-before-point))
1028 (setq len
(length (caddr meth
))
1032 (lambda (x) (format "%s->%s" (car meth
) x
))
1033 (xref-method-completions
1034 (cons 'expr
(format "'%s'" (car meth
)))
1036 "Sepia::repl_eval")))))
1037 ;; 1.x - look for a module
1040 (and (looking-back " *\\(?:use\\|require\\|package\\|no\\)\\s +[^ ]*" (sepia-bol-from))
1041 (xref-apropos-module
1042 (multiple-value-bind (typ name
)
1043 (sepia-ident-before-point)
1044 (setq len
(length name
))
1049 ;; 2 - look for a regular function/variable/whatever
1051 len
(+ (if type
1 0) (length name
))
1057 (format "%c%s" type x
)))
1067 (and (eq major-mode
'sepia-mode
)
1068 (sepia-function-at-point))))))
1069 ;; 3 - try a Perl built-in
1070 (when (and (not completions
)
1071 (or (not type
) (eq type ?
&)))
1072 (when (string-match ".*::([^:]+)$" name
)
1073 (setq name
(match-string 1 name
)))
1074 (setq completions
(all-completions name sepia-perl-builtins
)))
1075 (case (length completions
)
1076 (0 (message "No completions.") nil
)
1077 (1 ;; XXX - skip sigil to match s-i-before-point
1078 (delete-region (- (point) len
) (point))
1079 (insert (car completions
))
1080 ;; Hide stale completions buffer (stolen from lisp.el).
1081 (if win
(with-selected-window win
(bury-buffer))) t
)
1083 (new (try-completion "" completions
)))
1084 (if (<= (length new
) (+ (length old
) (if type
1 0)))
1085 (with-output-to-temp-buffer "*Completions*"
1086 (display-completion-list completions
))
1087 (let ((win (get-buffer-window "*Completions*" 0)))
1088 (if win
(with-selected-window win
(bury-buffer))))
1089 (delete-region (- (point) len
) (point))
1093 (defun sepia-indent-or-complete ()
1094 "Indent the current line or complete the symbol around point.
1096 Specifically, try completion when indentation doesn't move point.
1097 This function is intended to be bound to TAB."
1099 (let ((pos (point)))
1100 (let (beginning-of-defun-function
1101 end-of-defun-function
)
1102 (cperl-indent-command))
1103 (when (and (= pos
(point))
1105 (or (eq last-command
'sepia-indent-or-complete
)
1106 (looking-at "\\_>")))
1107 (when (or (not sepia-indent-expand-abbrev
)
1108 (and (not (expand-abbrev))
1109 ;; XXX this shouldn't be necessary, but
1110 ;; expand-abbrev returns NIL for e.g. the "else"
1113 (sepia-complete-symbol)))))
1115 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1118 (defvar sepia-mode-map
1119 (let ((map (copy-keymap sepia-shared-map
)))
1120 (set-keymap-parent map cperl-mode-map
)
1121 (define-key map
"\C-c\C-h" nil
)
1123 "Keymap for Sepia mode.")
1126 (define-derived-mode sepia-mode cperl-mode
"Sepia"
1127 "Major mode for Perl editing, derived from cperl mode.
1130 (sepia-install-eldoc)
1132 (set (make-local-variable 'beginning-of-defun-function
)
1133 'sepia-beginning-of-defun
)
1134 (set (make-local-variable 'end-of-defun-function
)
1135 'sepia-end-of-defun
)
1136 (setq indent-line-function
'sepia-indent-line
))
1138 (defun sepia-init ()
1139 "Perform the initialization necessary to start Sepia."
1141 ;; Create glue wrappers for Module::Info funcs.
1142 (unless (fboundp 'xref-completions
)
1143 (dolist (x '((name "Find module name.\n\nDoes not require loading.")
1144 (version "Find module version.\n\nDoes not require loading.")
1145 (inc-dir "Find directory in which this module was found.\n\nDoes not require loading.")
1146 (file "Absolute path of file defining this module.\n\nDoes not require loading.")
1147 (is-core "Guess whether or not a module is part of the core distribution.
1148 Does not require loading.")
1149 (modules-used "List modules used by this module.\n\nRequires loading." list-context
)
1150 (packages-inside "List sub-packages in this module.\n\nRequires loading." list-context
)
1151 (superclasses "List module's superclasses.\n\nRequires loading." list-context
)))
1152 (apply #'define-modinfo-function x
))
1153 ;; Create low-level wrappers for Sepia
1154 (dolist (x '((completions "Find completions in the symbol table.")
1155 (method-completions "Complete on an object's methods.")
1156 (location "Find an identifier's location.")
1157 (mod-subs "Find all subs defined in a package.")
1158 (mod-decls "Generate declarations for subs in a package.")
1159 (mod-file "Find the file defining a package.")
1160 (apropos "Find subnames matching RE.")
1161 (lexicals "Find lexicals for a sub.")
1162 (apropos-module "Find installed modules matching RE.")
1164 (apply #'define-xref-function
"Sepia" x
))
1166 (dolist (x '((rebuild "Build Xref database for current Perl process.")
1167 (redefined "Rebuild Xref information for a given sub.")
1169 (callers "Find all callers of a function.")
1170 (callees "Find all functions called by a function.")
1172 (var-apropos "Find varnames matching RE.")
1173 (mod-apropos "Find modules matching RE.")
1174 (file-apropos "Find files matching RE.")
1176 (var-defs "Find all definitions of a variable.")
1177 (var-assigns "Find all assignments to a variable.")
1178 (var-uses "Find all uses of a variable.")
1180 (mod-redefined "Rebuild Xref information for a given package.")
1181 (guess-module-file "Guess file corresponding to module.")
1182 (file-modules "List the modules defined in a file.")))
1183 (apply #'define-xref-function
"Sepia::Xref" x
))
1184 ;; Initialize built hash
1185 (sepia-init-perl-builtins)))
1187 (defvar sepia-scratchpad-mode-map
1188 (let ((map (make-sparse-keymap)))
1189 (set-keymap-parent map sepia-mode-map
)
1190 (define-key map
"\C-j" 'sepia-scratch-send-line
)
1194 (define-derived-mode sepia-scratchpad-mode sepia-mode
"Sepia-Scratch"
1195 "Major mode for the Perl scratchpad, derived from Sepia mode."
1199 (defun sepia-scratch ()
1200 "Switch to the sepia scratchpad."
1203 (or (get-buffer "*sepia-scratch*")
1204 (with-current-buffer (get-buffer-create "*sepia-scratch*")
1205 (sepia-scratchpad-mode)
1206 (current-buffer)))))
1208 (defun sepia-scratch-send-line (&optional scalarp
)
1209 "Send the current line to perl, and display the result."
1215 (concat "$Sepia::REPL{eval}->(q#"
1216 (buffer-substring (sepia-bol-from)
1217 (sepia-eol-from)) "#)"))))))
1219 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1222 (defun sepia-indent-line (&rest args
)
1223 "Unbind `beginning-of-defun-function' to not confuse `cperl-indent-line'."
1224 (let (beginning-of-defun-function)
1225 (apply #'cperl-indent-line args
)))
1227 (defun sepia-string-count-matches (reg str
)
1230 (while (setq pos
(string-match reg str
(1+ pos
)))
1234 (defun sepia-perlize-region-internal (pre post beg end replace-p
)
1235 "Pass buffer text from BEG to END through a Perl command."
1236 (let* ((exp (concat pre
"<<'SEPIA_END_REGION';\n"
1237 (buffer-substring-no-properties beg end
)
1238 (if (= (char-before end
) ?
\n) "" "\n")
1239 "SEPIA_END_REGION\n" post
))
1240 (new-str (car (sepia-eval-raw exp
))))
1242 (progn (delete-region beg end
)
1245 (if (> (sepia-string-count-matches "\n" new-str
) 2)
1246 (with-current-buffer (get-buffer-create "*sepia-filter*")
1247 (let ((inhibit-read-only t
))
1250 (goto-char (point-min))
1251 (pop-to-buffer (current-buffer))))
1252 (message "%s" new-str
)))))
1254 (defun sepia-eol-from (&optional pt n
)
1256 (line-end-position n
)
1259 (line-end-position n
))))
1261 (defun sepia-bol-from (&optional pt n
)
1263 (line-beginning-position n
)
1266 (line-beginning-position n
))))
1268 (defun sepia-perl-pe-region (expr beg end
&optional replace-p
)
1269 "Do the equivalent of perl -pe on region
1271 \(i.e. evaluate an expression on each line of region). With
1272 prefix arg, replace the region with the result."
1273 (interactive "MExpression: \nr\nP")
1274 (sepia-perlize-region-internal
1275 "do { my $ret=''; local $_; local $/ = \"\\n\"; my $region = "
1276 (concat "; for (split /(?<=\\n)/, $region, -1) { " expr
1277 "} continue { $ret.=$_}; $ret}")
1278 (sepia-bol-from beg
) (sepia-eol-from end
) replace-p
))
1280 (defun sepia-perl-ne-region (expr beg end
&optional replace-p
)
1281 "Do the moral equivalent of perl -ne on region
1283 \(i.e. evaluate an expression on each line of region). With
1284 prefix arg, replace the region with the result."
1285 (interactive "MExpression: \nr\nP")
1286 (sepia-perlize-region-internal
1287 "do { my $ret='';my $region = "
1288 (concat "; for (split /(?<=\\n)/, $region, -1) { $ret .= do { " expr
1290 (sepia-bol-from beg
) (sepia-eol-from end
) replace-p
))
1292 (defun sepia-perlize-region (expr beg end
&optional replace-p
)
1293 "Evaluate a Perl expression on the region as a whole.
1295 With prefix arg, replace the region with the result."
1296 (interactive "MExpression: \nr\nP")
1297 (sepia-perlize-region-internal
1298 "do { local $_ = " (concat "; do { " expr
";}; $_ }") beg end replace-p
))
1300 (defun sepia-core-version (module &optional message
)
1301 "Report the first version of Perl shipping with MODULE."
1302 (interactive (list (sepia-interactive-arg 'module
) t
))
1305 (format "eval { Sepia::core_version('%s') }" module
)
1308 (format "%s was first released in %s." module version
)
1309 (format "%s is not in core." module
))))
1310 (when message
(message "%s" res
))
1313 (defun sepia-guess-package (sub &optional file
)
1314 "Guess which package SUB is defined in."
1315 (let ((defs (xref-location (xref-apropos sub
))))
1316 (or (and (= (length defs
) 1)
1317 (or (not file
) (equal (caar defs
) file
))
1318 (fourth (car defs
)))
1320 (fourth (find-if (lambda (x) (equal (car x
) file
)) defs
)))
1321 ;; (car (xref-file-modules file))
1322 (sepia-buffer-package))))
1325 (defun sepia-apropos-module (name)
1326 "List installed modules matching a regexp."
1327 (interactive "MList modules matching regexp: ")
1328 (let ((res (xref-apropos-module name
)))
1330 (with-output-to-temp-buffer "*Modules*"
1331 (display-completion-list res
))
1332 (message "No modules matching %s." name
))))
1335 (defun sepia-eval-defun ()
1336 "Re-evaluate the current function and rebuild its Xrefs."
1338 (let (pt end beg sub res
1344 end
(progn (end-of-defun) (point))
1345 beg
(progn (beginning-of-defun) (point)))
1347 (when (looking-at "^sub\\s +\\(.+\\_>\\)")
1348 (setq sub
(match-string 1))
1349 (let ((body (buffer-substring-no-properties beg end
)))
1351 (setq sepia-eval-package
(sepia-guess-package sub
(buffer-file-name))
1352 sepia-eval-file
(buffer-file-name)
1353 sepia-eval-line
(line-number-at-pos beg
)
1356 (if sepia-eval-defun-include-decls
1358 (apply #'concat
(xref-mod-decls sepia-eval-package
))
1363 (when (string-match " line \\([0-9]+\\), near \"\\([^\"]*\\)\""
1366 (beginning-of-line (string-to-number (match-string 1 (cdr res
))))
1367 (search-forward (match-string 2 (cdr res
))
1368 (sepia-eol-from) t
))
1369 (message "Error: %s" (cdr res
)))
1370 (xref-redefined sub sepia-eval-package
)
1371 (message "Defined %s" sub
))))
1374 (defun sepia-eval-expression (expr &optional list-p message-p
)
1375 "Evaluate EXPR in scalar context."
1376 (interactive (list (read-string "Expression: ") current-prefix-arg t
))
1377 (let ((res (sepia-eval expr
(if list-p
'list-context
'scalar-context
))))
1378 (when message-p
(message "%s" res
))
1381 (defun sepia-extract-def (file line obj
)
1382 (with-current-buffer (find-file-noselect (expand-file-name file
))
1384 (funcall (sepia-refiner 'function
) line obj
)
1386 (when (looking-at (concat "^\\s *sub\\_>.*\\_<" obj
"\\_>"))
1387 (buffer-substring (point)
1388 (progn (end-of-defun) (point)))))))
1390 (defun sepia-eval-no-run (string)
1391 (let ((res (sepia-eval-raw
1392 (concat "eval q#{ BEGIN { use B; B::minus_c(); $^C=1; } do { "
1394 " };BEGIN { die \"ok\\n\" }#, $@"))))
1395 (if (string-match "^ok\n" (car res
))
1399 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1402 (defvar sepia-eval-file nil
1403 "File in which `sepia-eval' evaluates perl expressions.")
1404 (defvar sepia-eval-line nil
1405 "Line at which `sepia-eval' evaluates perl expressions.")
1407 (defun sepia-set-cwd (dir)
1408 "Set the inferior Perl process's working directory to DIR.
1410 When called interactively, the current buffer's
1411 `default-directory' is used."
1412 (interactive (list (expand-file-name default-directory
)))
1413 (sepia-call "Cwd::chdir" 'list-context dir
))
1415 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1418 (defvar sepia-doc-map
(make-hash-table :test
#'equal
))
1419 (defvar sepia-var-doc-map
(make-hash-table :test
#'equal
))
1420 (defvar sepia-module-doc-map
(make-hash-table :test
#'equal
))
1421 (defvar sepia-skip-doc-scan nil
)
1423 (defun sepia-doc-scan-buffer ()
1424 ;; too many confusing things in perldiag, so just give up.
1425 (when (or sepia-skip-doc-scan
1426 (and (buffer-file-name)
1427 (string-match "perldiag\\.pod$" (buffer-file-name))))
1430 (goto-char (point-min))
1432 while
(re-search-forward
1433 "^=\\(item\\|head[2-9]\\)\\s +\\([%$&@A-Za-z_].*\\)" nil t
)
1436 (let ((short (match-string 2)) longdoc
)
1438 (let ((case-fold-search nil
))
1439 (replace-regexp-in-string
1441 (replace-regexp-in-string
1443 (replace-regexp-in-string
1444 "[A-DF-Z]<\\([^<>]+\\)>" "\\1" short
)))))
1445 (while (string-match "^\\s *[A-Z]<\\(.*\\)>\\s *$" short
)
1446 (setq short
(match-string 1 short
)))
1448 (let ((beg (progn (forward-line 2) (point)))
1449 (end (1- (re-search-forward "^=" nil t
))))
1452 (if (re-search-forward "^\\(.+\\)$" end t
)
1454 (substring-no-properties
1456 0 (position ?.
(match-string 1))))
1459 ;; e.g. "$x -- this is x"
1460 ((string-match "^[%$@]\\([A-Za-z0-9_:]+\\)\\s *--\\s *\\(.*\\)"
1462 (list 'variable
(match-string-no-properties 1 short
)
1463 (or (and (equal short
(match-string 1 short
)) longdoc
)
1465 ;; e.g. "C<foo(BLAH)>" or "$x = $y->foo()"
1466 ((string-match "^\\([A-Za-z0-9_:]+\\)\\s *\\(\\$\\|(\\)" short
)
1467 (list 'function
(match-string-no-properties 1 short
)
1468 (or (and (equal short
(match-string 1 short
)) longdoc
)
1470 ;; e.g. "C<$result = foo $args...>"
1471 ((string-match "^[%@$*][A-Za-z0-9_:]+\\s *=\\s *\\([A-Za-z0-9_:]+\\)" short
)
1472 (list 'function
(match-string-no-properties 1 short
)
1473 (or (and (equal short
(match-string 1 short
)) longdoc
)
1475 ;; e.g. "$x this is x" (note: this has to come last)
1476 ((string-match "^[%$@]\\([^( ]+\\)" short
)
1477 (list 'variable
(match-string-no-properties 1 short
) longdoc
)))))
1480 (defun sepia-buffer-package ()
1482 (or (and (re-search-backward "^\\s *package\\s +\\([^ ;]+\\)\\s *;" nil t
)
1483 (match-string-no-properties 1))
1486 (defun sepia-doc-update ()
1487 "Update documentation for a file.
1489 This documentation, taken from \"=item\" entries in the POD, is
1490 used for eldoc feedback. Set the file variable
1491 `sepia-skip-doc-scan' to non-nil to skip scanning this buffer.
1492 This can be used to avoid generating bogus documentation from
1493 files like perldiag.pod."
1495 (let ((pack (ifa (sepia-buffer-package) (concat it
"::") "")))
1496 (dolist (x (sepia-doc-scan-buffer))
1497 (let ((map (ecase (car x
)
1498 (function sepia-doc-map
)
1499 (variable sepia-var-doc-map
))))
1500 (puthash (second x
) (third x
) map
)
1501 (puthash (concat pack
(second x
)) (third x
) map
)))))
1503 (defun sepia-looks-like-module (obj)
1504 (let (case-fold-search)
1506 (eval-when-compile (regexp-opt '("strict" "vars" "warnings" "lib")))
1509 (string-match "^\\([A-Z][A-Za-z0-9]*::\\)*[A-Z]+[A-Za-z0-9]+\\sw*$" obj
)))))
1511 (defun sepia-describe-object (thing)
1512 "Display documentation for `thing', like ``describe-function'' for elisp."
1514 (let ((id (sepia-ident-at-point)))
1515 (when (string= (cadr id
) "")
1516 (setq id
(sepia-ident-before-point)))
1522 (setq thing
(format "%c%s" (car thing
) (cadr thing
)))
1523 (with-current-buffer (get-buffer-create "*sepia-help*")
1524 (let ((inhibit-read-only t
))
1526 (shell-command (concat "perldoc -v " (shell-quote-argument thing
))
1529 (goto-char (point-min)))
1530 (unless (looking-at "No documentation for")
1531 (pop-to-buffer "*sepia-help*" t
))))
1532 ((gethash thing sepia-perl-builtins
)
1533 (with-current-buffer (get-buffer-create "*sepia-help*")
1534 (let ((inhibit-read-only t
))
1536 (shell-command (concat "perldoc -f " thing
) (current-buffer))
1538 (goto-char (point-min))))
1539 (pop-to-buffer "*sepia-help*" t
))))
1541 (defun sepia-symbol-info (&optional obj type
)
1542 "Eldoc function for `sepia-mode'.
1544 Looks in `sepia-doc-map' and `sepia-var-doc-map', then tries
1545 calling `cperl-describe-perl-symbol'."
1547 (multiple-value-bind (ty ob
) (sepia-ident-at-point)
1548 (setq obj
(if (consp ob
) (car ob
) ob
)
1551 (or (gethash obj
(ecase (or type ?
&)
1553 ((?$ ?
@ ?%
) sepia-var-doc-map
)
1554 (nil sepia-module-doc-map
)
1555 (?
* sepia-module-doc-map
)
1556 (t (error "sepia-symbol-info: %s" type
))))
1557 ;; Loathe cperl a bit.
1558 (flet ((message (&rest blah
) (apply #'format blah
)))
1559 (let* (case-fold-search
1560 (cperl-message-on-help-error nil
)
1561 (hlp (car (save-excursion
1562 (cperl-describe-perl-symbol
1563 (if (member type
'(?$ ?
@ ?%
))
1564 (format "%c%s" type obj
)
1568 ;; cperl's docstrings are too long.
1569 (setq hlp
(replace-regexp-in-string "\\s \\{2,\\}\\|\t" " " hlp
))
1570 (if (> (length hlp
) 75)
1571 (concat (substring hlp
0 72) "...")
1573 ;; Try to see if it's a module
1575 (let ((bol (save-excursion (beginning-of-line)
1577 (looking-back " *\\(?:use\\|require\\|package\\|no\\)\\s +[^ ]*" bol
))
1578 (sepia-looks-like-module obj
))
1579 (sepia-core-version obj
)
1583 (defun sepia-install-eldoc ()
1584 "Install Sepia hooks for eldoc support.
1586 This automatically disables `cperl-lazy-installed', the
1587 `cperl-mode' reimplementation of eldoc."
1590 (set-variable 'eldoc-documentation-function
'sepia-symbol-info t
)
1591 (if cperl-lazy-installed
(cperl-lazy-unstall))
1593 (set-variable 'eldoc-idle-delay
1.0 t
))
1595 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1598 (defun sepia-extract-next-warning (pos &optional end
)
1600 (while (re-search-forward "^\\(.+\\) at \\(.+?\\) line \\([0-9]+\\)"
1602 (unless (string= "(eval " (substring (match-string 2) 0 6))
1603 (throw 'foo
(list (match-string 2)
1604 (string-to-number (match-string 3))
1605 (match-string 1)))))))
1607 (defun sepia-goto-error-at (pos)
1608 "Visit the source of the error on line at point."
1610 (ifa (sepia-extract-next-warning (sepia-bol-from pos
) (sepia-eol-from pos
))
1611 (destructuring-bind (file line msg
) it
1615 (error "No error to find.")))
1617 (defun sepia-display-errors (beg end
)
1618 "Display source causing errors in current buffer from BEG to END."
1622 (loop for w
= (sepia-extract-next-warning (sepia-bol-from) end
)
1624 do
(destructuring-bind (file line msg
) w
1625 (push (format "%s:%d:%s\n" (abbreviate-file-name file
) line msg
)
1628 (goto-char (point-min))
1629 (mapc #'insert
(nreverse msgs
))
1630 (goto-char (point-min))
1633 (defun sepia-lisp-to-perl (thing)
1634 "Convert elisp data structure to Perl."
1636 ((null thing
) "undef")
1638 (let ((pname (substitute ?_ ?-
(symbol-name thing
)))
1639 (type (string-to-char (symbol-name thing
))))
1640 (if (member type
'(?% ?$ ?
@ ?
*))
1642 (concat "\\*" pname
))))
1643 ((stringp thing
) (format "%S" (substring-no-properties thing
0)))
1644 ((integerp thing
) (format "%d" thing
))
1645 ((numberp thing
) (format "%g" thing
))
1647 ((and (consp thing
) (eq (car thing
) 'expr
))
1648 (cdr thing
)) ; XXX -- need quoting??
1649 ((and (consp thing
) (not (consp (cdr thing
))))
1650 (concat (sepia-lisp-to-perl (car thing
)) " => "
1651 (sepia-lisp-to-perl (cdr thing
))))
1653 ((or (not (consp (car thing
)))
1654 (listp (cdar thing
)))
1655 (concat "[" (mapconcat #'sepia-lisp-to-perl thing
", ") "]"))
1658 (concat "{" (mapconcat #'sepia-lisp-to-perl thing
", ") "}"))))
1660 (defun sepia-find-loaded-modules ()
1662 "Visit all source files loaded by the currently-running Perl.
1664 Currently, this means any value of %INC matching /.p[lm]$/."
1665 (dolist (file (sepia-eval "values %INC" 'list-context
))
1666 (when (string-match "\\.p[lm]$" file
)
1667 (find-file-noselect file t
))))
1669 (defun sepia-dired-package (package)
1670 (interactive "sPackage: ")
1671 "Browse files installed by `package'.
1673 Create a `dired-mode' buffer listing all flies installed by `package'."
1674 ;; XXX group by common prefix and use /^ DIRECTORY:$/ format
1675 (let ((ls (sort #'string
<
1676 (sepia-call "Sepia::file_list" 'list-context package
)))
1679 (setq maxlen
(apply #'max
(mapcar #'length ls
)))
1680 (with-current-buffer (get-buffer-create (format "*Package %s*" package
))
1681 (let ((inhibit-read-only t
)
1683 ;; Start with a clean slate
1685 (setq marker
(point-min-marker))
1686 (set (make-local-variable 'dired-subdir-alist
) nil
)
1687 ;; Build up the contents
1689 ;; Find a decent prefix
1690 (setq pfx
(try-completion "" ls
))
1691 (unless (file-exists-p pfx
)
1692 (string-match "^\\(.*/\\)" pfx
)
1693 (setq pfx
(match-string 1 pfx
)))
1694 ;; If we found a lousy prefix, chew off the first few paths and
1695 ;; try again. XXX not done.
1696 (insert (format " %s:\n" pfx
))
1697 (setq default-directory pfx
)
1698 (apply 'call-process
"/bin/ls" nil
(current-buffer) t
1701 (replace-regexp-in-string
1702 (concat pfx
"?") "" x
))
1704 (push `((,default-directory .
,marker
)) dired-subdir-alist
)
1707 (pop-to-buffer (current-buffer))))))
1709 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1710 ;;; Follow POD links from source
1712 (defun sepia-pod-follow-link-at-point (str src
)
1713 "Follow a POD-style link.
1715 If called interactively, follow link at point, or prompt if no
1716 such link exists. With prefix argument, view formatted
1717 documentation with `sepia-perldoc-this'; otherwise, view raw
1718 documentation source."
1720 (or (sepia-pod-link-at-point (point))
1721 (read-string "Link: "))
1722 (not current-prefix-arg
)))
1723 (sepia-pod-follow-link str src
))
1725 (defun sepia-pod-follow-link (str &optional src
)
1726 "Follow link STR to documentation, or to source of documentation if SRC.
1728 For URL links (e.g. L<http://www.emacs.org/>), always follow the
1729 link using `browse-url'."
1731 (when (string-match "^L<\\(.*\\)>$" str
)
1732 (setq str
(match-string 1 str
)))
1733 ;; strip out text|...
1734 (when (string-match "[^/\"|]+|\\(.*\\)" str
)
1735 (setq str
(match-string 1 str
)))
1737 ;; URL -- no way to "jump to source"
1738 ((string-match "^[a-z]+:.+" str
)
1739 ;; view the URL -- there's no "source"
1743 ((string-match "^\\([^/\"]+\\)/\"?\\([^\"]+\\)\"?$" str
)
1744 ;; open the POD, then go to the section
1745 ;; -- `M-. d' or `M-. m', plus jump
1746 (let ((page (match-string 1 str
))
1747 (sec (match-string 2 str
)))
1748 (sepia-perldoc-this page
)
1751 (case-fold-search t
))
1752 (sepia-module-find page
)
1754 (goto-char (point-min))
1755 (if (re-search-forward (concat "^=.*" sec
) nil t
)
1757 (message "Can't find anchor for %s." str
))))
1758 (w3m-search-name-anchor sec
))))
1760 ;; /"sec" or /sec or "sec"
1761 ((or (string-match "^/\"?\\([^\"]+\\)\"?$" str
)
1762 (string-match "^\"\\([^\"]+\\)\"$" str
))
1763 ;; jump to POD header in current file or in displayed POD
1764 (let ((sec (match-string 1 str
)))
1767 (case-fold-search t
))
1769 (goto-char (point-min))
1770 (unless (re-search-forward (concat "^=.*" sec
) nil t
)
1771 (error "Can't find anchor for %s." str
))
1772 (setq target
(match-beginning 0)))
1773 (and target
(goto-char target
)))
1775 (w3m-search-name-anchor (match-string 1 str
)))))
1778 ((string-match "^[^/\"]+$" str
)
1780 ;; -- `M-. d' or `M-. m'
1782 (sepia-module-find str
)
1783 (sepia-perldoc-this str
)))
1784 (t (error "Can't understand POD link %s." str
))))
1786 (defun sepia-pod-link-at-point (p)
1787 "Extract POD link at point, or nil."
1788 (let* ((bol (save-excursion (forward-line 0) (point)))
1789 (eol (line-end-position))
1790 (beg (or (save-excursion
1791 (forward-char 1) ;in case we're on < of L<
1792 (search-backward "L<" bol t
)) p
))
1793 (end (save-excursion (search-forward ">" eol t
))))
1794 (if (and beg end
) (buffer-substring-no-properties (+ beg
2) (1- end
))
1797 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1798 ;;; Fight CPerl a bit -- it can be opinionated
1800 (defadvice cperl-imenu--create-perl-index
(after simplify compile activate
)
1801 "Make cperl's imenu index simpler."
1802 (flet ((annoying (x)
1803 (dolist (y '("Rescan" "^\\+Unsorted" "^\\+Packages"))
1804 (when (string-match y
(car x
))
1805 (return-from annoying t
)))
1807 (setq ad-return-value
(remove-if #'annoying ad-return-value
))))
1809 ;; (defun sepia-view-mode-hook ()
1810 ;; "Let backspace scroll again.
1812 ;; XXX Unused, yet."
1813 ;; (local-unset-key (kbd "<backspace>")))
1815 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1818 (defun sepia-init-perl-builtins ()
1819 (setq sepia-perl-builtins
(make-hash-table :test
#'equal
))
2022 (puthash s t sepia-perl-builtins
)))
2025 ;;; sepia.el ends here