Merge from emacs-23; up to 2010-06-11T21:26:13Z!lekktu@gmail.com.
[emacs.git] / lisp / progmodes / perl-mode.el
blob8ca8c690f926a91ebee28a88d7a50390f97a843d
1 ;;; perl-mode.el --- Perl code editing commands for GNU Emacs
3 ;; Copyright (C) 1990, 1994, 2001-2011 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 .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.
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:
105 (eval-when-compile (require 'cl))
107 (defvar font-lock-comment-face)
108 (defvar font-lock-doc-face)
109 (defvar font-lock-string-face)
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)
117 (defvar perl-mode-abbrev-table nil
118 "Abbrev table in use in perl-mode buffers.")
119 (define-abbrev-table 'perl-mode-abbrev-table ())
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.")
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."
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)
163 "Syntax table in use in `perl-mode' buffers.")
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'.")
174 ;; Regexps updated with help from Tom Tromey <tromey@cambric.colorado.edu> and
175 ;; Jim Campbell <jec@murzim.ca.boeing.com>.
177 (defconst perl-font-lock-keywords-1
178 '(;; What is this for?
179 ;;("\\(--- .* ---\\|=== .* ===\\)" . font-lock-string-face)
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))
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.")
198 (defconst perl-font-lock-keywords-2
199 (append perl-font-lock-keywords-1
200 (list
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 "\\>")
209 ;; Fontify local and my keywords as types.
210 '("\\<\\(local\\|my\\)\\>" . font-lock-type-face)
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)
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.")
227 (defvar perl-font-lock-keywords perl-font-lock-keywords-1
228 "Default expressions to highlight in Perl mode.")
230 (defvar perl-quote-like-pairs
231 '((?\( . ?\)) (?\[ . ?\]) (?\{ . ?\}) (?\< . ?\>)))
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 /.../.../
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]\\)"
308 ;; Nasty cases:
309 ;; /foo/m $a->m $#m $m @m %m
310 ;; \s (appears often in regexps).
311 ;; -s file
312 ;; sub tr {...}
313 (3 (ignore
314 (if (save-excursion (goto-char (match-beginning 0))
315 (forward-word -1)
316 (looking-at-p "sub[ \t\n]"))
317 ;; This is defining a function.
319 (put-text-property (match-beginning 3) (match-end 3)
320 'syntax-table
321 (if (assoc (char-after (match-beginning 3))
322 perl-quote-like-pairs)
323 (string-to-syntax "|")
324 (string-to-syntax "\"")))
325 (perl-syntax-propertize-special-constructs end))))))
326 (point) end)))
328 (defvar perl-empty-syntax-table
329 (let ((st (copy-syntax-table)))
330 ;; Make all chars be of punctuation syntax.
331 (dotimes (i 256) (aset st i '(1)))
332 (modify-syntax-entry ?\\ "\\" st)
334 "Syntax table used internally for processing quote-like operators.")
336 (defun perl-quote-syntax-table (char)
337 (let ((close (cdr (assq char perl-quote-like-pairs)))
338 (st (copy-syntax-table perl-empty-syntax-table)))
339 (if (not close)
340 (modify-syntax-entry char "\"" st)
341 (modify-syntax-entry char "(" st)
342 (modify-syntax-entry close ")" st))
343 st))
345 (defun perl-syntax-propertize-special-constructs (limit)
346 "Propertize special constructs like regexps and formats."
347 (let ((state (syntax-ppss))
348 char)
349 (cond
350 ((or (null (setq char (nth 3 state)))
351 (and (characterp char) (eq (char-syntax (nth 3 state)) ?\")))
352 ;; Normal text, or comment, or docstring, or normal string.
353 nil)
354 ((eq (nth 3 state) ?\n)
355 ;; A `format' command.
356 (when (re-search-forward "^\\s *\\.\\s *\n" limit 'move)
357 (put-text-property (1- (point)) (point)
358 'syntax-table (string-to-syntax "\""))))
360 ;; This is regexp like quote thingy.
361 (setq char (char-after (nth 8 state)))
362 (let ((startpos (point))
363 (twoargs (save-excursion
364 (goto-char (nth 8 state))
365 (skip-syntax-backward " ")
366 (skip-syntax-backward "w")
367 (member (buffer-substring
368 (point) (progn (forward-word 1) (point)))
369 '("tr" "s" "y"))))
370 (close (cdr (assq char perl-quote-like-pairs)))
371 (st (perl-quote-syntax-table char)))
372 (when (with-syntax-table st
373 (if close
374 ;; For paired delimiters, Perl allows nesting them, but
375 ;; since we treat them as strings, Emacs does not count
376 ;; those delimiters in `state', so we don't know how deep
377 ;; we are: we have to go back to the beginning of this
378 ;; "string" and count from there.
379 (condition-case nil
380 (progn
381 ;; Start after the first char since it doesn't have
382 ;; paren-syntax (an alternative would be to let-bind
383 ;; parse-sexp-lookup-properties).
384 (goto-char (1+ (nth 8 state)))
385 (up-list 1)
387 ;; In case of error, make sure we don't move backward.
388 (scan-error (goto-char startpos) nil))
389 (not (or (nth 8 (parse-partial-sexp
390 (point) limit nil nil state 'syntax-table))
391 ;; If we have a self-paired opener and a twoargs
392 ;; command, the form is s/../../ so we have to skip
393 ;; a second time.
394 ;; In the case of s{...}{...}, we only handle the
395 ;; first part here and the next below.
396 (when (and twoargs (not close))
397 (nth 8 (parse-partial-sexp
398 (point) limit
399 nil nil state 'syntax-table)))))))
400 ;; Point is now right after the arg(s).
401 (when (eq (char-before (1- (point))) ?$)
402 (put-text-property (- (point) 2) (1- (point))
403 'syntax-table '(1)))
404 (put-text-property (1- (point)) (point)
405 'syntax-table
406 (if close
407 (string-to-syntax "|")
408 (string-to-syntax "\"")))
409 ;; If we have two args with a non-self-paired starter (e.g.
410 ;; s{...}{...}) we're right after the first arg, so we still have to
411 ;; handle the second part.
412 (when (and twoargs close)
413 ;; Skip whitespace and make sure that font-lock will
414 ;; refontify the second part in the proper context.
415 (put-text-property
416 (point) (progn (forward-comment (point-max)) (point))
417 'syntax-multiline t)
419 (when (< (point) limit)
420 (put-text-property (point) (1+ (point))
421 'syntax-table
422 (if (assoc (char-after)
423 perl-quote-like-pairs)
424 ;; Put an `e' in the cdr to mark this
425 ;; char as "second arg starter".
426 (string-to-syntax "|e")
427 (string-to-syntax "\"e")))
428 (forward-char 1)
429 ;; Re-use perl-syntax-propertize-special-constructs to handle the
430 ;; second part (the first delimiter of second part can't be
431 ;; preceded by "s" or "tr" or "y", so it will not be considered
432 ;; as twoarg).
433 (perl-syntax-propertize-special-constructs limit)))))))))
435 (defun perl-font-lock-syntactic-face-function (state)
436 (cond
437 ((and (nth 3 state)
438 (eq ?e (cdr-safe (get-text-property (nth 8 state) 'syntax-table)))
439 ;; This is a second-arg of s{..}{...} form; let's check if this second
440 ;; arg is executable code rather than a string. For that, we need to
441 ;; look for an "e" after this second arg, so we have to hunt for the
442 ;; end of the arg. Depending on whether the whole arg has already
443 ;; been syntax-propertized or not, the end-char will have different
444 ;; syntaxes, so let's ignore syntax-properties temporarily so we can
445 ;; pretend it has not been syntax-propertized yet.
446 (let* ((parse-sexp-lookup-properties nil)
447 (char (char-after (nth 8 state)))
448 (paired (assq char perl-quote-like-pairs)))
449 (with-syntax-table (perl-quote-syntax-table char)
450 (save-excursion
451 (if (not paired)
452 (parse-partial-sexp (point) (point-max)
453 nil nil state 'syntax-table)
454 (condition-case nil
455 (progn
456 (goto-char (1+ (nth 8 state)))
457 (up-list 1))
458 (scan-error (goto-char (point-max)))))
459 (put-text-property (nth 8 state) (point)
460 'jit-lock-defer-multiline t)
461 (looking-at "[ \t]*\\sw*e")))))
462 nil)
463 (t (funcall (default-value 'font-lock-syntactic-face-function) state))))
465 (defcustom perl-indent-level 4
466 "*Indentation of Perl statements with respect to containing block."
467 :type 'integer
468 :group 'perl)
470 ;; Is is not unusual to put both things like perl-indent-level and
471 ;; cperl-indent-level in the local variable section of a file. If only
472 ;; one of perl-mode and cperl-mode is in use, a warning will be issued
473 ;; about the variable. Autoload these here, so that no warning is
474 ;; issued when using either perl-mode or cperl-mode.
475 ;;;###autoload(put 'perl-indent-level 'safe-local-variable 'integerp)
476 ;;;###autoload(put 'perl-continued-statement-offset 'safe-local-variable 'integerp)
477 ;;;###autoload(put 'perl-continued-brace-offset 'safe-local-variable 'integerp)
478 ;;;###autoload(put 'perl-brace-offset 'safe-local-variable 'integerp)
479 ;;;###autoload(put 'perl-brace-imaginary-offset 'safe-local-variable 'integerp)
480 ;;;###autoload(put 'perl-label-offset 'safe-local-variable 'integerp)
482 (defcustom perl-continued-statement-offset 4
483 "*Extra indent for lines not starting new statements."
484 :type 'integer
485 :group 'perl)
486 (defcustom perl-continued-brace-offset -4
487 "*Extra indent for substatements that start with open-braces.
488 This is in addition to `perl-continued-statement-offset'."
489 :type 'integer
490 :group 'perl)
491 (defcustom perl-brace-offset 0
492 "*Extra indentation for braces, compared with other text in same context."
493 :type 'integer
494 :group 'perl)
495 (defcustom perl-brace-imaginary-offset 0
496 "*Imagined indentation of an open brace that actually follows a statement."
497 :type 'integer
498 :group 'perl)
499 (defcustom perl-label-offset -2
500 "*Offset of Perl label lines relative to usual indentation."
501 :type 'integer
502 :group 'perl)
503 (defcustom perl-indent-continued-arguments nil
504 "*If non-nil offset of argument lines relative to usual indentation.
505 If nil, continued arguments are aligned with the first argument."
506 :type '(choice integer (const nil))
507 :group 'perl)
509 (defcustom perl-tab-always-indent tab-always-indent
510 "Non-nil means TAB in Perl mode always indents the current line.
511 Otherwise it inserts a tab character if you type it past the first
512 nonwhite character on the line."
513 :type 'boolean
514 :group 'perl)
516 ;; I changed the default to nil for consistency with general Emacs
517 ;; conventions -- rms.
518 (defcustom perl-tab-to-comment nil
519 "*Non-nil means TAB moves to eol or makes a comment in some cases.
520 For lines which don't need indenting, TAB either indents an
521 existing comment, moves to end-of-line, or if at end-of-line already,
522 create a new comment."
523 :type 'boolean
524 :group 'perl)
526 (defcustom perl-nochange ";?#\\|\f\\|\\s(\\|\\(\\w\\|\\s_\\)+:[^:]"
527 "*Lines starting with this regular expression are not auto-indented."
528 :type 'regexp
529 :group 'perl)
531 ;; Outline support
533 (defvar perl-outline-regexp
534 (concat (mapconcat 'cadr perl-imenu-generic-expression "\\|")
535 "\\|^=cut\\>"))
537 (defun perl-outline-level ()
538 (cond
539 ((looking-at "package\\s-") 0)
540 ((looking-at "sub\\s-") 1)
541 ((looking-at "=head[0-9]") (- (char-before (match-end 0)) ?0))
542 ((looking-at "=cut") 1)
543 (t 3)))
545 (defvar perl-mode-hook nil
546 "Normal hook to run when entering Perl mode.")
548 ;;;###autoload
549 (define-derived-mode perl-mode prog-mode "Perl"
550 "Major mode for editing Perl code.
551 Expression and list commands understand all Perl brackets.
552 Tab indents for Perl code.
553 Comments are delimited with # ... \\n.
554 Paragraphs are separated by blank lines only.
555 Delete converts tabs to spaces as it moves back.
556 \\{perl-mode-map}
557 Variables controlling indentation style:
558 `perl-tab-always-indent'
559 Non-nil means TAB in Perl mode should always indent the current line,
560 regardless of where in the line point is when the TAB command is used.
561 `perl-tab-to-comment'
562 Non-nil means that for lines which don't need indenting, TAB will
563 either delete an empty comment, indent an existing comment, move
564 to end-of-line, or if at end-of-line already, create a new comment.
565 `perl-nochange'
566 Lines starting with this regular expression are not auto-indented.
567 `perl-indent-level'
568 Indentation of Perl statements within surrounding block.
569 The surrounding block's indentation is the indentation
570 of the line on which the open-brace appears.
571 `perl-continued-statement-offset'
572 Extra indentation given to a substatement, such as the
573 then-clause of an if or body of a while.
574 `perl-continued-brace-offset'
575 Extra indentation given to a brace that starts a substatement.
576 This is in addition to `perl-continued-statement-offset'.
577 `perl-brace-offset'
578 Extra indentation for line if it starts with an open brace.
579 `perl-brace-imaginary-offset'
580 An open brace following other text is treated as if it were
581 this far to the right of the start of its line.
582 `perl-label-offset'
583 Extra indentation for line that is a label.
584 `perl-indent-continued-arguments'
585 Offset of argument lines relative to usual indentation.
587 Various indentation styles: K&R BSD BLK GNU LW
588 perl-indent-level 5 8 0 2 4
589 perl-continued-statement-offset 5 8 4 2 4
590 perl-continued-brace-offset 0 0 0 0 -4
591 perl-brace-offset -5 -8 0 0 0
592 perl-brace-imaginary-offset 0 0 4 0 0
593 perl-label-offset -5 -8 -2 -2 -2
595 Turning on Perl mode runs the normal hook `perl-mode-hook'."
596 :abbrev-table perl-mode-abbrev-table
597 (set (make-local-variable 'paragraph-start) (concat "$\\|" page-delimiter))
598 (set (make-local-variable 'paragraph-separate) paragraph-start)
599 (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
600 (set (make-local-variable 'indent-line-function) #'perl-indent-line)
601 (set (make-local-variable 'comment-start) "# ")
602 (set (make-local-variable 'comment-end) "")
603 (set (make-local-variable 'comment-start-skip) "\\(^\\|\\s-\\);?#+ *")
604 (set (make-local-variable 'comment-indent-function) #'perl-comment-indent)
605 (set (make-local-variable 'parse-sexp-ignore-comments) t)
606 ;; Tell font-lock.el how to handle Perl.
607 (setq font-lock-defaults '((perl-font-lock-keywords
608 perl-font-lock-keywords-1
609 perl-font-lock-keywords-2)
610 nil nil ((?\_ . "w")) nil
611 (font-lock-syntactic-face-function
612 . perl-font-lock-syntactic-face-function)))
613 (set (make-local-variable 'syntax-propertize-function)
614 #'perl-syntax-propertize-function)
615 (add-hook 'syntax-propertize-extend-region-functions
616 #'syntax-propertize-multiline 'append 'local)
617 ;; Tell imenu how to handle Perl.
618 (set (make-local-variable 'imenu-generic-expression)
619 perl-imenu-generic-expression)
620 (setq imenu-case-fold-search nil)
621 ;; Setup outline-minor-mode.
622 (set (make-local-variable 'outline-regexp) perl-outline-regexp)
623 (set (make-local-variable 'outline-level) 'perl-outline-level))
625 ;; This is used by indent-for-comment
626 ;; to decide how much to indent a comment in Perl code
627 ;; based on its context.
628 (defun perl-comment-indent ()
629 (if (and (bolp) (not (eolp)))
630 0 ;Existing comment at bol stays there.
631 comment-column))
633 (defalias 'electric-perl-terminator 'perl-electric-terminator)
634 (defun perl-electric-terminator (arg)
635 "Insert character and adjust indentation.
636 If at end-of-line, and not in a comment or a quote, correct the's indentation."
637 (interactive "P")
638 (let ((insertpos (point)))
639 (and (not arg) ; decide whether to indent
640 (eolp)
641 (save-excursion
642 (beginning-of-line)
643 (and (not ; eliminate comments quickly
644 (and comment-start-skip
645 (re-search-forward comment-start-skip insertpos t)) )
646 (or (/= last-command-event ?:)
647 ;; Colon is special only after a label ....
648 (looking-at "\\s-*\\(\\w\\|\\s_\\)+$"))
649 (let ((pps (parse-partial-sexp
650 (perl-beginning-of-function) insertpos)))
651 (not (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))
652 (progn ; must insert, indent, delete
653 (insert-char last-command-event 1)
654 (perl-indent-line)
655 (delete-char -1))))
656 (self-insert-command (prefix-numeric-value arg)))
658 ;; not used anymore, but may be useful someday:
659 ;;(defun perl-inside-parens-p ()
660 ;; (condition-case ()
661 ;; (save-excursion
662 ;; (save-restriction
663 ;; (narrow-to-region (point)
664 ;; (perl-beginning-of-function))
665 ;; (goto-char (point-max))
666 ;; (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
667 ;; (error nil)))
669 (defun perl-indent-command (&optional arg)
670 "Indent Perl code in the active region or current line.
671 In Transient Mark mode, when the region is active, reindent the region.
672 Otherwise, with a prefix argument, reindent the current line
673 unconditionally.
675 Otherwise, if `perl-tab-always-indent' is nil and point is not in
676 the indentation area at the beginning of the line, insert a tab.
678 Otherwise, indent the current line. If point was within the
679 indentation area, it is moved to the end of the indentation area.
680 If the line was already indented properly and point was not
681 within the indentation area, and if `perl-tab-to-comment' is
682 non-nil (the default), then do the first possible action from the
683 following list:
685 1) delete an empty comment
686 2) move forward to start of comment, indenting if necessary
687 3) move forward to end of line
688 4) create an empty comment
689 5) move backward to start of comment, indenting if necessary."
690 (interactive "P")
691 (cond ((use-region-p) ; indent the active region
692 (indent-region (region-beginning) (region-end)))
693 (arg
694 (perl-indent-line "\f")) ; just indent this line
695 ((and (not perl-tab-always-indent)
696 (> (current-column) (current-indentation)))
697 (insert-tab))
699 (let* ((oldpnt (point))
700 (lsexp (progn (beginning-of-line) (point)))
701 (bof (perl-beginning-of-function))
702 (delta (progn
703 (goto-char oldpnt)
704 (perl-indent-line "\f\\|;?#" bof))))
705 (and perl-tab-to-comment
706 (= oldpnt (point)) ; done if point moved
707 (if (listp delta) ; if line starts in a quoted string
708 (setq lsexp (or (nth 2 delta) bof))
709 (= delta 0)) ; done if indenting occurred
710 (let ((eol (progn (end-of-line) (point)))
711 state)
712 (cond ((= (char-after bof) ?=)
713 (if (= oldpnt eol)
714 (message "In a format statement")))
715 ((progn (setq state (parse-partial-sexp lsexp eol))
716 (nth 3 state))
717 (if (= oldpnt eol) ; already at eol in a string
718 (message "In a string which starts with a %c."
719 (nth 3 state))))
720 ((not (nth 4 state))
721 (if (= oldpnt eol) ; no comment, create one?
722 (indent-for-comment)))
723 ((progn (beginning-of-line)
724 (and comment-start-skip
725 (re-search-forward
726 comment-start-skip eol 'move)))
727 (if (eolp)
728 (progn ; delete existing comment
729 (goto-char (match-beginning 0))
730 (skip-chars-backward " \t")
731 (delete-region (point) eol))
732 (if (or (< oldpnt (point)) (= oldpnt eol))
733 (indent-for-comment) ; indent existing comment
734 (end-of-line))))
735 ((/= oldpnt eol)
736 (end-of-line))
738 (message "Use backslash to quote # characters.")
739 (ding t)))))))))
741 (defun perl-indent-line (&optional nochange parse-start)
742 "Indent current line as Perl code.
743 Return the amount the indentation
744 changed by, or (parse-state) if line starts in a quoted string."
745 (let ((case-fold-search nil)
746 (pos (- (point-max) (point)))
747 (bof (or parse-start (save-excursion (perl-beginning-of-function))))
748 beg indent shift-amt)
749 (beginning-of-line)
750 (setq beg (point))
751 (setq shift-amt
752 (cond ((eq (char-after bof) ?=) 0)
753 ((listp (setq indent (perl-calculate-indent bof))) indent)
754 ((looking-at (or nochange perl-nochange)) 0)
756 (skip-chars-forward " \t\f")
757 (setq indent (perl-indent-new-calculate nil indent bof))
758 (- indent (current-column)))))
759 (skip-chars-forward " \t\f")
760 (if (and (numberp shift-amt) (/= 0 shift-amt))
761 (progn (delete-region beg (point))
762 (indent-to indent)))
763 ;; If initial point was within line's indentation,
764 ;; position after the indentation. Else stay at same point in text.
765 (if (> (- (point-max) pos) (point))
766 (goto-char (- (point-max) pos)))
767 shift-amt))
769 (defun perl-continuation-line-p (limit)
770 "Move to end of previous line and return non-nil if continued."
771 ;; Statement level. Is it a continuation or a new statement?
772 ;; Find previous non-comment character.
773 (perl-backward-to-noncomment)
774 ;; Back up over label lines, since they don't
775 ;; affect whether our line is a continuation.
776 (while (or (eq (preceding-char) ?\,)
777 (and (eq (preceding-char) ?:)
778 (memq (char-syntax (char-after (- (point) 2)))
779 '(?w ?_))))
780 (if (eq (preceding-char) ?\,)
781 (perl-backward-to-start-of-continued-exp limit)
782 (beginning-of-line))
783 (perl-backward-to-noncomment))
784 ;; Now we get the answer.
785 (not (memq (preceding-char) '(?\; ?\} ?\{))))
787 (defun perl-hanging-paren-p ()
788 "Non-nil if we are right after a hanging parenthesis-like char."
789 (and (looking-at "[ \t]*$")
790 (save-excursion
791 (skip-syntax-backward " (") (not (bolp)))))
793 (defun perl-indent-new-calculate (&optional virtual default parse-start)
795 (and virtual (save-excursion (skip-chars-backward " \t") (bolp))
796 (current-column))
797 (and (looking-at "\\(\\w\\|\\s_\\)+:[^:]")
798 (max 1 (+ (or default (perl-calculate-indent parse-start))
799 perl-label-offset)))
800 (and (= (char-syntax (following-char)) ?\))
801 (save-excursion
802 (forward-char 1)
803 (forward-sexp -1)
804 (perl-indent-new-calculate
805 ;; Recalculate the parsing-start, since we may have jumped
806 ;; dangerously close (typically in the case of nested functions).
807 'virtual nil (save-excursion (perl-beginning-of-function)))))
808 (and (and (= (following-char) ?{)
809 (save-excursion (forward-char) (perl-hanging-paren-p)))
810 (+ (or default (perl-calculate-indent parse-start))
811 perl-brace-offset))
812 (or default (perl-calculate-indent parse-start))))
814 (defun perl-calculate-indent (&optional parse-start)
815 "Return appropriate indentation for current line as Perl code.
816 In usual case returns an integer: the column to indent to.
817 Returns (parse-state) if line starts inside a string.
818 Optional argument PARSE-START should be the position of `beginning-of-defun'."
819 (save-excursion
820 (let ((indent-point (point))
821 (case-fold-search nil)
822 (colon-line-end 0)
823 state containing-sexp)
824 (if parse-start ;used to avoid searching
825 (goto-char parse-start)
826 (perl-beginning-of-function))
827 ;; We might be now looking at a local function that has nothing to
828 ;; do with us because `indent-point' is past it. In this case
829 ;; look further back up for another `perl-beginning-of-function'.
830 (while (and (looking-at "{")
831 (save-excursion
832 (beginning-of-line)
833 (looking-at "\\s-+sub\\>"))
834 (> indent-point (save-excursion (forward-sexp 1) (point))))
835 (perl-beginning-of-function))
836 (while (< (point) indent-point) ;repeat until right sexp
837 (setq state (parse-partial-sexp (point) indent-point 0))
838 ;; state = (depth_in_parens innermost_containing_list
839 ;; last_complete_sexp string_terminator_or_nil inside_commentp
840 ;; following_quotep minimum_paren-depth_this_scan)
841 ;; Parsing stops if depth in parentheses becomes equal to third arg.
842 (setq containing-sexp (nth 1 state)))
843 (cond ((nth 3 state) state) ; In a quoted string?
844 ((null containing-sexp) ; Line is at top level.
845 (skip-chars-forward " \t\f")
846 (if (= (following-char) ?{)
847 0 ; move to beginning of line if it starts a function body
848 ;; indent a little if this is a continuation line
849 (perl-backward-to-noncomment)
850 (if (or (bobp)
851 (memq (preceding-char) '(?\; ?\})))
852 0 perl-continued-statement-offset)))
853 ((/= (char-after containing-sexp) ?{)
854 ;; line is expression, not statement:
855 ;; indent to just after the surrounding open.
856 (goto-char (1+ containing-sexp))
857 (if (perl-hanging-paren-p)
858 ;; We're indenting an arg of a call like:
859 ;; $a = foobarlongnamefun (
860 ;; arg1
861 ;; arg2
862 ;; );
863 (progn
864 (skip-syntax-backward "(")
865 (condition-case nil
866 (while (save-excursion
867 (skip-syntax-backward " ") (not (bolp)))
868 (forward-sexp -1))
869 (scan-error nil))
870 (+ (current-column) perl-indent-level))
871 (if perl-indent-continued-arguments
872 (+ perl-indent-continued-arguments (current-indentation))
873 (skip-chars-forward " \t")
874 (current-column))))
876 ;; Statement level. Is it a continuation or a new statement?
877 (if (perl-continuation-line-p containing-sexp)
878 ;; This line is continuation of preceding line's statement;
879 ;; indent perl-continued-statement-offset more than the
880 ;; previous line of the statement.
881 (progn
882 (perl-backward-to-start-of-continued-exp containing-sexp)
883 (+ (if (save-excursion
884 (perl-continuation-line-p containing-sexp))
885 ;; If the continued line is itself a continuation
886 ;; line, then align, otherwise add an offset.
887 0 perl-continued-statement-offset)
888 (current-column)
889 (if (save-excursion (goto-char indent-point)
890 (looking-at "[ \t]*{"))
891 perl-continued-brace-offset 0)))
892 ;; This line starts a new statement.
893 ;; Position at last unclosed open.
894 (goto-char containing-sexp)
896 ;; Is line first statement after an open-brace?
897 ;; If no, find that first statement and indent like it.
898 (save-excursion
899 (forward-char 1)
900 ;; Skip over comments and labels following openbrace.
901 (while (progn
902 (skip-chars-forward " \t\f\n")
903 (cond ((looking-at ";?#")
904 (forward-line 1) t)
905 ((looking-at "\\(\\w\\|\\s_\\)+:[^:]")
906 (setq colon-line-end (line-end-position))
907 (search-forward ":")))))
908 ;; The first following code counts
909 ;; if it is before the line we want to indent.
910 (and (< (point) indent-point)
911 (if (> colon-line-end (point))
912 (- (current-indentation) perl-label-offset)
913 (current-column))))
914 ;; If no previous statement,
915 ;; indent it relative to line brace is on.
916 ;; For open paren in column zero, don't let statement
917 ;; start there too. If perl-indent-level is zero,
918 ;; use perl-brace-offset + perl-continued-statement-offset
919 ;; For open-braces not the first thing in a line,
920 ;; add in perl-brace-imaginary-offset.
921 (+ (if (and (bolp) (zerop perl-indent-level))
922 (+ perl-brace-offset perl-continued-statement-offset)
923 perl-indent-level)
924 ;; Move back over whitespace before the openbrace.
925 ;; If openbrace is not first nonwhite thing on the line,
926 ;; add the perl-brace-imaginary-offset.
927 (progn (skip-chars-backward " \t")
928 (if (bolp) 0 perl-brace-imaginary-offset))
929 ;; If the openbrace is preceded by a parenthesized exp,
930 ;; move to the beginning of that;
931 ;; possibly a different line
932 (progn
933 (if (eq (preceding-char) ?\))
934 (forward-sexp -1))
935 ;; Get initial indentation of the line we are on.
936 (current-indentation))))))))))
938 (defun perl-backward-to-noncomment ()
939 "Move point backward to after the first non-white-space, skipping comments."
940 (interactive)
941 (forward-comment (- (point-max))))
943 (defun perl-backward-to-start-of-continued-exp (lim)
944 (if (= (preceding-char) ?\))
945 (forward-sexp -1))
946 (beginning-of-line)
947 (if (<= (point) lim)
948 (goto-char (1+ lim)))
949 (skip-chars-forward " \t\f"))
951 ;; note: this may be slower than the c-mode version, but I can understand it.
952 (defalias 'indent-perl-exp 'perl-indent-exp)
953 (defun perl-indent-exp ()
954 "Indent each line of the Perl grouping following point."
955 (interactive)
956 (let* ((case-fold-search nil)
957 (oldpnt (point-marker))
958 (bof-mark (save-excursion
959 (end-of-line 2)
960 (perl-beginning-of-function)
961 (point-marker)))
962 eol last-mark lsexp-mark delta)
963 (if (= (char-after (marker-position bof-mark)) ?=)
964 (message "Can't indent a format statement")
965 (message "Indenting Perl expression...")
966 (setq eol (line-end-position))
967 (save-excursion ; locate matching close paren
968 (while (and (not (eobp)) (<= (point) eol))
969 (parse-partial-sexp (point) (point-max) 0))
970 (setq last-mark (point-marker)))
971 (setq lsexp-mark bof-mark)
972 (beginning-of-line)
973 (while (< (point) (marker-position last-mark))
974 (setq delta (perl-indent-line nil (marker-position bof-mark)))
975 (if (numberp delta) ; unquoted start-of-line?
976 (progn
977 (if (eolp)
978 (delete-horizontal-space))
979 (setq lsexp-mark (point-marker))))
980 (end-of-line)
981 (setq eol (point))
982 (if (nth 4 (parse-partial-sexp (marker-position lsexp-mark) eol))
983 (progn ; line ends in a comment
984 (beginning-of-line)
985 (if (or (not (looking-at "\\s-*;?#"))
986 (listp delta)
987 (and (/= 0 delta)
988 (= (- (current-indentation) delta) comment-column)))
989 (if (and comment-start-skip
990 (re-search-forward comment-start-skip eol t))
991 (indent-for-comment))))) ; indent existing comment
992 (forward-line 1))
993 (goto-char (marker-position oldpnt))
994 (message "Indenting Perl expression...done"))))
996 (defun perl-beginning-of-function (&optional arg)
997 "Move backward to next beginning-of-function, or as far as possible.
998 With argument, repeat that many times; negative args move forward.
999 Returns new value of point in all cases."
1000 (interactive "p")
1001 (or arg (setq arg 1))
1002 (if (< arg 0) (forward-char 1))
1003 (and (/= arg 0)
1004 (re-search-backward
1005 "^\\s(\\|^\\s-*sub\\b[ \t\n]*\\_<[^{]+{\\|^\\s-*format\\b[^=]*=\\|^\\."
1006 nil 'move arg)
1007 (goto-char (1- (match-end 0))))
1008 (point))
1010 ;; note: this routine is adapted directly from emacs lisp.el, end-of-defun;
1011 ;; no bugs have been removed :-)
1012 (defun perl-end-of-function (&optional arg)
1013 "Move forward to next end-of-function.
1014 The end of a function is found by moving forward from the beginning of one.
1015 With argument, repeat that many times; negative args move backward."
1016 (interactive "p")
1017 (or arg (setq arg 1))
1018 (let ((first t))
1019 (while (and (> arg 0) (< (point) (point-max)))
1020 (let ((pos (point)))
1021 (while (progn
1022 (if (and first
1023 (progn
1024 (forward-char 1)
1025 (perl-beginning-of-function 1)
1026 (not (bobp))))
1028 (or (bobp) (forward-char -1))
1029 (perl-beginning-of-function -1))
1030 (setq first nil)
1031 (forward-list 1)
1032 (skip-chars-forward " \t")
1033 (if (looking-at "[#\n]")
1034 (forward-line 1))
1035 (<= (point) pos))))
1036 (setq arg (1- arg)))
1037 (while (< arg 0)
1038 (let ((pos (point)))
1039 (perl-beginning-of-function 1)
1040 (forward-sexp 1)
1041 (forward-line 1)
1042 (if (>= (point) pos)
1043 (if (progn (perl-beginning-of-function 2) (not (bobp)))
1044 (progn
1045 (forward-list 1)
1046 (skip-chars-forward " \t")
1047 (if (looking-at "[#\n]")
1048 (forward-line 1)))
1049 (goto-char (point-min)))))
1050 (setq arg (1+ arg)))))
1052 (defalias 'mark-perl-function 'perl-mark-function)
1053 (defun perl-mark-function ()
1054 "Put mark at end of Perl function, point at beginning."
1055 (interactive)
1056 (push-mark (point))
1057 (perl-end-of-function)
1058 (push-mark (point))
1059 (perl-beginning-of-function)
1060 (backward-paragraph))
1062 (provide 'perl-mode)
1064 ;;; perl-mode.el ends here