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