]> code.delx.au - gnu-emacs/blob - lisp/progmodes/perl-mode.el
* lisp/progmodes/perl-mode.el (perl-indent-line): Use `noindent' in strings.
[gnu-emacs] / lisp / progmodes / perl-mode.el
1 ;;; perl-mode.el --- Perl code editing commands for GNU Emacs
2
3 ;; Copyright (C) 1990, 1994, 2001-2012 Free Software Foundation, Inc.
4
5 ;; Author: William F. Mann
6 ;; Maintainer: FSF
7 ;; Adapted-By: ESR
8 ;; Keywords: languages
9
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.
12
13 ;; This file is part of GNU Emacs.
14
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.
19
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.
24
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/>.
27
28 ;;; Commentary:
29
30 ;; To enter perl-mode automatically, add (autoload 'perl-mode "perl-mode")
31 ;; to your .emacs 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))
37 ;; auto-mode-alist))
38 ;; to your .emacs file; otherwise the .pl suffix defaults to prolog-mode.
39
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.
42
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 \#.
49
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.
53
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.
60
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.
63
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.
69 ;; 3) The << quoting operators are not recognized; see below.
70 ;; 5) To make '$' work correctly, $' is not recognized as a variable.
71 ;; Use "$'" or $POSTMATCH instead.
72 ;;
73 ;; If you don't use font-lock, additional problems will appear:
74 ;; 1) Regular expression delimiters do not act as quotes, so special
75 ;; characters such as `'"#:;[](){} may need to be backslashed
76 ;; in regular expressions and in both parts of s/// and tr///.
77 ;; 4) The q and qq quoting operators are not recognized; see below.
78 ;; 5) To make variables such a $' and $#array work, perl-mode treats
79 ;; $ just like backslash, so '$' is not treated correctly.
80 ;; 6) Unfortunately, treating $ like \ makes ${var} be treated as an
81 ;; unmatched }. See below.
82 ;; 7) When ' (quote) is used as a package name separator, perl-mode
83 ;; doesn't understand, and thinks it is seeing a quoted string.
84
85 ;; Here are some ugly tricks to bypass some of these problems: the perl
86 ;; expression /`/ (that's a back-tick) usually evaluates harmlessly,
87 ;; but will trick perl-mode into starting a quoted string, which
88 ;; can be ended with another /`/. Assuming you have no embedded
89 ;; back-ticks, this can used to help solve problem 3:
90 ;;
91 ;; /`/; $ugly = q?"'$?; /`/;
92 ;;
93 ;; The same trick can be used for problem 6 as in:
94 ;; /{/; while (<${glob_me}>)
95 ;; but a simpler solution is to add a space between the $ and the {:
96 ;; while (<$ {glob_me}>)
97 ;;
98 ;; Problem 7 is even worse, but this 'fix' does work :-(
99 ;; $DB'stop#'
100 ;; [$DB'line#'
101 ;; ] =~ s/;9$//;
102
103 ;;; Code:
104
105 (eval-when-compile (require 'cl))
106
107 (defvar font-lock-comment-face)
108 (defvar font-lock-doc-face)
109 (defvar font-lock-string-face)
110
111 (defgroup perl nil
112 "Major mode for editing Perl code."
113 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
114 :prefix "perl-"
115 :group 'languages)
116
117 (defvar perl-mode-abbrev-table nil
118 "Abbrev table in use in perl-mode buffers.")
119 (define-abbrev-table 'perl-mode-abbrev-table ())
120
121 (defvar perl-mode-map
122 (let ((map (make-sparse-keymap)))
123 (define-key map "{" 'perl-electric-terminator)
124 (define-key map "}" 'perl-electric-terminator)
125 (define-key map ";" 'perl-electric-terminator)
126 (define-key map ":" 'perl-electric-terminator)
127 (define-key map "\e\C-a" 'perl-beginning-of-function)
128 (define-key map "\e\C-e" 'perl-end-of-function)
129 (define-key map "\e\C-h" 'perl-mark-function)
130 (define-key map "\e\C-q" 'perl-indent-exp)
131 (define-key map "\177" 'backward-delete-char-untabify)
132 (define-key map "\t" 'perl-indent-command)
133 map)
134 "Keymap used in Perl mode.")
135
136 (autoload 'c-macro-expand "cmacexp"
137 "Display the result of expanding all C macros occurring in the region.
138 The expansion is entirely correct because it uses the C preprocessor."
139 t)
140
141 (defvar perl-mode-syntax-table
142 (let ((st (make-syntax-table (standard-syntax-table))))
143 (modify-syntax-entry ?\n ">" st)
144 (modify-syntax-entry ?# "<" st)
145 ;; `$' is also a prefix char so I was tempted to say "/ p",
146 ;; but the `p' thingy basically overrides the `/' :-( --stef
147 (modify-syntax-entry ?$ "/" st)
148 (modify-syntax-entry ?% ". p" st)
149 (modify-syntax-entry ?@ ". p" st)
150 (modify-syntax-entry ?& "." st)
151 (modify-syntax-entry ?\' "\"" st)
152 (modify-syntax-entry ?* "." st)
153 (modify-syntax-entry ?+ "." st)
154 (modify-syntax-entry ?- "." st)
155 (modify-syntax-entry ?/ "." st)
156 (modify-syntax-entry ?< "." st)
157 (modify-syntax-entry ?= "." st)
158 (modify-syntax-entry ?> "." st)
159 (modify-syntax-entry ?\\ "\\" st)
160 (modify-syntax-entry ?` "\"" st)
161 (modify-syntax-entry ?| "." st)
162 st)
163 "Syntax table in use in `perl-mode' buffers.")
164
165 (defvar perl-imenu-generic-expression
166 '(;; Functions
167 (nil "^sub\\s-+\\([-A-Za-z0-9+_:]+\\)" 1)
168 ;;Variables
169 ("Variables" "^\\(?:my\\|our\\)\\s-+\\([$@%][-A-Za-z0-9+_:]+\\)\\s-*=" 1)
170 ("Packages" "^package\\s-+\\([-A-Za-z0-9+_:]+\\);" 1)
171 ("Doc sections" "^=head[0-9][ \t]+\\(.*\\)" 1))
172 "Imenu generic expression for Perl mode. See `imenu-generic-expression'.")
173
174 ;; Regexps updated with help from Tom Tromey <tromey@cambric.colorado.edu> and
175 ;; Jim Campbell <jec@murzim.ca.boeing.com>.
176
177 (defconst perl-font-lock-keywords-1
178 '(;; What is this for?
179 ;;("\\(--- .* ---\\|=== .* ===\\)" . font-lock-string-face)
180 ;;
181 ;; Fontify preprocessor statements as we do in `c-font-lock-keywords'.
182 ;; Ilya Zakharevich <ilya@math.ohio-state.edu> thinks this is a bad idea.
183 ;; ("^#[ \t]*include[ \t]+\\(<[^>\"\n]+>\\)" 1 font-lock-string-face)
184 ;; ("^#[ \t]*define[ \t]+\\(\\sw+\\)(" 1 font-lock-function-name-face)
185 ;; ("^#[ \t]*if\\>"
186 ;; ("\\<\\(defined\\)\\>[ \t]*(?\\(\\sw+\\)?" nil nil
187 ;; (1 font-lock-constant-face) (2 font-lock-variable-name-face nil t)))
188 ;; ("^#[ \t]*\\(\\sw+\\)\\>[ \t]*\\(\\sw+\\)?"
189 ;; (1 font-lock-constant-face) (2 font-lock-variable-name-face nil t))
190 ;;
191 ;; Fontify function and package names in declarations.
192 ("\\<\\(package\\|sub\\)\\>[ \t]*\\(\\sw+\\)?"
193 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
194 ("\\<\\(import\\|no\\|require\\|use\\)\\>[ \t]*\\(\\sw+\\)?"
195 (1 font-lock-keyword-face) (2 font-lock-constant-face nil t)))
196 "Subdued level highlighting for Perl mode.")
197
198 (defconst perl-font-lock-keywords-2
199 (append perl-font-lock-keywords-1
200 (list
201 ;;
202 ;; Fontify keywords, except those fontified otherwise.
203 (concat "\\<"
204 (regexp-opt '("if" "until" "while" "elsif" "else" "unless"
205 "do" "dump" "for" "foreach" "exit" "die"
206 "BEGIN" "END" "return" "exec" "eval") t)
207 "\\>")
208 ;;
209 ;; Fontify local and my keywords as types.
210 '("\\<\\(local\\|my\\)\\>" . font-lock-type-face)
211 ;;
212 ;; Fontify function, variable and file name references.
213 '("&\\(\\sw+\\(::\\sw+\\)*\\)" 1 font-lock-function-name-face)
214 ;; Additionally underline non-scalar variables. Maybe this is a bad idea.
215 ;;'("[$@%*][#{]?\\(\\sw+\\)" 1 font-lock-variable-name-face)
216 '("[$*]{?\\(\\sw+\\(::\\sw+\\)*\\)" 1 font-lock-variable-name-face)
217 '("\\([@%]\\|\\$#\\)\\(\\sw+\\(::\\sw+\\)*\\)"
218 (2 (cons font-lock-variable-name-face '(underline))))
219 '("<\\(\\sw+\\)>" 1 font-lock-constant-face)
220 ;;
221 ;; Fontify keywords with/and labels as we do in `c++-font-lock-keywords'.
222 '("\\<\\(continue\\|goto\\|last\\|next\\|redo\\)\\>[ \t]*\\(\\sw+\\)?"
223 (1 font-lock-keyword-face) (2 font-lock-constant-face nil t))
224 '("^[ \t]*\\(\\sw+\\)[ \t]*:[^:]" 1 font-lock-constant-face)))
225 "Gaudy level highlighting for Perl mode.")
226
227 (defvar perl-font-lock-keywords perl-font-lock-keywords-1
228 "Default expressions to highlight in Perl mode.")
229
230 (defvar perl-quote-like-pairs
231 '((?\( . ?\)) (?\[ . ?\]) (?\{ . ?\}) (?\< . ?\>)))
232
233 ;; FIXME: handle here-docs and regexps.
234 ;; <<EOF <<"EOF" <<'EOF' (no space)
235 ;; see `man perlop'
236 ;; ?...?
237 ;; /.../
238 ;; m [...]
239 ;; m /.../
240 ;; q /.../ = '...'
241 ;; qq /.../ = "..."
242 ;; qx /.../ = `...`
243 ;; qr /.../ = precompiled regexp =~=~ m/.../
244 ;; qw /.../
245 ;; s /.../.../
246 ;; s <...> /.../
247 ;; s '...'...'
248 ;; tr /.../.../
249 ;; y /.../.../
250 ;;
251 ;; <file*glob>
252 (defun perl-syntax-propertize-function (start end)
253 (let ((case-fold-search nil))
254 (goto-char start)
255 (perl-syntax-propertize-special-constructs end)
256 ;; TODO: here-documents ("<<\\(\\sw\\|['\"]\\)")
257 (funcall
258 (syntax-propertize-rules
259 ;; Turn POD into b-style comments. Place the cut rule first since it's
260 ;; more specific.
261 ("^=cut\\>.*\\(\n\\)" (1 "> b"))
262 ("^\\(=\\)\\sw" (1 "< b"))
263 ;; Catch ${ so that ${var} doesn't screw up indentation.
264 ;; This also catches $' to handle 'foo$', although it should really
265 ;; check that it occurs inside a '..' string.
266 ("\\(\\$\\)[{']" (1 ". p"))
267 ;; Handle funny names like $DB'stop.
268 ("\\$ ?{?^?[_a-zA-Z][_a-zA-Z0-9]*\\('\\)[_a-zA-Z]" (1 "_"))
269 ;; format statements
270 ("^[ \t]*format.*=[ \t]*\\(\n\\)"
271 (1 (prog1 "\"" (perl-syntax-propertize-special-constructs end))))
272 ;; Funny things in `sub' arg-specs like `sub myfun ($)' or `sub ($)'.
273 ;; Be careful not to match "sub { (...) ... }".
274 ("\\<sub\\(?:[[:space:]]+[^{}[:punct:][:space:]]+\\)?[[:space:]]*(\\([^)]+\\))"
275 (1 "."))
276 ;; Turn __DATA__ trailer into a comment.
277 ("^\\(_\\)_\\(?:DATA\\|END\\)__[ \t]*\\(?:\\(\n\\)#.-\\*-.*perl.*-\\*-\\|\n.*\\)"
278 (1 "< c") (2 "> c")
279 (0 (ignore (put-text-property (match-beginning 0) (match-end 0)
280 'syntax-multiline t))))
281 ;; Regexp and funny quotes. Distinguishing a / that starts a regexp
282 ;; match from the division operator is ...interesting.
283 ;; Basically, / is a regexp match if it's preceded by an infix operator
284 ;; (or some similar separator), or by one of the special keywords
285 ;; corresponding to builtin functions that can take their first arg
286 ;; without parentheses. Of course, that presume we're looking at the
287 ;; *opening* slash. We can afford to mis-match the closing ones
288 ;; here, because they will be re-treated separately later in
289 ;; perl-font-lock-special-syntactic-constructs.
290 ((concat "\\(?:\\(?:^\\|[^$@&%[:word:]]\\)"
291 (regexp-opt '("split" "if" "unless" "until" "while" "split"
292 "grep" "map" "not" "or" "and"))
293 "\\|[?:.,;=!~({[]\\|\\(^\\)\\)[ \t\n]*\\(/\\)")
294 (2 (ignore
295 (if (and (match-end 1) ; / at BOL.
296 (save-excursion
297 (goto-char (match-end 1))
298 (forward-comment (- (point-max)))
299 (put-text-property (point) (match-end 2)
300 'syntax-multiline t)
301 (not (memq (char-before)
302 '(?? ?: ?. ?, ?\; ?= ?! ?~ ?\( ?\[)))))
303 nil ;; A division sign instead of a regexp-match.
304 (put-text-property (match-beginning 2) (match-end 2)
305 'syntax-table (string-to-syntax "\""))
306 (perl-syntax-propertize-special-constructs end)))))
307 ("\\(^\\|[?:.,;=!~({[ \t]\\)\\([msy]\\|q[qxrw]?\\|tr\\)\\>\\s-*\\(?:\\([^])}>= \n\t]\\)\\|\\(?3:=\\)[^>]\\)"
308 ;; Nasty cases:
309 ;; /foo/m $a->m $#m $m @m %m
310 ;; \s (appears often in regexps).
311 ;; -s file
312 ;; y => 3
313 ;; sub tr {...}
314 (3 (ignore
315 (if (save-excursion (goto-char (match-beginning 0))
316 (forward-word -1)
317 (looking-at-p "sub[ \t\n]"))
318 ;; This is defining a function.
319 nil
320 (put-text-property (match-beginning 3) (match-end 3)
321 'syntax-table
322 (if (assoc (char-after (match-beginning 3))
323 perl-quote-like-pairs)
324 (string-to-syntax "|")
325 (string-to-syntax "\"")))
326 (perl-syntax-propertize-special-constructs end))))))
327 (point) end)))
328
329 (defvar perl-empty-syntax-table
330 (let ((st (copy-syntax-table)))
331 ;; Make all chars be of punctuation syntax.
332 (dotimes (i 256) (aset st i '(1)))
333 (modify-syntax-entry ?\\ "\\" st)
334 st)
335 "Syntax table used internally for processing quote-like operators.")
336
337 (defun perl-quote-syntax-table (char)
338 (let ((close (cdr (assq char perl-quote-like-pairs)))
339 (st (copy-syntax-table perl-empty-syntax-table)))
340 (if (not close)
341 (modify-syntax-entry char "\"" st)
342 (modify-syntax-entry char "(" st)
343 (modify-syntax-entry close ")" st))
344 st))
345
346 (defun perl-syntax-propertize-special-constructs (limit)
347 "Propertize special constructs like regexps and formats."
348 (let ((state (syntax-ppss))
349 char)
350 (cond
351 ((or (null (setq char (nth 3 state)))
352 (and (characterp char) (eq (char-syntax (nth 3 state)) ?\")))
353 ;; Normal text, or comment, or docstring, or normal string.
354 nil)
355 ((eq (nth 3 state) ?\n)
356 ;; A `format' command.
357 (when (re-search-forward "^\\s *\\.\\s *\n" limit 'move)
358 (put-text-property (1- (point)) (point)
359 'syntax-table (string-to-syntax "\""))))
360 (t
361 ;; This is regexp like quote thingy.
362 (setq char (char-after (nth 8 state)))
363 (let ((startpos (point))
364 (twoargs (save-excursion
365 (goto-char (nth 8 state))
366 (skip-syntax-backward " ")
367 (skip-syntax-backward "w")
368 (member (buffer-substring
369 (point) (progn (forward-word 1) (point)))
370 '("tr" "s" "y"))))
371 (close (cdr (assq char perl-quote-like-pairs)))
372 (st (perl-quote-syntax-table char)))
373 (when (with-syntax-table st
374 (if close
375 ;; For paired delimiters, Perl allows nesting them, but
376 ;; since we treat them as strings, Emacs does not count
377 ;; those delimiters in `state', so we don't know how deep
378 ;; we are: we have to go back to the beginning of this
379 ;; "string" and count from there.
380 (condition-case nil
381 (progn
382 ;; Start after the first char since it doesn't have
383 ;; paren-syntax (an alternative would be to let-bind
384 ;; parse-sexp-lookup-properties).
385 (goto-char (1+ (nth 8 state)))
386 (up-list 1)
387 t)
388 ;; In case of error, make sure we don't move backward.
389 (scan-error (goto-char startpos) nil))
390 (not (or (nth 8 (parse-partial-sexp
391 ;; Since we don't know if point is within
392 ;; the first or the scond arg, we have to
393 ;; start from the beginning.
394 (if twoargs (1+ (nth 8 state)) (point))
395 limit nil nil state 'syntax-table))
396 ;; If we have a self-paired opener and a twoargs
397 ;; command, the form is s/../../ so we have to skip
398 ;; a second time.
399 ;; In the case of s{...}{...}, we only handle the
400 ;; first part here and the next below.
401 (when (and twoargs (not close))
402 (nth 8 (parse-partial-sexp
403 (point) limit
404 nil nil state 'syntax-table)))))))
405 ;; Point is now right after the arg(s).
406 (when (eq (char-before (1- (point))) ?$)
407 (put-text-property (- (point) 2) (1- (point))
408 'syntax-table '(1)))
409 (put-text-property (1- (point)) (point)
410 'syntax-table
411 (if close
412 (string-to-syntax "|")
413 (string-to-syntax "\"")))
414 ;; If we have two args with a non-self-paired starter (e.g.
415 ;; s{...}{...}) we're right after the first arg, so we still have to
416 ;; handle the second part.
417 (when (and twoargs close)
418 ;; Skip whitespace and make sure that font-lock will
419 ;; refontify the second part in the proper context.
420 (put-text-property
421 (point) (progn (forward-comment (point-max)) (point))
422 'syntax-multiline t)
423 ;;
424 (when (< (point) limit)
425 (put-text-property (point) (1+ (point))
426 'syntax-table
427 (if (assoc (char-after)
428 perl-quote-like-pairs)
429 ;; Put an `e' in the cdr to mark this
430 ;; char as "second arg starter".
431 (string-to-syntax "|e")
432 (string-to-syntax "\"e")))
433 (forward-char 1)
434 ;; Re-use perl-syntax-propertize-special-constructs to handle the
435 ;; second part (the first delimiter of second part can't be
436 ;; preceded by "s" or "tr" or "y", so it will not be considered
437 ;; as twoarg).
438 (perl-syntax-propertize-special-constructs limit)))))))))
439
440 (defun perl-font-lock-syntactic-face-function (state)
441 (cond
442 ((and (nth 3 state)
443 (eq ?e (cdr-safe (get-text-property (nth 8 state) 'syntax-table)))
444 ;; This is a second-arg of s{..}{...} form; let's check if this second
445 ;; arg is executable code rather than a string. For that, we need to
446 ;; look for an "e" after this second arg, so we have to hunt for the
447 ;; end of the arg. Depending on whether the whole arg has already
448 ;; been syntax-propertized or not, the end-char will have different
449 ;; syntaxes, so let's ignore syntax-properties temporarily so we can
450 ;; pretend it has not been syntax-propertized yet.
451 (let* ((parse-sexp-lookup-properties nil)
452 (char (char-after (nth 8 state)))
453 (paired (assq char perl-quote-like-pairs)))
454 (with-syntax-table (perl-quote-syntax-table char)
455 (save-excursion
456 (if (not paired)
457 (parse-partial-sexp (point) (point-max)
458 nil nil state 'syntax-table)
459 (condition-case nil
460 (progn
461 (goto-char (1+ (nth 8 state)))
462 (up-list 1))
463 (scan-error (goto-char (point-max)))))
464 (put-text-property (nth 8 state) (point)
465 'jit-lock-defer-multiline t)
466 (looking-at "[ \t]*\\sw*e")))))
467 nil)
468 (t (funcall (default-value 'font-lock-syntactic-face-function) state))))
469
470 (defcustom perl-indent-level 4
471 "*Indentation of Perl statements with respect to containing block."
472 :type 'integer
473 :group 'perl)
474
475 ;; Is is not unusual to put both things like perl-indent-level and
476 ;; cperl-indent-level in the local variable section of a file. If only
477 ;; one of perl-mode and cperl-mode is in use, a warning will be issued
478 ;; about the variable. Autoload these here, so that no warning is
479 ;; issued when using either perl-mode or cperl-mode.
480 ;;;###autoload(put 'perl-indent-level 'safe-local-variable 'integerp)
481 ;;;###autoload(put 'perl-continued-statement-offset 'safe-local-variable 'integerp)
482 ;;;###autoload(put 'perl-continued-brace-offset 'safe-local-variable 'integerp)
483 ;;;###autoload(put 'perl-brace-offset 'safe-local-variable 'integerp)
484 ;;;###autoload(put 'perl-brace-imaginary-offset 'safe-local-variable 'integerp)
485 ;;;###autoload(put 'perl-label-offset 'safe-local-variable 'integerp)
486
487 (defcustom perl-continued-statement-offset 4
488 "*Extra indent for lines not starting new statements."
489 :type 'integer
490 :group 'perl)
491 (defcustom perl-continued-brace-offset -4
492 "*Extra indent for substatements that start with open-braces.
493 This is in addition to `perl-continued-statement-offset'."
494 :type 'integer
495 :group 'perl)
496 (defcustom perl-brace-offset 0
497 "*Extra indentation for braces, compared with other text in same context."
498 :type 'integer
499 :group 'perl)
500 (defcustom perl-brace-imaginary-offset 0
501 "*Imagined indentation of an open brace that actually follows a statement."
502 :type 'integer
503 :group 'perl)
504 (defcustom perl-label-offset -2
505 "*Offset of Perl label lines relative to usual indentation."
506 :type 'integer
507 :group 'perl)
508 (defcustom perl-indent-continued-arguments nil
509 "*If non-nil offset of argument lines relative to usual indentation.
510 If nil, continued arguments are aligned with the first argument."
511 :type '(choice integer (const nil))
512 :group 'perl)
513
514 (defcustom perl-tab-always-indent tab-always-indent
515 "Non-nil means TAB in Perl mode always indents the current line.
516 Otherwise it inserts a tab character if you type it past the first
517 nonwhite character on the line."
518 :type 'boolean
519 :group 'perl)
520
521 ;; I changed the default to nil for consistency with general Emacs
522 ;; conventions -- rms.
523 (defcustom perl-tab-to-comment nil
524 "*Non-nil means TAB moves to eol or makes a comment in some cases.
525 For lines which don't need indenting, TAB either indents an
526 existing comment, moves to end-of-line, or if at end-of-line already,
527 create a new comment."
528 :type 'boolean
529 :group 'perl)
530
531 (defcustom perl-nochange ";?#\\|\f\\|\\s(\\|\\(\\w\\|\\s_\\)+:[^:]"
532 "*Lines starting with this regular expression are not auto-indented."
533 :type 'regexp
534 :group 'perl)
535
536 ;; Outline support
537
538 (defvar perl-outline-regexp
539 (concat (mapconcat 'cadr perl-imenu-generic-expression "\\|")
540 "\\|^=cut\\>"))
541
542 (defun perl-outline-level ()
543 (cond
544 ((looking-at "package\\s-") 0)
545 ((looking-at "sub\\s-") 1)
546 ((looking-at "=head[0-9]") (- (char-before (match-end 0)) ?0))
547 ((looking-at "=cut") 1)
548 (t 3)))
549 \f
550 (defvar perl-mode-hook nil
551 "Normal hook to run when entering Perl mode.")
552
553 ;;;###autoload
554 (define-derived-mode perl-mode prog-mode "Perl"
555 "Major mode for editing Perl code.
556 Expression and list commands understand all Perl brackets.
557 Tab indents for Perl code.
558 Comments are delimited with # ... \\n.
559 Paragraphs are separated by blank lines only.
560 Delete converts tabs to spaces as it moves back.
561 \\{perl-mode-map}
562 Variables controlling indentation style:
563 `perl-tab-always-indent'
564 Non-nil means TAB in Perl mode should always indent the current line,
565 regardless of where in the line point is when the TAB command is used.
566 `perl-tab-to-comment'
567 Non-nil means that for lines which don't need indenting, TAB will
568 either delete an empty comment, indent an existing comment, move
569 to end-of-line, or if at end-of-line already, create a new comment.
570 `perl-nochange'
571 Lines starting with this regular expression are not auto-indented.
572 `perl-indent-level'
573 Indentation of Perl statements within surrounding block.
574 The surrounding block's indentation is the indentation
575 of the line on which the open-brace appears.
576 `perl-continued-statement-offset'
577 Extra indentation given to a substatement, such as the
578 then-clause of an if or body of a while.
579 `perl-continued-brace-offset'
580 Extra indentation given to a brace that starts a substatement.
581 This is in addition to `perl-continued-statement-offset'.
582 `perl-brace-offset'
583 Extra indentation for line if it starts with an open brace.
584 `perl-brace-imaginary-offset'
585 An open brace following other text is treated as if it were
586 this far to the right of the start of its line.
587 `perl-label-offset'
588 Extra indentation for line that is a label.
589 `perl-indent-continued-arguments'
590 Offset of argument lines relative to usual indentation.
591
592 Various indentation styles: K&R BSD BLK GNU LW
593 perl-indent-level 5 8 0 2 4
594 perl-continued-statement-offset 5 8 4 2 4
595 perl-continued-brace-offset 0 0 0 0 -4
596 perl-brace-offset -5 -8 0 0 0
597 perl-brace-imaginary-offset 0 0 4 0 0
598 perl-label-offset -5 -8 -2 -2 -2
599
600 Turning on Perl mode runs the normal hook `perl-mode-hook'."
601 :abbrev-table perl-mode-abbrev-table
602 (set (make-local-variable 'paragraph-start) (concat "$\\|" page-delimiter))
603 (set (make-local-variable 'paragraph-separate) paragraph-start)
604 (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
605 (set (make-local-variable 'indent-line-function) #'perl-indent-line)
606 (set (make-local-variable 'comment-start) "# ")
607 (set (make-local-variable 'comment-end) "")
608 (set (make-local-variable 'comment-start-skip) "\\(^\\|\\s-\\);?#+ *")
609 (set (make-local-variable 'comment-indent-function) #'perl-comment-indent)
610 (set (make-local-variable 'parse-sexp-ignore-comments) t)
611 ;; Tell font-lock.el how to handle Perl.
612 (setq font-lock-defaults '((perl-font-lock-keywords
613 perl-font-lock-keywords-1
614 perl-font-lock-keywords-2)
615 nil nil ((?\_ . "w")) nil
616 (font-lock-syntactic-face-function
617 . perl-font-lock-syntactic-face-function)))
618 (set (make-local-variable 'syntax-propertize-function)
619 #'perl-syntax-propertize-function)
620 (add-hook 'syntax-propertize-extend-region-functions
621 #'syntax-propertize-multiline 'append 'local)
622 ;; Tell imenu how to handle Perl.
623 (set (make-local-variable 'imenu-generic-expression)
624 perl-imenu-generic-expression)
625 (setq imenu-case-fold-search nil)
626 ;; Setup outline-minor-mode.
627 (set (make-local-variable 'outline-regexp) perl-outline-regexp)
628 (set (make-local-variable 'outline-level) 'perl-outline-level))
629 \f
630 ;; This is used by indent-for-comment
631 ;; to decide how much to indent a comment in Perl code
632 ;; based on its context.
633 (defun perl-comment-indent ()
634 (if (and (bolp) (not (eolp)))
635 0 ;Existing comment at bol stays there.
636 comment-column))
637
638 (defalias 'electric-perl-terminator 'perl-electric-terminator)
639 (defun perl-electric-terminator (arg)
640 "Insert character and maybe adjust indentation.
641 If at end-of-line, and not in a comment or a quote, correct the indentation."
642 (interactive "P")
643 (let ((insertpos (point)))
644 (and (not arg) ; decide whether to indent
645 (eolp)
646 (save-excursion
647 (beginning-of-line)
648 (and (not ; eliminate comments quickly
649 (and comment-start-skip
650 (re-search-forward comment-start-skip insertpos t)) )
651 (or (/= last-command-event ?:)
652 ;; Colon is special only after a label ....
653 (looking-at "\\s-*\\(\\w\\|\\s_\\)+$"))
654 (let ((pps (parse-partial-sexp
655 (perl-beginning-of-function) insertpos)))
656 (not (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))
657 (progn ; must insert, indent, delete
658 (insert-char last-command-event 1)
659 (perl-indent-line)
660 (delete-char -1))))
661 (self-insert-command (prefix-numeric-value arg)))
662
663 ;; not used anymore, but may be useful someday:
664 ;;(defun perl-inside-parens-p ()
665 ;; (condition-case ()
666 ;; (save-excursion
667 ;; (save-restriction
668 ;; (narrow-to-region (point)
669 ;; (perl-beginning-of-function))
670 ;; (goto-char (point-max))
671 ;; (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
672 ;; (error nil)))
673 \f
674 (defun perl-indent-command (&optional arg)
675 "Indent Perl code in the active region or current line.
676 In Transient Mark mode, when the region is active, reindent the region.
677 Otherwise, with a prefix argument, reindent the current line
678 unconditionally.
679
680 Otherwise, if `perl-tab-always-indent' is nil and point is not in
681 the indentation area at the beginning of the line, insert a tab.
682
683 Otherwise, indent the current line. If point was within the
684 indentation area, it is moved to the end of the indentation area.
685 If the line was already indented properly and point was not
686 within the indentation area, and if `perl-tab-to-comment' is
687 non-nil (the default), then do the first possible action from the
688 following list:
689
690 1) delete an empty comment
691 2) move forward to start of comment, indenting if necessary
692 3) move forward to end of line
693 4) create an empty comment
694 5) move backward to start of comment, indenting if necessary."
695 (interactive "P")
696 (cond ((use-region-p) ; indent the active region
697 (indent-region (region-beginning) (region-end)))
698 (arg
699 (perl-indent-line "\f")) ; just indent this line
700 ((and (not perl-tab-always-indent)
701 (> (current-column) (current-indentation)))
702 (insert-tab))
703 (t
704 (let* ((oldpnt (point))
705 (lsexp (progn (beginning-of-line) (point)))
706 (bof (perl-beginning-of-function))
707 (delta (progn
708 (goto-char oldpnt)
709 (perl-indent-line "\f\\|;?#" bof))))
710 (and perl-tab-to-comment
711 (= oldpnt (point)) ; done if point moved
712 (if (listp delta) ; if line starts in a quoted string
713 (setq lsexp (or (nth 2 delta) bof))
714 (= delta 0)) ; done if indenting occurred
715 (let ((eol (progn (end-of-line) (point)))
716 state)
717 (cond ((= (char-after bof) ?=)
718 (if (= oldpnt eol)
719 (message "In a format statement")))
720 ((progn (setq state (parse-partial-sexp lsexp eol))
721 (nth 3 state))
722 (if (= oldpnt eol) ; already at eol in a string
723 (message "In a string which starts with a %c."
724 (nth 3 state))))
725 ((not (nth 4 state))
726 (if (= oldpnt eol) ; no comment, create one?
727 (indent-for-comment)))
728 ((progn (beginning-of-line)
729 (and comment-start-skip
730 (re-search-forward
731 comment-start-skip eol 'move)))
732 (if (eolp)
733 (progn ; delete existing comment
734 (goto-char (match-beginning 0))
735 (skip-chars-backward " \t")
736 (delete-region (point) eol))
737 (if (or (< oldpnt (point)) (= oldpnt eol))
738 (indent-for-comment) ; indent existing comment
739 (end-of-line))))
740 ((/= oldpnt eol)
741 (end-of-line))
742 (t
743 (message "Use backslash to quote # characters.")
744 (ding t)))))))))
745
746 (defun perl-indent-line (&optional nochange parse-start)
747 "Indent current line as Perl code.
748 Return the amount the indentation
749 changed by, or (parse-state) if line starts in a quoted string."
750 (let ((case-fold-search nil)
751 (pos (- (point-max) (point)))
752 (bof (or parse-start (save-excursion (perl-beginning-of-function))))
753 beg indent shift-amt)
754 (beginning-of-line)
755 (setq beg (point))
756 (setq shift-amt
757 (cond ((eq (char-after bof) ?=) 0)
758 ((listp (setq indent (perl-calculate-indent bof))) indent)
759 ((eq 'noindent indent) indent)
760 ((looking-at (or nochange perl-nochange)) 0)
761 (t
762 (skip-chars-forward " \t\f")
763 (setq indent (perl-indent-new-calculate nil indent bof))
764 (- indent (current-column)))))
765 (skip-chars-forward " \t\f")
766 (if (and (numberp shift-amt) (/= 0 shift-amt))
767 (progn (delete-region beg (point))
768 (indent-to indent)))
769 ;; If initial point was within line's indentation,
770 ;; position after the indentation. Else stay at same point in text.
771 (if (> (- (point-max) pos) (point))
772 (goto-char (- (point-max) pos)))
773 shift-amt))
774
775 (defun perl-continuation-line-p (limit)
776 "Move to end of previous line and return non-nil if continued."
777 ;; Statement level. Is it a continuation or a new statement?
778 ;; Find previous non-comment character.
779 (perl-backward-to-noncomment)
780 ;; Back up over label lines, since they don't
781 ;; affect whether our line is a continuation.
782 (while (or (eq (preceding-char) ?\,)
783 (and (eq (preceding-char) ?:)
784 (memq (char-syntax (char-after (- (point) 2)))
785 '(?w ?_))))
786 (if (eq (preceding-char) ?\,)
787 (perl-backward-to-start-of-continued-exp limit)
788 (beginning-of-line))
789 (perl-backward-to-noncomment))
790 ;; Now we get the answer.
791 (not (memq (preceding-char) '(?\; ?\} ?\{))))
792
793 (defun perl-hanging-paren-p ()
794 "Non-nil if we are right after a hanging parenthesis-like char."
795 (and (looking-at "[ \t]*$")
796 (save-excursion
797 (skip-syntax-backward " (") (not (bolp)))))
798
799 (defun perl-indent-new-calculate (&optional virtual default parse-start)
800 (or
801 (and virtual (save-excursion (skip-chars-backward " \t") (bolp))
802 (current-column))
803 (and (looking-at "\\(\\w\\|\\s_\\)+:[^:]")
804 (max 1 (+ (or default (perl-calculate-indent parse-start))
805 perl-label-offset)))
806 (and (= (char-syntax (following-char)) ?\))
807 (save-excursion
808 (forward-char 1)
809 (forward-sexp -1)
810 (perl-indent-new-calculate
811 ;; Recalculate the parsing-start, since we may have jumped
812 ;; dangerously close (typically in the case of nested functions).
813 'virtual nil (save-excursion (perl-beginning-of-function)))))
814 (and (and (= (following-char) ?{)
815 (save-excursion (forward-char) (perl-hanging-paren-p)))
816 (+ (or default (perl-calculate-indent parse-start))
817 perl-brace-offset))
818 (or default (perl-calculate-indent parse-start))))
819
820 (defun perl-calculate-indent (&optional parse-start)
821 "Return appropriate indentation for current line as Perl code.
822 In usual case returns an integer: the column to indent to.
823 Returns (parse-state) if line starts inside a string.
824 Optional argument PARSE-START should be the position of `beginning-of-defun'."
825 (save-excursion
826 (let ((indent-point (point))
827 (case-fold-search nil)
828 (colon-line-end 0)
829 state containing-sexp)
830 (if parse-start ;used to avoid searching
831 (goto-char parse-start)
832 (perl-beginning-of-function))
833 ;; We might be now looking at a local function that has nothing to
834 ;; do with us because `indent-point' is past it. In this case
835 ;; look further back up for another `perl-beginning-of-function'.
836 (while (and (looking-at "{")
837 (save-excursion
838 (beginning-of-line)
839 (looking-at "\\s-+sub\\>"))
840 (> indent-point (save-excursion
841 (condition-case nil
842 (forward-sexp 1)
843 (scan-error nil))
844 (point))))
845 (perl-beginning-of-function))
846 (while (< (point) indent-point) ;repeat until right sexp
847 (setq state (parse-partial-sexp (point) indent-point 0))
848 ;; state = (depth_in_parens innermost_containing_list
849 ;; last_complete_sexp string_terminator_or_nil inside_commentp
850 ;; following_quotep minimum_paren-depth_this_scan)
851 ;; Parsing stops if depth in parentheses becomes equal to third arg.
852 (setq containing-sexp (nth 1 state)))
853 (cond ((nth 3 state) 'noindent) ; In a quoted string?
854 ((null containing-sexp) ; Line is at top level.
855 (skip-chars-forward " \t\f")
856 (if (= (following-char) ?{)
857 0 ; move to beginning of line if it starts a function body
858 ;; indent a little if this is a continuation line
859 (perl-backward-to-noncomment)
860 (if (or (bobp)
861 (memq (preceding-char) '(?\; ?\})))
862 0 perl-continued-statement-offset)))
863 ((/= (char-after containing-sexp) ?{)
864 ;; line is expression, not statement:
865 ;; indent to just after the surrounding open.
866 (goto-char (1+ containing-sexp))
867 (if (perl-hanging-paren-p)
868 ;; We're indenting an arg of a call like:
869 ;; $a = foobarlongnamefun (
870 ;; arg1
871 ;; arg2
872 ;; );
873 (progn
874 (skip-syntax-backward "(")
875 (condition-case nil
876 (while (save-excursion
877 (skip-syntax-backward " ") (not (bolp)))
878 (forward-sexp -1))
879 (scan-error nil))
880 (+ (current-column) perl-indent-level))
881 (if perl-indent-continued-arguments
882 (+ perl-indent-continued-arguments (current-indentation))
883 (skip-chars-forward " \t")
884 (current-column))))
885 (t
886 ;; Statement level. Is it a continuation or a new statement?
887 (if (perl-continuation-line-p containing-sexp)
888 ;; This line is continuation of preceding line's statement;
889 ;; indent perl-continued-statement-offset more than the
890 ;; previous line of the statement.
891 (progn
892 (perl-backward-to-start-of-continued-exp containing-sexp)
893 (+ (if (save-excursion
894 (perl-continuation-line-p containing-sexp))
895 ;; If the continued line is itself a continuation
896 ;; line, then align, otherwise add an offset.
897 0 perl-continued-statement-offset)
898 (current-column)
899 (if (save-excursion (goto-char indent-point)
900 (looking-at "[ \t]*{"))
901 perl-continued-brace-offset 0)))
902 ;; This line starts a new statement.
903 ;; Position at last unclosed open.
904 (goto-char containing-sexp)
905 (or
906 ;; Is line first statement after an open-brace?
907 ;; If no, find that first statement and indent like it.
908 (save-excursion
909 (forward-char 1)
910 ;; Skip over comments and labels following openbrace.
911 (while (progn
912 (skip-chars-forward " \t\f\n")
913 (cond ((looking-at ";?#")
914 (forward-line 1) t)
915 ((looking-at "\\(\\w\\|\\s_\\)+:[^:]")
916 (setq colon-line-end (line-end-position))
917 (search-forward ":")))))
918 ;; The first following code counts
919 ;; if it is before the line we want to indent.
920 (and (< (point) indent-point)
921 (if (> colon-line-end (point))
922 (- (current-indentation) perl-label-offset)
923 (current-column))))
924 ;; If no previous statement,
925 ;; indent it relative to line brace is on.
926 ;; For open paren in column zero, don't let statement
927 ;; start there too. If perl-indent-level is zero,
928 ;; use perl-brace-offset + perl-continued-statement-offset
929 ;; For open-braces not the first thing in a line,
930 ;; add in perl-brace-imaginary-offset.
931 (+ (if (and (bolp) (zerop perl-indent-level))
932 (+ perl-brace-offset perl-continued-statement-offset)
933 perl-indent-level)
934 ;; Move back over whitespace before the openbrace.
935 ;; If openbrace is not first nonwhite thing on the line,
936 ;; add the perl-brace-imaginary-offset.
937 (progn (skip-chars-backward " \t")
938 (if (bolp) 0 perl-brace-imaginary-offset))
939 ;; If the openbrace is preceded by a parenthesized exp,
940 ;; move to the beginning of that;
941 ;; possibly a different line
942 (progn
943 (if (eq (preceding-char) ?\))
944 (forward-sexp -1))
945 ;; Get initial indentation of the line we are on.
946 (current-indentation))))))))))
947
948 (defun perl-backward-to-noncomment ()
949 "Move point backward to after the first non-white-space, skipping comments."
950 (interactive)
951 (forward-comment (- (point-max))))
952
953 (defun perl-backward-to-start-of-continued-exp (lim)
954 (if (= (preceding-char) ?\))
955 (forward-sexp -1))
956 (beginning-of-line)
957 (if (<= (point) lim)
958 (goto-char (1+ lim)))
959 (skip-chars-forward " \t\f"))
960 \f
961 ;; note: this may be slower than the c-mode version, but I can understand it.
962 (defalias 'indent-perl-exp 'perl-indent-exp)
963 (defun perl-indent-exp ()
964 "Indent each line of the Perl grouping following point."
965 (interactive)
966 (let* ((case-fold-search nil)
967 (oldpnt (point-marker))
968 (bof-mark (save-excursion
969 (end-of-line 2)
970 (perl-beginning-of-function)
971 (point-marker)))
972 eol last-mark lsexp-mark delta)
973 (if (= (char-after (marker-position bof-mark)) ?=)
974 (message "Can't indent a format statement")
975 (message "Indenting Perl expression...")
976 (setq eol (line-end-position))
977 (save-excursion ; locate matching close paren
978 (while (and (not (eobp)) (<= (point) eol))
979 (parse-partial-sexp (point) (point-max) 0))
980 (setq last-mark (point-marker)))
981 (setq lsexp-mark bof-mark)
982 (beginning-of-line)
983 (while (< (point) (marker-position last-mark))
984 (setq delta (perl-indent-line nil (marker-position bof-mark)))
985 (if (numberp delta) ; unquoted start-of-line?
986 (progn
987 (if (eolp)
988 (delete-horizontal-space))
989 (setq lsexp-mark (point-marker))))
990 (end-of-line)
991 (setq eol (point))
992 (if (nth 4 (parse-partial-sexp (marker-position lsexp-mark) eol))
993 (progn ; line ends in a comment
994 (beginning-of-line)
995 (if (or (not (looking-at "\\s-*;?#"))
996 (listp delta)
997 (and (/= 0 delta)
998 (= (- (current-indentation) delta) comment-column)))
999 (if (and comment-start-skip
1000 (re-search-forward comment-start-skip eol t))
1001 (indent-for-comment))))) ; indent existing comment
1002 (forward-line 1))
1003 (goto-char (marker-position oldpnt))
1004 (message "Indenting Perl expression...done"))))
1005 \f
1006 (defun perl-beginning-of-function (&optional arg)
1007 "Move backward to next beginning-of-function, or as far as possible.
1008 With argument, repeat that many times; negative args move forward.
1009 Returns new value of point in all cases."
1010 (interactive "p")
1011 (or arg (setq arg 1))
1012 (if (< arg 0) (forward-char 1))
1013 (and (/= arg 0)
1014 (re-search-backward
1015 "^\\s(\\|^\\s-*sub\\b[ \t\n]*\\_<[^{]+{\\|^\\s-*format\\b[^=]*=\\|^\\."
1016 nil 'move arg)
1017 (goto-char (1- (match-end 0))))
1018 (point))
1019
1020 ;; note: this routine is adapted directly from emacs lisp.el, end-of-defun;
1021 ;; no bugs have been removed :-)
1022 (defun perl-end-of-function (&optional arg)
1023 "Move forward to next end-of-function.
1024 The end of a function is found by moving forward from the beginning of one.
1025 With argument, repeat that many times; negative args move backward."
1026 (interactive "p")
1027 (or arg (setq arg 1))
1028 (let ((first t))
1029 (while (and (> arg 0) (< (point) (point-max)))
1030 (let ((pos (point)))
1031 (while (progn
1032 (if (and first
1033 (progn
1034 (forward-char 1)
1035 (perl-beginning-of-function 1)
1036 (not (bobp))))
1037 nil
1038 (or (bobp) (forward-char -1))
1039 (perl-beginning-of-function -1))
1040 (setq first nil)
1041 (forward-list 1)
1042 (skip-chars-forward " \t")
1043 (if (looking-at "[#\n]")
1044 (forward-line 1))
1045 (<= (point) pos))))
1046 (setq arg (1- arg)))
1047 (while (< arg 0)
1048 (let ((pos (point)))
1049 (perl-beginning-of-function 1)
1050 (forward-sexp 1)
1051 (forward-line 1)
1052 (if (>= (point) pos)
1053 (if (progn (perl-beginning-of-function 2) (not (bobp)))
1054 (progn
1055 (forward-list 1)
1056 (skip-chars-forward " \t")
1057 (if (looking-at "[#\n]")
1058 (forward-line 1)))
1059 (goto-char (point-min)))))
1060 (setq arg (1+ arg)))))
1061
1062 (defalias 'mark-perl-function 'perl-mark-function)
1063 (defun perl-mark-function ()
1064 "Put mark at end of Perl function, point at beginning."
1065 (interactive)
1066 (push-mark (point))
1067 (perl-end-of-function)
1068 (push-mark (point))
1069 (perl-beginning-of-function)
1070 (backward-paragraph))
1071
1072 (provide 'perl-mode)
1073
1074 ;;; perl-mode.el ends here