1 ;;; perl-mode.el --- Perl code editing commands for GNU Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1990, 1994, 2001-2016 Free Software Foundation, Inc.
5 ;; Author: William F. Mann
6 ;; Maintainer: emacs-devel@gnu.org
10 ;; Adapted from C code editing commands 'c-mode.el', Copyright 1987 by the
11 ;; Free Software Foundation, under terms of its General Public License.
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation, either version 3 of the License, or
18 ;; (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
30 ;; To enter perl-mode automatically, add (autoload 'perl-mode "perl-mode")
31 ;; to your init file and change the first line of your perl script to:
32 ;; #!/usr/bin/perl -- # -*-Perl-*-
33 ;; With arguments to perl:
34 ;; #!/usr/bin/perl -P- # -*-Perl-*-
35 ;; To handle files included with do 'filename.pl';, add something like
36 ;; (setq auto-mode-alist (append (list (cons "\\.pl\\'" 'perl-mode))
38 ;; to your init file; otherwise the .pl suffix defaults to prolog-mode.
40 ;; This code is based on the 18.53 version c-mode.el, with extensive
41 ;; rewriting. Most of the features of c-mode survived intact.
43 ;; I added a new feature which adds functionality to TAB; it is controlled
44 ;; by the variable perl-tab-to-comment. With it enabled, TAB does the
45 ;; first thing it can from the following list: change the indentation;
46 ;; move past leading white space; delete an empty comment; reindent a
47 ;; comment; move to end of line; create an empty comment; tell you that
48 ;; the line ends in a quoted string, or has a # which should be a \#.
50 ;; If your machine is slow, you may want to remove some of the bindings
51 ;; to perl-electric-terminator. I changed the indenting defaults to be
52 ;; what Larry Wall uses in perl/lib, but left in all the options.
54 ;; I also tuned a few things: comments and labels starting in column
55 ;; zero are left there by perl-indent-exp; perl-beginning-of-function
56 ;; goes back to the first open brace/paren in column zero, the open brace
57 ;; in 'sub ... {', or the equal sign in 'format ... ='; perl-indent-exp
58 ;; (meta-^q) indents from the current line through the close of the next
59 ;; brace/paren, so you don't need to start exactly at a brace or paren.
61 ;; It may be good style to put a set of redundant braces around your
62 ;; main program. This will let you reindent it with meta-^q.
64 ;; Known problems (these are all caused by limitations in the Emacs Lisp
65 ;; parsing routine (parse-partial-sexp), which was not designed for such
66 ;; a rich language; writing a more suitable parser would be a big job):
67 ;; 2) The globbing syntax <pattern> is not recognized, so special
68 ;; characters in the pattern string must be backslashed.
70 ;; Here are some ugly tricks to bypass some of these problems: the perl
71 ;; expression /`/ (that's a back-tick) usually evaluates harmlessly,
72 ;; but will trick perl-mode into starting a quoted string, which
73 ;; can be ended with another /`/. Assuming you have no embedded
74 ;; back-ticks, this can used to help solve problem 3:
76 ;; /`/; $ugly = q?"'$?; /`/;
78 ;; The same trick can be used for problem 6 as in:
79 ;; /{/; while (<${glob_me}>)
80 ;; but a simpler solution is to add a space between the $ and the {:
81 ;; while (<$ {glob_me}>)
83 ;; Problem 7 is even worse, but this 'fix' does work :-(
91 "Major mode for editing Perl code."
92 :link
'(custom-group-link :tag
"Font Lock Faces group" font-lock-faces
)
96 (defvar perl-mode-abbrev-table nil
97 "Abbrev table in use in perl-mode buffers.")
98 (define-abbrev-table 'perl-mode-abbrev-table
())
100 (defvar perl-mode-map
101 (let ((map (make-sparse-keymap)))
102 (define-key map
"\e\C-a" 'perl-beginning-of-function
)
103 (define-key map
"\e\C-e" 'perl-end-of-function
)
104 (define-key map
"\e\C-h" 'perl-mark-function
)
105 (define-key map
"\e\C-q" 'perl-indent-exp
)
106 (define-key map
"\177" 'backward-delete-char-untabify
)
108 "Keymap used in Perl mode.")
110 (defvar perl-mode-syntax-table
111 (let ((st (make-syntax-table (standard-syntax-table))))
112 (modify-syntax-entry ?
\n ">" st
)
113 (modify-syntax-entry ?
# "<" st
)
114 ;; `$' is also a prefix char so I was tempted to say "/ p",
115 ;; but the `p' thingy basically overrides the `/' :-( -- Stef
116 (modify-syntax-entry ?$
"/" st
)
117 (modify-syntax-entry ?%
". p" st
)
118 (modify-syntax-entry ?
@ ". p" st
)
119 (modify-syntax-entry ?
& "." st
)
120 (modify-syntax-entry ?
\' "\"" st
)
121 (modify-syntax-entry ?
* "." st
)
122 (modify-syntax-entry ?
+ "." st
)
123 (modify-syntax-entry ?-
"." st
)
124 (modify-syntax-entry ?
/ "." st
)
125 (modify-syntax-entry ?
< "." st
)
126 (modify-syntax-entry ?
= "." st
)
127 (modify-syntax-entry ?
> "." st
)
128 (modify-syntax-entry ?
\\ "\\" st
)
129 (modify-syntax-entry ?
` "\"" st
)
130 (modify-syntax-entry ?|
"." st
)
132 "Syntax table in use in `perl-mode' buffers.")
134 (defvar perl-imenu-generic-expression
136 (nil "^[ \t]*sub\\s-+\\([-[:alnum:]+_:]+\\)" 1)
138 ("Variables" "^\\(?:my\\|our\\)\\s-+\\([$@%][-[:alnum:]+_:]+\\)\\s-*=" 1)
139 ("Packages" "^[ \t]*package\\s-+\\([-[:alnum:]+_:]+\\);" 1)
140 ("Doc sections" "^=head[0-9][ \t]+\\(.*\\)" 1))
141 "Imenu generic expression for Perl mode. See `imenu-generic-expression'.")
143 ;; Regexps updated with help from Tom Tromey <tromey@cambric.colorado.edu> and
144 ;; Jim Campbell <jec@murzim.ca.boeing.com>.
146 (defconst perl--prettify-symbols-alist
151 (defconst perl-font-lock-keywords-1
152 '(;; What is this for?
153 ;;("\\(--- .* ---\\|=== .* ===\\)" . font-lock-string-face)
155 ;; Fontify preprocessor statements as we do in `c-font-lock-keywords'.
156 ;; Ilya Zakharevich <ilya@math.ohio-state.edu> thinks this is a bad idea.
157 ;; ("^#[ \t]*include[ \t]+\\(<[^>\"\n]+>\\)" 1 font-lock-string-face)
158 ;; ("^#[ \t]*define[ \t]+\\(\\sw+\\)(" 1 font-lock-function-name-face)
160 ;; ("\\<\\(defined\\)\\>[ \t]*(?\\(\\sw+\\)?" nil nil
161 ;; (1 font-lock-constant-face) (2 font-lock-variable-name-face nil t)))
162 ;; ("^#[ \t]*\\(\\sw+\\)\\>[ \t]*\\(\\sw+\\)?"
163 ;; (1 font-lock-constant-face) (2 font-lock-variable-name-face nil t))
165 ;; Fontify function and package names in declarations.
166 ("\\<\\(package\\|sub\\)\\>[ \t]*\\(\\sw+\\)?"
167 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
))
168 ("\\<\\(import\\|no\\|require\\|use\\)\\>[ \t]*\\(\\sw+\\)?"
169 (1 font-lock-keyword-face
) (2 font-lock-constant-face nil t
)))
170 "Subdued level highlighting for Perl mode.")
172 (defconst perl-font-lock-keywords-2
174 perl-font-lock-keywords-1
175 `( ;; Fontify keywords, except those fontified otherwise.
177 (regexp-opt '("if" "until" "while" "elsif" "else" "unless"
178 "do" "dump" "for" "foreach" "exit" "die"
179 "BEGIN" "END" "return" "exec" "eval") t
)
182 ;; Fontify local and my keywords as types.
183 ("\\<\\(local\\|my\\)\\>" . font-lock-type-face
)
185 ;; Fontify function, variable and file name references.
186 ("&\\(\\sw+\\(::\\sw+\\)*\\)" 1 font-lock-function-name-face
)
187 ;; Additionally underline non-scalar variables. Maybe this is a bad idea.
188 ;;'("[$@%*][#{]?\\(\\sw+\\)" 1 font-lock-variable-name-face)
189 ("[$*]{?\\(\\sw+\\(::\\sw+\\)*\\)" 1 font-lock-variable-name-face
)
190 ("\\([@%]\\|\\$#\\)\\(\\sw+\\(::\\sw+\\)*\\)"
191 (2 (cons font-lock-variable-name-face
'(underline))))
192 ("<\\(\\sw+\\)>" 1 font-lock-constant-face
)
194 ;; Fontify keywords with/and labels as we do in `c++-font-lock-keywords'.
195 ("\\<\\(continue\\|goto\\|last\\|next\\|redo\\)\\>[ \t]*\\(\\sw+\\)?"
196 (1 font-lock-keyword-face
) (2 font-lock-constant-face nil t
))
197 ("^[ \t]*\\(\\sw+\\)[ \t]*:[^:]" 1 font-lock-constant-face
)))
198 "Gaudy level highlighting for Perl mode.")
200 (defvar perl-font-lock-keywords perl-font-lock-keywords-1
201 "Default expressions to highlight in Perl mode.")
203 (defvar perl-quote-like-pairs
204 '((?\
( . ?\
)) (?\
[ . ?\
]) (?\
{ . ?\
}) (?\
< . ?\
>)))
207 (defconst perl--syntax-exp-intro-keywords
208 '("split" "if" "unless" "until" "while" "print"
209 "grep" "map" "not" "or" "and" "for" "foreach"))
211 (defconst perl--syntax-exp-intro-regexp
212 (concat "\\(?:\\(?:^\\|[^$@&%[:word:]]\\)"
213 (regexp-opt perl--syntax-exp-intro-keywords
)
214 "\\|[-?:.,;|&+*=!~({[]\\|\\(^\\)\\)[ \t\n]*")))
216 ;; FIXME: handle here-docs and regexps.
217 ;; <<EOF <<"EOF" <<'EOF' (no space)
226 ;; qr /.../ = precompiled regexp =~=~ m/.../
235 (defun perl-syntax-propertize-function (start end
)
236 (let ((case-fold-search nil
))
238 (perl-syntax-propertize-special-constructs end
)
240 (syntax-propertize-rules
241 ;; Turn POD into b-style comments. Place the cut rule first since it's
243 ("^=cut\\>.*\\(\n\\)" (1 "> b"))
244 ("^\\(=\\)\\sw" (1 "< b"))
245 ;; Catch ${ so that ${var} doesn't screw up indentation.
246 ;; This also catches $' to handle 'foo$', although it should really
247 ;; check that it occurs inside a '..' string.
248 ("\\(\\$\\)[{']" (1 (unless (and (eq ?
\' (char-after (match-end 1)))
250 (not (nth 3 (syntax-ppss
251 (match-beginning 0))))))
252 (string-to-syntax ". p"))))
253 ;; Handle funny names like $DB'stop.
254 ("\\$ ?{?^?[_[:alpha:]][_[:alnum:]]*\\('\\)[_[:alpha:]]" (1 "_"))
256 ("^[ \t]*format.*=[ \t]*\\(\n\\)"
257 (1 (prog1 "\"" (perl-syntax-propertize-special-constructs end
))))
258 ;; Funny things in `sub' arg-specs like `sub myfun ($)' or `sub ($)'.
259 ;; Be careful not to match "sub { (...) ... }".
260 ("\\<sub\\(?:[\s\t\n]+\\(?:\\sw\\|\\s_\\)+\\)?[\s\t\n]*(\\([^)]+\\))"
262 ;; Turn __DATA__ trailer into a comment.
263 ("^\\(_\\)_\\(?:DATA\\|END\\)__[ \t]*\\(?:\\(\n\\)#.-\\*-.*perl.*-\\*-\\|\n.*\\)"
265 (0 (ignore (put-text-property (match-beginning 0) (match-end 0)
266 'syntax-multiline t
))))
267 ;; Regexp and funny quotes. Distinguishing a / that starts a regexp
268 ;; match from the division operator is ...interesting.
269 ;; Basically, / is a regexp match if it's preceded by an infix operator
270 ;; (or some similar separator), or by one of the special keywords
271 ;; corresponding to builtin functions that can take their first arg
272 ;; without parentheses. Of course, that presume we're looking at the
273 ;; *opening* slash. We can afford to mis-match the closing ones
274 ;; here, because they will be re-treated separately later in
275 ;; perl-font-lock-special-syntactic-constructs.
276 ((concat perl--syntax-exp-intro-regexp
"\\(/\\)")
278 (if (and (match-end 1) ; / at BOL.
280 (goto-char (match-end 1))
281 (forward-comment (- (point-max)))
282 (put-text-property (point) (match-end 2)
284 (not (or (and (eq ?w
(char-syntax (preceding-char)))
287 (member (buffer-substring (point) end
)
288 perl--syntax-exp-intro-keywords
)))
290 '(?? ?
: ?. ?
, ?\
; ?= ?! ?~ ?\( ?\[))))))
291 nil
;; A division sign instead of a regexp-match.
292 (put-text-property (match-beginning 2) (match-end 2)
293 'syntax-table
(string-to-syntax "\""))
294 (perl-syntax-propertize-special-constructs end
)))))
295 ("\\(^\\|[?:.,;=!~({[ \t]\\)\\([msy]\\|q[qxrw]?\\|tr\\)\\>\\s-*\\(?:\\([^])}>= \n\t]\\)\\|\\(?3:=\\)[^>]\\)"
297 ;; /foo/m $a->m $#m $m @m %m
298 ;; \s (appears often in regexps).
303 (if (save-excursion (goto-char (match-beginning 0))
304 (forward-word-strictly -
1)
305 (looking-at-p "sub[ \t\n]"))
306 ;; This is defining a function.
308 (unless (nth 8 (save-excursion (syntax-ppss (match-beginning 1))))
309 ;; Don't add this syntax-table property if
310 ;; within a string, which would misbehave in cases such as
311 ;; $a = "foo y \"toto\" bar" where we'd end up changing the
312 ;; syntax of the backslash and hence de-escaping the embedded
314 (put-text-property (match-beginning 3) (match-end 3)
316 (if (assoc (char-after (match-beginning 3))
317 perl-quote-like-pairs
)
318 (string-to-syntax "|")
319 (string-to-syntax "\"")))
320 (perl-syntax-propertize-special-constructs end
))))))
324 ;; << "EOF", << 'EOF', or << \EOF
325 "<<[ \t]*\\('[^'\n]*'\\|\"[^\"\n]*\"\\|\\\\[[:alpha:]][[:alnum:]]*\\)"
326 ;; The <<EOF case which needs perl--syntax-exp-intro-regexp, to
327 ;; disambiguate with the left-bitshift operator.
328 "\\|" perl--syntax-exp-intro-regexp
"<<\\(?1:\\sw+\\)\\)"
330 (3 (let* ((st (get-text-property (match-beginning 3) 'syntax-table
))
331 (name (match-string 1)))
332 (goto-char (match-end 1))
333 (if (save-excursion (nth 8 (syntax-ppss (match-beginning 0))))
334 ;; Leave the property of the newline unchanged.
336 (cons (car (string-to-syntax "< c"))
337 ;; Remember the names of heredocs found on this line.
338 (cons (pcase (aref name
0)
339 (`?
\\ (substring name
1))
340 ((or `?
\" `?
\' `?\
`) (substring name
1 -
1))
343 ;; We don't call perl-syntax-propertize-special-constructs directly
344 ;; from the << rule, because there might be other elements (between
345 ;; the << and the \n) that need to be propertized.
347 (0 (ignore (perl-syntax-propertize-special-constructs end
))))
351 (defvar perl-empty-syntax-table
352 (let ((st (copy-syntax-table)))
353 ;; Make all chars be of punctuation syntax.
354 (dotimes (i 256) (aset st i
'(1)))
355 (modify-syntax-entry ?
\\ "\\" st
)
357 "Syntax table used internally for processing quote-like operators.")
359 (defun perl-quote-syntax-table (char)
360 (let ((close (cdr (assq char perl-quote-like-pairs
)))
361 (st (copy-syntax-table perl-empty-syntax-table
)))
363 (modify-syntax-entry char
"\"" st
)
364 (modify-syntax-entry char
"(" st
)
365 (modify-syntax-entry close
")" st
))
368 (defun perl-syntax-propertize-special-constructs (limit)
369 "Propertize special constructs like regexps and formats."
370 (let ((state (syntax-ppss))
373 ((eq 2 (nth 7 state
))
375 (let ((names (cdr (get-text-property (nth 8 state
) 'syntax-table
))))
377 (setq names
(reverse names
))
378 ;; Multiple heredocs on a single line, we have to search from the
379 ;; beginning, since we don't know which names might be
381 (goto-char (nth 8 state
)))
384 (concat "^" (regexp-quote (pop names
)) "\n")
387 (put-text-property (1- (point)) (point) 'syntax-table
388 (string-to-syntax "> c"))))))
389 ((or (null (setq char
(nth 3 state
)))
390 (and (characterp char
) (eq (char-syntax (nth 3 state
)) ?
\")))
391 ;; Normal text, or comment, or docstring, or normal string.
393 ((eq (nth 3 state
) ?
\n)
394 ;; A `format' command.
395 (when (re-search-forward "^\\s *\\.\\s *\n" limit
'move
)
396 (put-text-property (1- (point)) (point)
397 'syntax-table
(string-to-syntax "\""))))
399 ;; This is regexp like quote thingy.
400 (setq char
(char-after (nth 8 state
)))
401 (let ((startpos (point))
402 (twoargs (save-excursion
403 (goto-char (nth 8 state
))
404 (skip-syntax-backward " ")
405 (skip-syntax-backward "w")
406 (member (buffer-substring
407 (point) (progn (forward-word-strictly 1)
410 (close (cdr (assq char perl-quote-like-pairs
)))
411 (st (perl-quote-syntax-table char
)))
412 (when (with-syntax-table st
414 ;; For paired delimiters, Perl allows nesting them, but
415 ;; since we treat them as strings, Emacs does not count
416 ;; those delimiters in `state', so we don't know how deep
417 ;; we are: we have to go back to the beginning of this
418 ;; "string" and count from there.
421 ;; Start after the first char since it doesn't have
422 ;; paren-syntax (an alternative would be to let-bind
423 ;; parse-sexp-lookup-properties).
424 (goto-char (1+ (nth 8 state
)))
427 ;; In case of error, make sure we don't move backward.
428 (scan-error (goto-char startpos
) nil
))
429 (not (or (nth 8 (parse-partial-sexp
430 ;; Since we don't know if point is within
431 ;; the first or the scond arg, we have to
432 ;; start from the beginning.
433 (if twoargs
(1+ (nth 8 state
)) (point))
434 limit nil nil state
'syntax-table
))
435 ;; If we have a self-paired opener and a twoargs
436 ;; command, the form is s/../../ so we have to skip
438 ;; In the case of s{...}{...}, we only handle the
439 ;; first part here and the next below.
440 (when (and twoargs
(not close
))
441 (nth 8 (parse-partial-sexp
443 nil nil state
'syntax-table
)))))))
444 ;; Point is now right after the arg(s).
445 (when (eq (char-before (1- (point))) ?$
)
446 (put-text-property (- (point) 2) (1- (point))
448 (put-text-property (1- (point)) (point)
451 (string-to-syntax "|")
452 (string-to-syntax "\"")))
453 ;; If we have two args with a non-self-paired starter (e.g.
454 ;; s{...}{...}) we're right after the first arg, so we still have to
455 ;; handle the second part.
456 (when (and twoargs close
)
457 ;; Skip whitespace and make sure that font-lock will
458 ;; refontify the second part in the proper context.
460 (point) (progn (forward-comment (point-max)) (point))
463 (when (< (point) limit
)
464 (put-text-property (point) (1+ (point))
466 (if (assoc (char-after)
467 perl-quote-like-pairs
)
468 ;; Put an `e' in the cdr to mark this
469 ;; char as "second arg starter".
470 (string-to-syntax "|e")
471 (string-to-syntax "\"e")))
473 ;; Re-use perl-syntax-propertize-special-constructs to handle the
474 ;; second part (the first delimiter of second part can't be
475 ;; preceded by "s" or "tr" or "y", so it will not be considered
477 (perl-syntax-propertize-special-constructs limit
)))))))))
479 (defun perl-font-lock-syntactic-face-function (state)
482 (eq ?e
(cdr-safe (get-text-property (nth 8 state
) 'syntax-table
)))
483 ;; This is a second-arg of s{..}{...} form; let's check if this second
484 ;; arg is executable code rather than a string. For that, we need to
485 ;; look for an "e" after this second arg, so we have to hunt for the
486 ;; end of the arg. Depending on whether the whole arg has already
487 ;; been syntax-propertized or not, the end-char will have different
488 ;; syntaxes, so let's ignore syntax-properties temporarily so we can
489 ;; pretend it has not been syntax-propertized yet.
490 (let* ((parse-sexp-lookup-properties nil
)
491 (char (char-after (nth 8 state
)))
492 (paired (assq char perl-quote-like-pairs
)))
493 (with-syntax-table (perl-quote-syntax-table char
)
496 (parse-partial-sexp (point) (point-max)
497 nil nil state
'syntax-table
)
500 (goto-char (1+ (nth 8 state
)))
502 (scan-error (goto-char (point-max)))))
503 (put-text-property (nth 8 state
) (point)
504 'jit-lock-defer-multiline t
)
505 (looking-at "[ \t]*\\sw*e")))))
507 (t (funcall (default-value 'font-lock-syntactic-face-function
) state
))))
509 (defcustom perl-indent-level
4
510 "Indentation of Perl statements with respect to containing block."
513 ;; Is is not unusual to put both things like perl-indent-level and
514 ;; cperl-indent-level in the local variable section of a file. If only
515 ;; one of perl-mode and cperl-mode is in use, a warning will be issued
516 ;; about the variable. Autoload these here, so that no warning is
517 ;; issued when using either perl-mode or cperl-mode.
518 ;;;###autoload(put 'perl-indent-level 'safe-local-variable 'integerp)
519 ;;;###autoload(put 'perl-continued-statement-offset 'safe-local-variable 'integerp)
520 ;;;###autoload(put 'perl-continued-brace-offset 'safe-local-variable 'integerp)
521 ;;;###autoload(put 'perl-brace-offset 'safe-local-variable 'integerp)
522 ;;;###autoload(put 'perl-brace-imaginary-offset 'safe-local-variable 'integerp)
523 ;;;###autoload(put 'perl-label-offset 'safe-local-variable 'integerp)
525 (defcustom perl-continued-statement-offset
4
526 "Extra indent for lines not starting new statements."
528 (defcustom perl-continued-brace-offset -
4
529 "Extra indent for substatements that start with open-braces.
530 This is in addition to `perl-continued-statement-offset'."
532 (defcustom perl-brace-offset
0
533 "Extra indentation for braces, compared with other text in same context."
535 (defcustom perl-brace-imaginary-offset
0
536 "Imagined indentation of an open brace that actually follows a statement."
538 (defcustom perl-label-offset -
2
539 "Offset of Perl label lines relative to usual indentation."
541 (defcustom perl-indent-continued-arguments nil
542 "If non-nil offset of argument lines relative to usual indentation.
543 If nil, continued arguments are aligned with the first argument."
544 :type
'(choice integer
(const nil
)))
546 (defcustom perl-indent-parens-as-block nil
547 "Non-nil means that non-block ()-, {}- and []-groups are indented as blocks.
548 The closing bracket is aligned with the line of the opening bracket,
549 not the contents of the brackets."
553 (defcustom perl-tab-always-indent tab-always-indent
554 "Non-nil means TAB in Perl mode always indents the current line.
555 Otherwise it inserts a tab character if you type it past the first
556 nonwhite character on the line."
559 ;; I changed the default to nil for consistency with general Emacs
560 ;; conventions -- rms.
561 (defcustom perl-tab-to-comment nil
562 "Non-nil means TAB moves to eol or makes a comment in some cases.
563 For lines which don't need indenting, TAB either indents an
564 existing comment, moves to end-of-line, or if at end-of-line already,
565 create a new comment."
568 (defcustom perl-nochange
"\f"
569 "Lines starting with this regular expression are not auto-indented."
571 :options
'(";?#\\|\f\\|\\s(\\|\\(\\w\\|\\s_\\)+:[^:]"))
575 (defvar perl-outline-regexp
576 (concat (mapconcat 'cadr perl-imenu-generic-expression
"\\|")
579 (defun perl-outline-level ()
581 ((looking-at "[ \t]*\\(package\\)\\s-")
582 (- (match-beginning 1) (match-beginning 0)))
583 ((looking-at "[ \t]*s\\(ub\\)\\s-")
584 (- (match-beginning 1) (match-beginning 0)))
585 ((looking-at "=head[0-9]") (- (char-before (match-end 0)) ?
0))
586 ((looking-at "=cut") 1)
589 (defun perl-current-defun-name ()
590 "The `add-log-current-defun' function in Perl mode."
592 (if (re-search-backward "^sub[ \t]+\\([^({ \t\n]+\\)" nil t
)
593 (match-string-no-properties 1))))
596 (defvar perl-mode-hook nil
597 "Normal hook to run when entering Perl mode.")
600 (define-derived-mode perl-mode prog-mode
"Perl"
601 "Major mode for editing Perl code.
602 Expression and list commands understand all Perl brackets.
603 Tab indents for Perl code.
604 Comments are delimited with # ... \\n.
605 Paragraphs are separated by blank lines only.
606 Delete converts tabs to spaces as it moves back.
608 Variables controlling indentation style:
609 `perl-tab-always-indent'
610 Non-nil means TAB in Perl mode should always indent the current line,
611 regardless of where in the line point is when the TAB command is used.
612 `perl-tab-to-comment'
613 Non-nil means that for lines which don't need indenting, TAB will
614 either delete an empty comment, indent an existing comment, move
615 to end-of-line, or if at end-of-line already, create a new comment.
617 Lines starting with this regular expression are not auto-indented.
619 Indentation of Perl statements within surrounding block.
620 The surrounding block's indentation is the indentation
621 of the line on which the open-brace appears.
622 `perl-continued-statement-offset'
623 Extra indentation given to a substatement, such as the
624 then-clause of an if or body of a while.
625 `perl-continued-brace-offset'
626 Extra indentation given to a brace that starts a substatement.
627 This is in addition to `perl-continued-statement-offset'.
629 Extra indentation for line if it starts with an open brace.
630 `perl-brace-imaginary-offset'
631 An open brace following other text is treated as if it were
632 this far to the right of the start of its line.
634 Extra indentation for line that is a label.
635 `perl-indent-continued-arguments'
636 Offset of argument lines relative to usual indentation.
638 Various indentation styles: K&R BSD BLK GNU LW
639 perl-indent-level 5 8 0 2 4
640 perl-continued-statement-offset 5 8 4 2 4
641 perl-continued-brace-offset 0 0 0 0 -4
642 perl-brace-offset -5 -8 0 0 0
643 perl-brace-imaginary-offset 0 0 4 0 0
644 perl-label-offset -5 -8 -2 -2 -2
646 Turning on Perl mode runs the normal hook `perl-mode-hook'."
647 :abbrev-table perl-mode-abbrev-table
648 (setq-local paragraph-start
(concat "$\\|" page-delimiter
))
649 (setq-local paragraph-separate paragraph-start
)
650 (setq-local paragraph-ignore-fill-prefix t
)
651 (setq-local indent-line-function
#'perl-indent-line
)
652 (setq-local comment-start
"# ")
653 (setq-local comment-end
"")
654 (setq-local comment-start-skip
"\\(^\\|\\s-\\);?#+ *")
655 (setq-local comment-indent-function
#'perl-comment-indent
)
656 (setq-local parse-sexp-ignore-comments t
)
658 ;; Tell font-lock.el how to handle Perl.
659 (setq font-lock-defaults
'((perl-font-lock-keywords
660 perl-font-lock-keywords-1
661 perl-font-lock-keywords-2
)
662 nil nil
((?\_ .
"w")) nil
663 (font-lock-syntactic-face-function
664 . perl-font-lock-syntactic-face-function
)))
665 (setq-local prettify-symbols-alist perl--prettify-symbols-alist
)
666 (setq-local syntax-propertize-function
#'perl-syntax-propertize-function
)
667 (add-hook 'syntax-propertize-extend-region-functions
668 #'syntax-propertize-multiline
'append
'local
)
670 ;; FIXME: setup electric-layout-rules.
671 (setq-local electric-indent-chars
672 (append '(?\
{ ?\
} ?\
; ?\:) electric-indent-chars))
673 (add-hook 'electric-indent-functions
#'perl-electric-noindent-p nil t
)
674 ;; Tell imenu how to handle Perl.
675 (setq-local imenu-generic-expression perl-imenu-generic-expression
)
676 (setq imenu-case-fold-search nil
)
677 ;; Setup outline-minor-mode.
678 (setq-local outline-regexp perl-outline-regexp
)
679 (setq-local outline-level
'perl-outline-level
)
680 (setq-local add-log-current-defun-function
#'perl-current-defun-name
))
682 ;; This is used by indent-for-comment
683 ;; to decide how much to indent a comment in Perl code
684 ;; based on its context.
685 (defun perl-comment-indent ()
686 (if (and (bolp) (not (eolp)))
687 0 ;Existing comment at bol stays there.
690 (define-obsolete-function-alias 'electric-perl-terminator
691 'perl-electric-terminator
"22.1")
692 (defun perl-electric-noindent-p (_char)
693 (unless (eolp) 'no-indent
))
695 (defun perl-electric-terminator (arg)
696 "Insert character and maybe adjust indentation.
697 If at end-of-line, and not in a comment or a quote, correct the indentation."
699 (let ((insertpos (point)))
700 (and (not arg
) ; decide whether to indent
704 (and (not ; eliminate comments quickly
705 (and comment-start-skip
706 (re-search-forward comment-start-skip insertpos t
)) )
707 (or (/= last-command-event ?
:)
708 ;; Colon is special only after a label ....
709 (looking-at "\\s-*\\(\\w\\|\\s_\\)+$"))
710 (let ((pps (parse-partial-sexp
711 (perl-beginning-of-function) insertpos
)))
712 (not (or (nth 3 pps
) (nth 4 pps
) (nth 5 pps
))))))
713 (progn ; must insert, indent, delete
714 (insert-char last-command-event
1)
717 (self-insert-command (prefix-numeric-value arg
)))
718 (make-obsolete 'perl-electric-terminator
'electric-indent-mode
"24.4")
720 ;; not used anymore, but may be useful someday:
721 ;;(defun perl-inside-parens-p ()
722 ;; (condition-case ()
725 ;; (narrow-to-region (point)
726 ;; (perl-beginning-of-function))
727 ;; (goto-char (point-max))
728 ;; (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
731 (defun perl-indent-command (&optional arg
)
732 "Indent Perl code in the active region or current line.
733 In Transient Mark mode, when the region is active, reindent the region.
734 Otherwise, with a prefix argument, reindent the current line
737 Otherwise, if `perl-tab-always-indent' is nil and point is not in
738 the indentation area at the beginning of the line, insert a tab.
740 Otherwise, indent the current line. If point was within the
741 indentation area, it is moved to the end of the indentation area.
742 If the line was already indented properly and point was not
743 within the indentation area, and if `perl-tab-to-comment' is
744 non-nil (the default), then do the first possible action from the
747 1) delete an empty comment
748 2) move forward to start of comment, indenting if necessary
749 3) move forward to end of line
750 4) create an empty comment
751 5) move backward to start of comment, indenting if necessary."
753 (cond ((use-region-p) ; indent the active region
754 (indent-region (region-beginning) (region-end)))
756 (perl-indent-line "\f")) ; just indent this line
757 ((and (not perl-tab-always-indent
)
758 (> (current-column) (current-indentation)))
761 (let* ((oldpnt (point))
762 (lsexp (progn (beginning-of-line) (point)))
763 (bof (perl-beginning-of-function))
766 (perl-indent-line "\f\\|;?#"))))
767 (and perl-tab-to-comment
768 (= oldpnt
(point)) ; done if point moved
769 (if (listp delta
) ; if line starts in a quoted string
770 (setq lsexp
(or (nth 2 delta
) bof
))
771 (= delta
0)) ; done if indenting occurred
772 (let ((eol (progn (end-of-line) (point)))
774 (cond ((= (char-after bof
) ?
=)
776 (message "In a format statement")))
777 ((progn (setq state
(parse-partial-sexp lsexp eol
))
779 (if (= oldpnt eol
) ; already at eol in a string
780 (message "In a string which starts with a %c."
783 (if (= oldpnt eol
) ; no comment, create one?
784 (indent-for-comment)))
785 ((progn (beginning-of-line)
786 (and comment-start-skip
788 comment-start-skip eol
'move
)))
790 (progn ; delete existing comment
791 (goto-char (match-beginning 0))
792 (skip-chars-backward " \t")
793 (delete-region (point) eol
))
794 (if (or (< oldpnt
(point)) (= oldpnt eol
))
795 (indent-for-comment) ; indent existing comment
800 (message "Use backslash to quote # characters.")
802 (make-obsolete 'perl-indent-command
'indent-according-to-mode
"24.4")
804 (defun perl-indent-line (&optional nochange
)
805 "Indent current line as Perl code.
806 Return the amount the indentation
807 changed by, or (parse-state) if line starts in a quoted string."
808 (let ((case-fold-search nil
)
809 (pos (- (point-max) (point)))
810 beg indent shift-amt
)
814 (cond ((eq 1 (nth 7 (syntax-ppss))) 0) ;For doc sections!
815 ((listp (setq indent
(perl-calculate-indent))) indent
)
816 ((eq 'noindent indent
) indent
)
817 ((looking-at (or nochange perl-nochange
)) 0)
819 (skip-chars-forward " \t\f")
820 (setq indent
(perl-indent-new-calculate nil indent
))
821 (- indent
(current-column)))))
822 (skip-chars-forward " \t\f")
823 (if (and (numberp shift-amt
) (/= 0 shift-amt
))
824 (progn (delete-region beg
(point))
826 ;; If initial point was within line's indentation,
827 ;; position after the indentation. Else stay at same point in text.
828 (if (> (- (point-max) pos
) (point))
829 (goto-char (- (point-max) pos
)))
832 (defun perl-continuation-line-p ()
833 "Move to end of previous line and return non-nil if continued."
834 ;; Statement level. Is it a continuation or a new statement?
835 ;; Find previous non-comment character.
836 (perl-backward-to-noncomment)
837 ;; Back up over label lines, since they don't
838 ;; affect whether our line is a continuation.
839 (while (and (eq (preceding-char) ?
:)
840 (memq (char-syntax (char-after (- (point) 2)))
843 (perl-backward-to-noncomment))
844 ;; Now we get the answer.
845 (unless (memq (preceding-char) '(?\
; ?\} ?\{))
848 (defun perl-hanging-paren-p ()
849 "Non-nil if we are right after a hanging parenthesis-like char."
850 (and (looking-at "[ \t]*$")
852 (skip-syntax-backward " (") (not (bolp)))))
854 (defun perl-indent-new-calculate (&optional virtual default
)
856 (and virtual
(save-excursion (skip-chars-backward " \t") (bolp))
858 (and (looking-at "\\(\\w\\|\\s_\\)+:[^:]")
859 (max 1 (+ (or default
(perl-calculate-indent))
861 (and (= (char-syntax (following-char)) ?\
))
864 (when (condition-case nil
(progn (forward-sexp -
1) t
)
866 (perl-indent-new-calculate 'virtual
))))
867 (and (and (= (following-char) ?
{)
868 (save-excursion (forward-char) (perl-hanging-paren-p)))
869 (+ (or default
(perl-calculate-indent))
871 (or default
(perl-calculate-indent))))
873 (defun perl-calculate-indent ()
874 "Return appropriate indentation for current line as Perl code.
875 In usual case returns an integer: the column to indent to.
876 Returns (parse-state) if line starts inside a string."
878 (let ((indent-point (point))
879 (case-fold-search nil
)
882 state containing-sexp
)
883 (setq containing-sexp
(nth 1 (syntax-ppss indent-point
)))
885 ;; Don't auto-indent in a quoted string or a here-document.
886 ((or (nth 3 state
) (eq 2 (nth 7 state
))) 'noindent
)
887 ((null containing-sexp
) ; Line is at top level.
888 (skip-chars-forward " \t\f")
889 (if (memq (following-char)
890 (if perl-indent-parens-as-block
'(?\
{ ?\
( ?\
[) '(?\
{)))
891 0 ; move to beginning of line if it starts a function body
892 ;; indent a little if this is a continuation line
893 (perl-backward-to-noncomment)
895 (memq (preceding-char) '(?\
; ?\})))
896 0 perl-continued-statement-offset
)))
897 ((/= (char-after containing-sexp
) ?
{)
898 ;; line is expression, not statement:
899 ;; indent to just after the surrounding open.
900 (goto-char (1+ containing-sexp
))
901 (if (perl-hanging-paren-p)
902 ;; We're indenting an arg of a call like:
903 ;; $a = foobarlongnamefun (
908 (skip-syntax-backward "(")
910 (while (save-excursion
911 (skip-syntax-backward " ") (not (bolp)))
914 (+ (current-column) perl-indent-level
))
915 (if perl-indent-continued-arguments
916 (+ perl-indent-continued-arguments
(current-indentation))
917 (skip-chars-forward " \t")
919 ;; Statement level. Is it a continuation or a new statement?
920 ((setq prev-char
(perl-continuation-line-p))
921 ;; This line is continuation of preceding line's statement;
922 ;; indent perl-continued-statement-offset more than the
923 ;; previous line of the statement.
924 (perl-backward-to-start-of-continued-exp)
925 (+ (if (or (save-excursion
926 (perl-continuation-line-p))
927 (and (eq prev-char ?\
,)
928 (looking-at "[[:alnum:]_]+[ \t\n]*=>")))
929 ;; If the continued line is itself a continuation
930 ;; line, then align, otherwise add an offset.
931 0 perl-continued-statement-offset
)
933 (if (save-excursion (goto-char indent-point
)
935 (if perl-indent-parens-as-block
936 "[ \t]*[{([]" "[ \t]*{")))
937 perl-continued-brace-offset
0)))
939 ;; This line starts a new statement.
940 ;; Position at last unclosed open.
941 (goto-char containing-sexp
)
943 ;; Is line first statement after an open-brace?
944 ;; If no, find that first statement and indent like it.
947 ;; Skip over comments and labels following openbrace.
949 (skip-chars-forward " \t\f\n")
950 (cond ((looking-at ";?#")
952 ((looking-at "\\(\\w\\|\\s_\\)+:[^:]")
953 (setq colon-line-end
(line-end-position))
954 (search-forward ":")))))
955 ;; The first following code counts
956 ;; if it is before the line we want to indent.
957 (and (< (point) indent-point
)
958 (if (> colon-line-end
(point))
959 (- (current-indentation) perl-label-offset
)
961 ;; If no previous statement,
962 ;; indent it relative to line brace is on.
963 ;; For open paren in column zero, don't let statement
964 ;; start there too. If perl-indent-level is zero,
965 ;; use perl-brace-offset + perl-continued-statement-offset
966 ;; For open-braces not the first thing in a line,
967 ;; add in perl-brace-imaginary-offset.
968 (+ (if (and (bolp) (zerop perl-indent-level
))
969 (+ perl-brace-offset perl-continued-statement-offset
)
971 ;; Move back over whitespace before the openbrace.
972 ;; If openbrace is not first nonwhite thing on the line,
973 ;; add the perl-brace-imaginary-offset.
974 (progn (skip-chars-backward " \t")
975 (if (bolp) 0 perl-brace-imaginary-offset
))
976 ;; If the openbrace is preceded by a parenthesized exp,
977 ;; move to the beginning of that;
978 ;; possibly a different line
980 (if (eq (preceding-char) ?\
))
982 ;; Get initial indentation of the line we are on.
983 (current-indentation)))))))))
985 (defun perl-backward-to-noncomment ()
986 "Move point backward to after the first non-white-space, skipping comments."
987 (forward-comment (- (point-max))))
989 (defun perl-backward-to-start-of-continued-exp ()
991 (let ((c (preceding-char)))
993 ((memq c
'(?\
; ?\{ ?\[ ?\()) (forward-comment (point-max)) nil)
994 ((memq c
'(?\
) ?\
] ?\
} ?
\"))
995 (forward-sexp -
1) (forward-comment (- (point))) t
)
996 ((eq ?w
(char-syntax c
))
997 (forward-word-strictly -
1) (forward-comment (- (point))) t
)
998 (t (forward-char -
1) (forward-comment (- (point))) t
)))))
1000 ;; note: this may be slower than the c-mode version, but I can understand it.
1001 (defalias 'indent-perl-exp
'perl-indent-exp
)
1002 (defun perl-indent-exp ()
1003 "Indent each line of the Perl grouping following point."
1005 (let* ((case-fold-search nil
)
1006 (oldpnt (point-marker))
1007 (bof-mark (save-excursion
1009 (perl-beginning-of-function)
1011 eol last-mark lsexp-mark delta
)
1012 (if (= (char-after (marker-position bof-mark
)) ?
=)
1013 (message "Can't indent a format statement")
1014 (message "Indenting Perl expression...")
1015 (setq eol
(line-end-position))
1016 (save-excursion ; locate matching close paren
1017 (while (and (not (eobp)) (<= (point) eol
))
1018 (parse-partial-sexp (point) (point-max) 0))
1019 (setq last-mark
(point-marker)))
1020 (setq lsexp-mark bof-mark
)
1022 (while (< (point) (marker-position last-mark
))
1023 (setq delta
(perl-indent-line nil
))
1024 (if (numberp delta
) ; unquoted start-of-line?
1027 (delete-horizontal-space))
1028 (setq lsexp-mark
(point-marker))))
1031 (if (nth 4 (parse-partial-sexp (marker-position lsexp-mark
) eol
))
1032 (progn ; line ends in a comment
1034 (if (or (not (looking-at "\\s-*;?#"))
1037 (= (- (current-indentation) delta
) comment-column
)))
1038 (if (and comment-start-skip
1039 (re-search-forward comment-start-skip eol t
))
1040 (indent-for-comment))))) ; indent existing comment
1042 (goto-char (marker-position oldpnt
))
1043 (message "Indenting Perl expression...done"))))
1045 (defun perl-beginning-of-function (&optional arg
)
1046 "Move backward to next beginning-of-function, or as far as possible.
1047 With argument, repeat that many times; negative args move forward.
1048 Returns new value of point in all cases."
1050 (or arg
(setq arg
1))
1051 (if (< arg
0) (forward-char 1))
1054 "^\\s(\\|^\\s-*sub\\b[ \t\n]*\\_<[^{]+{\\|^\\s-*format\\b[^=]*=\\|^\\."
1056 (goto-char (1- (match-end 0))))
1059 ;; note: this routine is adapted directly from emacs lisp.el, end-of-defun;
1060 ;; no bugs have been removed :-)
1061 (defun perl-end-of-function (&optional arg
)
1062 "Move forward to next end-of-function.
1063 The end of a function is found by moving forward from the beginning of one.
1064 With argument, repeat that many times; negative args move backward."
1066 (or arg
(setq arg
1))
1068 (while (and (> arg
0) (< (point) (point-max)))
1069 (let ((pos (point)))
1074 (perl-beginning-of-function 1)
1077 (or (bobp) (forward-char -
1))
1078 (perl-beginning-of-function -
1))
1081 (skip-chars-forward " \t")
1082 (if (looking-at "[#\n]")
1085 (setq arg
(1- arg
)))
1087 (let ((pos (point)))
1088 (perl-beginning-of-function 1)
1091 (if (>= (point) pos
)
1092 (if (progn (perl-beginning-of-function 2) (not (bobp)))
1095 (skip-chars-forward " \t")
1096 (if (looking-at "[#\n]")
1098 (goto-char (point-min)))))
1099 (setq arg
(1+ arg
)))))
1101 (defalias 'mark-perl-function
'perl-mark-function
)
1102 (defun perl-mark-function ()
1103 "Put mark at end of Perl function, point at beginning."
1106 (perl-end-of-function)
1108 (perl-beginning-of-function)
1109 (backward-paragraph))
1111 (provide 'perl-mode
)
1113 ;;; perl-mode.el ends here