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