perl-mode.el 42.8 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1 2
;;; perl-mode.el --- Perl code editing commands for GNU Emacs

3
;; Copyright (C) 1990, 1994, 2001-2011  Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
4

Eric S. Raymond's avatar
Eric S. Raymond committed
5
;; Author: William F. Mann
6
;; Maintainer: FSF
Eric S. Raymond's avatar
Eric S. Raymond committed
7
;; Adapted-By: ESR
Eric S. Raymond's avatar
Eric S. Raymond committed
8
;; Keywords: languages
Eric S. Raymond's avatar
Eric S. Raymond committed
9

Jim Blandy's avatar
Jim Blandy committed
10 11 12
;; Adapted from C code editing commands 'c-mode.el', Copyright 1987 by the
;; Free Software Foundation, under terms of its General Public License.

Richard M. Stallman's avatar
Richard M. Stallman committed
13 14
;; This file is part of GNU Emacs.

15
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
16
;; it under the terms of the GNU General Public License as published by
17 18
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
19 20 21 22 23 24 25

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; 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/>.
Jim Blandy's avatar
Jim Blandy committed
27

Eric S. Raymond's avatar
Eric S. Raymond committed
28 29
;;; Commentary:

Jim Blandy's avatar
Jim Blandy committed
30 31 32
;; To enter perl-mode automatically, add (autoload 'perl-mode "perl-mode")
;; to your .emacs file and change the first line of your perl script to:
;; #!/usr/bin/perl --	 # -*-Perl-*-
Karl Heuer's avatar
Karl Heuer committed
33
;; With arguments to perl:
Jim Blandy's avatar
Jim Blandy committed
34 35
;; #!/usr/bin/perl -P-	 # -*-Perl-*-
;; To handle files included with do 'filename.pl';, add something like
Richard M. Stallman's avatar
Richard M. Stallman committed
36
;; (setq auto-mode-alist (append (list (cons "\\.pl\\'" 'perl-mode))
Jim Blandy's avatar
Jim Blandy committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50
;;                               auto-mode-alist))
;; to your .emacs file; otherwise the .pl suffix defaults to prolog-mode.

;; This code is based on the 18.53 version c-mode.el, with extensive
;; rewriting.  Most of the features of c-mode survived intact.

;; I added a new feature which adds functionality to TAB; it is controlled
;; by the variable perl-tab-to-comment.  With it enabled, TAB does the
;; first thing it can from the following list:  change the indentation;
;; move past leading white space; delete an empty comment; reindent a
;; comment; move to end of line; create an empty comment; tell you that
;; the line ends in a quoted string, or has a # which should be a \#.

;; 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
Jim Blandy's avatar
Jim Blandy committed
52 53 54
;; what Larry Wall uses in perl/lib, but left in all the options.

;; 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
Jim Blandy's avatar
Jim Blandy committed
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
Jim Blandy's avatar
Jim Blandy committed
58 59 60 61 62 63
;; (meta-^q) indents from the current line through the close of the next
;; brace/paren, so you don't need to start exactly at a brace or paren.

;; It may be good style to put a set of redundant braces around your
;; main program.  This will let you reindent it with meta-^q.

Eric S. Raymond's avatar
Eric S. Raymond committed
64
;; Known problems (these are all caused by limitations in the Emacs Lisp
Jim Blandy's avatar
Jim Blandy committed
65 66 67 68
;; parsing routine (parse-partial-sexp), which was not designed for such
;; a rich language; writing a more suitable parser would be a big job):
;; 2)  The globbing syntax <pattern> is not recognized, so special
;;       characters in the pattern string must be backslashed.
69
;; 3)  The << quoting operators are not recognized; see below.
70 71 72 73
;; 5)  To make '$' work correctly, $' is not recognized as a variable.
;;     Use "$'" or $POSTMATCH instead.
;;
;; If you don't use font-lock, additional problems will appear:
74 75 76 77
;; 1)  Regular expression delimiters do not act as quotes, so special
;;       characters such as `'"#:;[](){} may need to be backslashed
;;       in regular expressions and in both parts of s/// and tr///.
;; 4)  The q and qq quoting operators are not recognized; see below.
Jim Blandy's avatar
Jim Blandy committed
78
;; 5)  To make variables such a $' and $#array work, perl-mode treats
79
;;       $ just like backslash, so '$' is not treated correctly.
Jim Blandy's avatar
Jim Blandy committed
80 81
;; 6)  Unfortunately, treating $ like \ makes ${var} be treated as an
;;       unmatched }.  See below.
82 83
;; 7)  When ' (quote) is used as a package name separator, perl-mode
;;       doesn't understand, and thinks it is seeing a quoted string.
Jim Blandy's avatar
Jim Blandy committed
84 85 86 87 88 89 90 91 92

;; Here are some ugly tricks to bypass some of these problems:  the perl
;; expression /`/ (that's a back-tick) usually evaluates harmlessly,
;; but will trick perl-mode into starting a quoted string, which
;; can be ended with another /`/.  Assuming you have no embedded
;; back-ticks, this can used to help solve problem 3:
;;
;;     /`/; $ugly = q?"'$?; /`/;
;;
93 94 95 96
;; The same trick can be used for problem 6 as in:
;;     /{/; while (<${glob_me}>)
;; but a simpler solution is to add a space between the $ and the {:
;;     while (<$ {glob_me}>)
97
;;
Jim Blandy's avatar
Jim Blandy committed
98 99 100 101 102
;; Problem 7 is even worse, but this 'fix' does work :-(
;;     $DB'stop#'
;;         [$DB'line#'
;;          ] =~ s/;9$//;

Eric S. Raymond's avatar
Eric S. Raymond committed
103
;;; Code:
Jim Blandy's avatar
Jim Blandy committed
104

105 106
(eval-when-compile (require 'cl))

107 108 109 110
(defvar font-lock-comment-face)
(defvar font-lock-doc-face)
(defvar font-lock-string-face)

Stephen Eglen's avatar
Stephen Eglen committed
111 112
(defgroup perl nil
  "Major mode for editing Perl code."
113
  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
Stephen Eglen's avatar
Stephen Eglen committed
114 115 116
  :prefix "perl-"
  :group 'languages)

117 118 119 120
(defvar perl-mode-abbrev-table nil
  "Abbrev table in use in perl-mode buffers.")
(define-abbrev-table 'perl-mode-abbrev-table ())

121 122 123 124 125 126 127 128 129 130 131 132 133
(defvar perl-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "{" 'perl-electric-terminator)
    (define-key map "}" 'perl-electric-terminator)
    (define-key map ";" 'perl-electric-terminator)
    (define-key map ":" 'perl-electric-terminator)
    (define-key map "\e\C-a" 'perl-beginning-of-function)
    (define-key map "\e\C-e" 'perl-end-of-function)
    (define-key map "\e\C-h" 'perl-mark-function)
    (define-key map "\e\C-q" 'perl-indent-exp)
    (define-key map "\177" 'backward-delete-char-untabify)
    (define-key map "\t" 'perl-indent-command)
    map)
134
  "Keymap used in Perl mode.")
Jim Blandy's avatar
Jim Blandy committed
135 136 137 138 139 140

(autoload 'c-macro-expand "cmacexp"
  "Display the result of expanding all C macros occurring in the region.
The expansion is entirely correct because it uses the C preprocessor."
  t)

141 142 143 144
(defvar perl-mode-syntax-table
  (let ((st (make-syntax-table (standard-syntax-table))))
    (modify-syntax-entry ?\n ">" st)
    (modify-syntax-entry ?# "<" st)
145 146 147
    ;; `$' is also a prefix char so I was tempted to say "/ p",
    ;; but the `p' thingy basically overrides the `/' :-(   --stef
    (modify-syntax-entry ?$ "/" st)
148 149
    (modify-syntax-entry ?% ". p" st)
    (modify-syntax-entry ?@ ". p" st)
150 151 152 153 154 155 156 157 158 159 160 161 162 163
    (modify-syntax-entry ?& "." st)
    (modify-syntax-entry ?\' "\"" st)
    (modify-syntax-entry ?* "." st)
    (modify-syntax-entry ?+ "." st)
    (modify-syntax-entry ?- "." st)
    (modify-syntax-entry ?/ "." st)
    (modify-syntax-entry ?< "." st)
    (modify-syntax-entry ?= "." st)
    (modify-syntax-entry ?> "." st)
    (modify-syntax-entry ?\\ "\\" st)
    (modify-syntax-entry ?` "\"" st)
    (modify-syntax-entry ?| "." st)
    st)
  "Syntax table in use in `perl-mode' buffers.")
Jim Blandy's avatar
Jim Blandy committed
164

165
(defvar perl-imenu-generic-expression
166
  '(;; Functions
167
    (nil "^sub\\s-+\\([-A-Za-z0-9+_:]+\\)" 1)
168
    ;;Variables
169
    ("Variables" "^\\(?:my\\|our\\)\\s-+\\([$@%][-A-Za-z0-9+_:]+\\)\\s-*=" 1)
170 171
    ("Packages" "^package\\s-+\\([-A-Za-z0-9+_:]+\\);" 1)
    ("Doc sections" "^=head[0-9][ \t]+\\(.*\\)" 1))
172 173
  "Imenu generic expression for Perl mode.  See `imenu-generic-expression'.")

Simon Marshall's avatar
Simon Marshall committed
174 175 176 177 178 179 180 181 182
;; Regexps updated with help from Tom Tromey <tromey@cambric.colorado.edu> and
;; Jim Campbell <jec@murzim.ca.boeing.com>.

(defconst perl-font-lock-keywords-1
  '(;; What is this for?
    ;;("\\(--- .* ---\\|=== .* ===\\)" . font-lock-string-face)
    ;;
    ;; Fontify preprocessor statements as we do in `c-font-lock-keywords'.
    ;; Ilya Zakharevich <ilya@math.ohio-state.edu> thinks this is a bad idea.
183 184 185 186 187 188 189
    ;; ("^#[ \t]*include[ \t]+\\(<[^>\"\n]+>\\)" 1 font-lock-string-face)
    ;; ("^#[ \t]*define[ \t]+\\(\\sw+\\)(" 1 font-lock-function-name-face)
    ;; ("^#[ \t]*if\\>"
    ;;  ("\\<\\(defined\\)\\>[ \t]*(?\\(\\sw+\\)?" nil nil
    ;;   (1 font-lock-constant-face) (2 font-lock-variable-name-face nil t)))
    ;; ("^#[ \t]*\\(\\sw+\\)\\>[ \t]*\\(\\sw+\\)?"
    ;;  (1 font-lock-constant-face) (2 font-lock-variable-name-face nil t))
Simon Marshall's avatar
Simon Marshall committed
190 191 192 193 194
    ;;
    ;; Fontify function and package names in declarations.
    ("\\<\\(package\\|sub\\)\\>[ \t]*\\(\\sw+\\)?"
     (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
    ("\\<\\(import\\|no\\|require\\|use\\)\\>[ \t]*\\(\\sw+\\)?"
195
     (1 font-lock-keyword-face) (2 font-lock-constant-face nil t)))
Simon Marshall's avatar
Simon Marshall committed
196 197 198 199 200 201 202
  "Subdued level highlighting for Perl mode.")

(defconst perl-font-lock-keywords-2
  (append perl-font-lock-keywords-1
   (list
    ;;
    ;; Fontify keywords, except those fontified otherwise.
203 204 205 206 207
    (concat "\\<"
	    (regexp-opt '("if" "until" "while" "elsif" "else" "unless"
			  "do" "dump" "for" "foreach" "exit" "die"
			  "BEGIN" "END" "return" "exec" "eval") t)
	    "\\>")
Simon Marshall's avatar
Simon Marshall committed
208 209 210 211 212
    ;;
    ;; Fontify local and my keywords as types.
    '("\\<\\(local\\|my\\)\\>" . font-lock-type-face)
    ;;
    ;; Fontify function, variable and file name references.
Stefan Monnier's avatar
Stefan Monnier committed
213
    '("&\\(\\sw+\\(::\\sw+\\)*\\)" 1 font-lock-function-name-face)
Simon Marshall's avatar
Simon Marshall committed
214 215
    ;; Additionally underline non-scalar variables.  Maybe this is a bad idea.
    ;;'("[$@%*][#{]?\\(\\sw+\\)" 1 font-lock-variable-name-face)
Stefan Monnier's avatar
Stefan Monnier committed
216 217
    '("[$*]{?\\(\\sw+\\(::\\sw+\\)*\\)" 1 font-lock-variable-name-face)
    '("\\([@%]\\|\\$#\\)\\(\\sw+\\(::\\sw+\\)*\\)"
Simon Marshall's avatar
Simon Marshall committed
218
      (2 (cons font-lock-variable-name-face '(underline))))
219
    '("<\\(\\sw+\\)>" 1 font-lock-constant-face)
Simon Marshall's avatar
Simon Marshall committed
220 221 222
    ;;
    ;; Fontify keywords with/and labels as we do in `c++-font-lock-keywords'.
    '("\\<\\(continue\\|goto\\|last\\|next\\|redo\\)\\>[ \t]*\\(\\sw+\\)?"
223 224
      (1 font-lock-keyword-face) (2 font-lock-constant-face nil t))
    '("^[ \t]*\\(\\sw+\\)[ \t]*:[^:]" 1 font-lock-constant-face)))
Simon Marshall's avatar
Simon Marshall committed
225 226 227 228 229
  "Gaudy level highlighting for Perl mode.")

(defvar perl-font-lock-keywords perl-font-lock-keywords-1
  "Default expressions to highlight in Perl mode.")

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
(defvar perl-quote-like-pairs
  '((?\( . ?\)) (?\[ . ?\]) (?\{ . ?\}) (?\< . ?\>)))

;; FIXME: handle here-docs and regexps.
;; <<EOF <<"EOF" <<'EOF' (no space)
;; see `man perlop'
;; ?...?
;; /.../
;; m [...]
;; m /.../
;; q /.../ = '...'
;; qq /.../ = "..."
;; qx /.../ = `...`
;; qr /.../ = precompiled regexp =~=~ m/.../
;; qw /.../
;; s /.../.../
;; s <...> /.../
;; s '...'...'
;; tr /.../.../
;; y /.../.../
;;
;; <file*glob>
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
(defun perl-syntax-propertize-function (start end)
  (let ((case-fold-search nil))
    (goto-char start)
    (perl-syntax-propertize-special-constructs end)
    ;; TODO: here-documents ("<<\\(\\sw\\|['\"]\\)")
    (funcall
     (syntax-propertize-rules
      ;; Turn POD into b-style comments.  Place the cut rule first since it's
      ;; more specific.
      ("^=cut\\>.*\\(\n\\)" (1 "> b"))
      ("^\\(=\\)\\sw" (1 "< b"))
      ;; Catch ${ so that ${var} doesn't screw up indentation.
      ;; This also catches $' to handle 'foo$', although it should really
      ;; check that it occurs inside a '..' string.
      ("\\(\\$\\)[{']" (1 ". p"))
      ;; Handle funny names like $DB'stop.
      ("\\$ ?{?^?[_a-zA-Z][_a-zA-Z0-9]*\\('\\)[_a-zA-Z]" (1 "_"))
      ;; format statements
      ("^[ \t]*format.*=[ \t]*\\(\n\\)"
       (1 (prog1 "\"" (perl-syntax-propertize-special-constructs end))))
      ;; Funny things in `sub' arg-specs like `sub myfun ($)' or `sub ($)'.
      ;; Be careful not to match "sub { (...) ... }".
      ("\\<sub\\(?:[[:space:]]+[^{}[:punct:][:space:]]+\\)?[[:space:]]*(\\([^)]+\\))"
       (1 "."))
276 277 278 279 280
      ;; Turn __DATA__ trailer into a comment.
      ("^\\(_\\)_\\(?:DATA\\|END\\)__[ \t]*\\(?:\\(\n\\)#.-\\*-.*perl.*-\\*-\\|\n.*\\)"
       (1 "< c") (2 "> c")
       (0 (ignore (put-text-property (match-beginning 0) (match-end 0)
                                     'syntax-multiline t))))
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
      ;; Regexp and funny quotes.  Distinguishing a / that starts a regexp
      ;; match from the division operator is ...interesting.
      ;; Basically, / is a regexp match if it's preceded by an infix operator
      ;; (or some similar separator), or by one of the special keywords
      ;; corresponding to builtin functions that can take their first arg
      ;; without parentheses.  Of course, that presume we're looking at the
      ;; *opening* slash.  We can afford to mis-match the closing ones
      ;; here, because they will be re-treated separately later in
      ;; perl-font-lock-special-syntactic-constructs.
      ((concat "\\(?:\\(?:^\\|[^$@&%[:word:]]\\)"
               (regexp-opt '("split" "if" "unless" "until" "while" "split"
                             "grep" "map" "not" "or" "and"))
               "\\|[?:.,;=!~({[]\\|\\(^\\)\\)[ \t\n]*\\(/\\)")
       (2 (ignore
           (if (and (match-end 1)       ; / at BOL.
                    (save-excursion
                      (goto-char (match-end 1))
                      (forward-comment (- (point-max)))
                      (put-text-property (point) (match-end 2)
                                         'syntax-multiline t)
                      (not (memq (char-before)
                                 '(?? ?: ?. ?, ?\; ?= ?! ?~ ?\( ?\[)))))
               nil ;; A division sign instead of a regexp-match.
             (put-text-property (match-beginning 2) (match-end 2)
                                'syntax-table (string-to-syntax "\""))
             (perl-syntax-propertize-special-constructs end)))))
307
      ("\\(^\\|[?:.,;=!~({[ \t]\\)\\([msy]\\|q[qxrw]?\\|tr\\)\\>\\s-*\\(?:\\([^])}>= \n\t]\\)\\|\\(?3:=\\)[^>]\\)"
308 309 310 311
       ;; Nasty cases:
       ;; /foo/m  $a->m  $#m $m @m %m
       ;; \s (appears often in regexps).
       ;; -s file
312
       ;; y => 3
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
       ;; sub tr {...}
       (3 (ignore
           (if (save-excursion (goto-char (match-beginning 0))
                               (forward-word -1)
                               (looking-at-p "sub[ \t\n]"))
               ;; This is defining a function.
               nil
             (put-text-property (match-beginning 3) (match-end 3)
                                'syntax-table
                                (if (assoc (char-after (match-beginning 3))
                                           perl-quote-like-pairs)
                                    (string-to-syntax "|")
                                  (string-to-syntax "\"")))
             (perl-syntax-propertize-special-constructs end))))))
     (point) end)))
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

(defvar perl-empty-syntax-table
  (let ((st (copy-syntax-table)))
    ;; Make all chars be of punctuation syntax.
    (dotimes (i 256) (aset st i '(1)))
    (modify-syntax-entry ?\\ "\\" st)
    st)
  "Syntax table used internally for processing quote-like operators.")

(defun perl-quote-syntax-table (char)
  (let ((close (cdr (assq char perl-quote-like-pairs)))
	(st (copy-syntax-table perl-empty-syntax-table)))
    (if (not close)
	(modify-syntax-entry char "\"" st)
      (modify-syntax-entry char "(" st)
      (modify-syntax-entry close ")" st))
    st))
345

346 347
(defun perl-syntax-propertize-special-constructs (limit)
  "Propertize special constructs like regexps and formats."
348 349
  (let ((state (syntax-ppss))
        char)
350 351 352 353 354 355 356 357 358 359 360 361 362
    (cond
     ((or (null (setq char (nth 3 state)))
          (and (characterp char) (eq (char-syntax (nth 3 state)) ?\")))
      ;; Normal text, or comment, or docstring, or normal string.
      nil)
     ((eq (nth 3 state) ?\n)
      ;; A `format' command.
      (when (re-search-forward "^\\s *\\.\\s *\n" limit 'move)
        (put-text-property (1- (point)) (point)
                           'syntax-table (string-to-syntax "\""))))
     (t
      ;; This is regexp like quote thingy.
      (setq char (char-after (nth 8 state)))
363 364
      (let ((startpos (point))
            (twoargs (save-excursion
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
                       (goto-char (nth 8 state))
                       (skip-syntax-backward " ")
                       (skip-syntax-backward "w")
                       (member (buffer-substring
                                (point) (progn (forward-word 1) (point)))
                               '("tr" "s" "y"))))
            (close (cdr (assq char perl-quote-like-pairs)))
            (st (perl-quote-syntax-table char)))
        (when (with-syntax-table st
		(if close
		    ;; For paired delimiters, Perl allows nesting them, but
		    ;; since we treat them as strings, Emacs does not count
		    ;; those delimiters in `state', so we don't know how deep
		    ;; we are: we have to go back to the beginning of this
		    ;; "string" and count from there.
		    (condition-case nil
                        (progn
			  ;; Start after the first char since it doesn't have
			  ;; paren-syntax (an alternative would be to let-bind
			  ;; parse-sexp-lookup-properties).
			  (goto-char (1+ (nth 8 state)))
			  (up-list 1)
			  t)
388 389
                      ;; In case of error, make sure we don't move backward.
		      (scan-error (goto-char startpos) nil))
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
		  (not (or (nth 8 (parse-partial-sexp
				   (point) limit nil nil state 'syntax-table))
			   ;; If we have a self-paired opener and a twoargs
			   ;; command, the form is s/../../ so we have to skip
			   ;; a second time.
			   ;; In the case of s{...}{...}, we only handle the
			   ;; first part here and the next below.
			   (when (and twoargs (not close))
			     (nth 8 (parse-partial-sexp
				     (point) limit
				     nil nil state 'syntax-table)))))))
	  ;; Point is now right after the arg(s).
	  (when (eq (char-before (1- (point))) ?$)
	    (put-text-property (- (point) 2) (1- (point))
			       'syntax-table '(1)))
	  (put-text-property (1- (point)) (point)
			     'syntax-table
			     (if close
				 (string-to-syntax "|")
			       (string-to-syntax "\"")))
	  ;; If we have two args with a non-self-paired starter (e.g.
	  ;; s{...}{...}) we're right after the first arg, so we still have to
	  ;; handle the second part.
	  (when (and twoargs close)
            ;; Skip whitespace and make sure that font-lock will
            ;; refontify the second part in the proper context.
            (put-text-property
             (point) (progn (forward-comment (point-max)) (point))
	     'syntax-multiline t)
            ;;
	    (when (< (point) limit)
              (put-text-property (point) (1+ (point))
                                 'syntax-table
                                 (if (assoc (char-after)
                                            perl-quote-like-pairs)
                                     ;; Put an `e' in the cdr to mark this
                                     ;; char as "second arg starter".
				     (string-to-syntax "|e")
				   (string-to-syntax "\"e")))
	      (forward-char 1)
	      ;; Re-use perl-syntax-propertize-special-constructs to handle the
	      ;; second part (the first delimiter of second part can't be
	      ;; preceded by "s" or "tr" or "y", so it will not be considered
	      ;; as twoarg).
	      (perl-syntax-propertize-special-constructs limit)))))))))

(defun perl-font-lock-syntactic-face-function (state)
  (cond
   ((and (nth 3 state)
         (eq ?e (cdr-safe (get-text-property (nth 8 state) 'syntax-table)))
         ;; This is a second-arg of s{..}{...} form; let's check if this second
         ;; arg is executable code rather than a string.  For that, we need to
         ;; look for an "e" after this second arg, so we have to hunt for the
         ;; end of the arg.  Depending on whether the whole arg has already
         ;; been syntax-propertized or not, the end-char will have different
         ;; syntaxes, so let's ignore syntax-properties temporarily so we can
         ;; pretend it has not been syntax-propertized yet.
         (let* ((parse-sexp-lookup-properties nil)
                (char (char-after (nth 8 state)))
                (paired (assq char perl-quote-like-pairs)))
           (with-syntax-table (perl-quote-syntax-table char)
             (save-excursion
               (if (not paired)
                   (parse-partial-sexp (point) (point-max)
                                       nil nil state 'syntax-table)
                 (condition-case nil
                     (progn
                       (goto-char (1+ (nth 8 state)))
                       (up-list 1))
                   (scan-error (goto-char (point-max)))))
               (put-text-property (nth 8 state) (point)
                                  'jit-lock-defer-multiline t)
               (looking-at "[ \t]*\\sw*e")))))
    nil)
   (t (funcall (default-value 'font-lock-syntactic-face-function) state))))
465

Stephen Eglen's avatar
Stephen Eglen committed
466 467
(defcustom perl-indent-level 4
  "*Indentation of Perl statements with respect to containing block."
468 469
  :type 'integer
  :group 'perl)
470

471
;; Is is not unusual to put both things like perl-indent-level and
472 473
;; cperl-indent-level in the local variable section of a file. If only
;; one of perl-mode and cperl-mode is in use, a warning will be issued
474
;; about the variable. Autoload these here, so that no warning is
475 476
;; issued when using either perl-mode or cperl-mode.
;;;###autoload(put 'perl-indent-level 'safe-local-variable 'integerp)
477 478 479 480 481
;;;###autoload(put 'perl-continued-statement-offset 'safe-local-variable 'integerp)
;;;###autoload(put 'perl-continued-brace-offset 'safe-local-variable 'integerp)
;;;###autoload(put 'perl-brace-offset 'safe-local-variable 'integerp)
;;;###autoload(put 'perl-brace-imaginary-offset 'safe-local-variable 'integerp)
;;;###autoload(put 'perl-label-offset 'safe-local-variable 'integerp)
482

Stephen Eglen's avatar
Stephen Eglen committed
483 484
(defcustom perl-continued-statement-offset 4
  "*Extra indent for lines not starting new statements."
485 486
  :type 'integer
  :group 'perl)
Stephen Eglen's avatar
Stephen Eglen committed
487
(defcustom perl-continued-brace-offset -4
Jim Blandy's avatar
Jim Blandy committed
488
  "*Extra indent for substatements that start with open-braces.
Stephen Eglen's avatar
Stephen Eglen committed
489
This is in addition to `perl-continued-statement-offset'."
490 491
  :type 'integer
  :group 'perl)
Stephen Eglen's avatar
Stephen Eglen committed
492 493
(defcustom perl-brace-offset 0
  "*Extra indentation for braces, compared with other text in same context."
494 495
  :type 'integer
  :group 'perl)
Stephen Eglen's avatar
Stephen Eglen committed
496 497
(defcustom perl-brace-imaginary-offset 0
  "*Imagined indentation of an open brace that actually follows a statement."
498 499
  :type 'integer
  :group 'perl)
Stephen Eglen's avatar
Stephen Eglen committed
500 501
(defcustom perl-label-offset -2
  "*Offset of Perl label lines relative to usual indentation."
502 503
  :type 'integer
  :group 'perl)
504 505 506
(defcustom perl-indent-continued-arguments nil
  "*If non-nil offset of argument lines relative to usual indentation.
If nil, continued arguments are aligned with the first argument."
507 508
  :type '(choice integer (const nil))
  :group 'perl)
Stephen Eglen's avatar
Stephen Eglen committed
509

510 511
(defcustom perl-tab-always-indent tab-always-indent
  "Non-nil means TAB in Perl mode always indents the current line.
512
Otherwise it inserts a tab character if you type it past the first
Stephen Eglen's avatar
Stephen Eglen committed
513
nonwhite character on the line."
514 515
  :type 'boolean
  :group 'perl)
Jim Blandy's avatar
Jim Blandy committed
516

517 518
;; I changed the default to nil for consistency with general Emacs
;; conventions -- rms.
Stephen Eglen's avatar
Stephen Eglen committed
519
(defcustom perl-tab-to-comment nil
520 521 522
  "*Non-nil means TAB moves to eol or makes a comment in some cases.
For lines which don't need indenting, TAB either indents an
existing comment, moves to end-of-line, or if at end-of-line already,
Stephen Eglen's avatar
Stephen Eglen committed
523
create a new comment."
524 525
  :type 'boolean
  :group 'perl)
Stephen Eglen's avatar
Stephen Eglen committed
526

527
(defcustom perl-nochange ";?#\\|\f\\|\\s(\\|\\(\\w\\|\\s_\\)+:[^:]"
Stephen Eglen's avatar
Stephen Eglen committed
528
  "*Lines starting with this regular expression are not auto-indented."
529 530
  :type 'regexp
  :group 'perl)
531 532 533 534 535 536 537 538 539 540 541 542 543 544

;; Outline support

(defvar perl-outline-regexp
  (concat (mapconcat 'cadr perl-imenu-generic-expression "\\|")
	  "\\|^=cut\\>"))

(defun perl-outline-level ()
  (cond
   ((looking-at "package\\s-") 0)
   ((looking-at "sub\\s-") 1)
   ((looking-at "=head[0-9]") (- (char-before (match-end 0)) ?0))
   ((looking-at "=cut") 1)
   (t 3)))
Jim Blandy's avatar
Jim Blandy committed
545

546 547 548
(defvar perl-mode-hook nil
  "Normal hook to run when entering Perl mode.")

549
;;;###autoload
550
(define-derived-mode perl-mode prog-mode "Perl"
Jim Blandy's avatar
Jim Blandy committed
551 552 553 554 555 556 557 558
  "Major mode for editing Perl code.
Expression and list commands understand all Perl brackets.
Tab indents for Perl code.
Comments are delimited with # ... \\n.
Paragraphs are separated by blank lines only.
Delete converts tabs to spaces as it moves back.
\\{perl-mode-map}
Variables controlling indentation style:
559
 `perl-tab-always-indent'
Jim Blandy's avatar
Jim Blandy committed
560 561
    Non-nil means TAB in Perl mode should always indent the current line,
    regardless of where in the line point is when the TAB command is used.
562
 `perl-tab-to-comment'
Jim Blandy's avatar
Jim Blandy committed
563
    Non-nil means that for lines which don't need indenting, TAB will
564
    either delete an empty comment, indent an existing comment, move
Jim Blandy's avatar
Jim Blandy committed
565
    to end-of-line, or if at end-of-line already, create a new comment.
566
 `perl-nochange'
567
    Lines starting with this regular expression are not auto-indented.
568
 `perl-indent-level'
Jim Blandy's avatar
Jim Blandy committed
569 570 571
    Indentation of Perl statements within surrounding block.
    The surrounding block's indentation is the indentation
    of the line on which the open-brace appears.
572
 `perl-continued-statement-offset'
Jim Blandy's avatar
Jim Blandy committed
573 574
    Extra indentation given to a substatement, such as the
    then-clause of an if or body of a while.
575
 `perl-continued-brace-offset'
Jim Blandy's avatar
Jim Blandy committed
576
    Extra indentation given to a brace that starts a substatement.
577
    This is in addition to `perl-continued-statement-offset'.
578
 `perl-brace-offset'
Jim Blandy's avatar
Jim Blandy committed
579
    Extra indentation for line if it starts with an open brace.
580
 `perl-brace-imaginary-offset'
Jim Blandy's avatar
Jim Blandy committed
581 582
    An open brace following other text is treated as if it were
    this far to the right of the start of its line.
583
 `perl-label-offset'
Jim Blandy's avatar
Jim Blandy committed
584
    Extra indentation for line that is a label.
585 586
 `perl-indent-continued-arguments'
    Offset of argument lines relative to usual indentation.
Jim Blandy's avatar
Jim Blandy committed
587 588 589 590 591 592 593 594 595

Various indentation styles:       K&R  BSD  BLK  GNU  LW
  perl-indent-level                5    8    0    2    4
  perl-continued-statement-offset  5    8    4    2    4
  perl-continued-brace-offset      0    0    0    0   -4
  perl-brace-offset               -5   -8    0    0    0
  perl-brace-imaginary-offset      0    0    4    0    0
  perl-label-offset               -5   -8   -2   -2   -2

596
Turning on Perl mode runs the normal hook `perl-mode-hook'."
597 598 599 600 601 602 603 604 605 606
  :abbrev-table perl-mode-abbrev-table
  (set (make-local-variable 'paragraph-start) (concat "$\\|" page-delimiter))
  (set (make-local-variable 'paragraph-separate) paragraph-start)
  (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
  (set (make-local-variable 'indent-line-function) #'perl-indent-line)
  (set (make-local-variable 'comment-start) "# ")
  (set (make-local-variable 'comment-end) "")
  (set (make-local-variable 'comment-start-skip) "\\(^\\|\\s-\\);?#+ *")
  (set (make-local-variable 'comment-indent-function) #'perl-comment-indent)
  (set (make-local-variable 'parse-sexp-ignore-comments) t)
Simon Marshall's avatar
Simon Marshall committed
607 608 609 610
  ;; Tell font-lock.el how to handle Perl.
  (setq font-lock-defaults '((perl-font-lock-keywords
			      perl-font-lock-keywords-1
			      perl-font-lock-keywords-2)
611
			     nil nil ((?\_ . "w")) nil
612 613 614 615 616 617
                             (font-lock-syntactic-face-function
                              . perl-font-lock-syntactic-face-function)))
  (set (make-local-variable 'syntax-propertize-function)
       #'perl-syntax-propertize-function)
  (add-hook 'syntax-propertize-extend-region-functions
            #'syntax-propertize-multiline 'append 'local)
618
  ;; Tell imenu how to handle Perl.
619 620
  (set (make-local-variable 'imenu-generic-expression)
       perl-imenu-generic-expression)
621
  (setq imenu-case-fold-search nil)
622 623
  ;; Setup outline-minor-mode.
  (set (make-local-variable 'outline-regexp) perl-outline-regexp)
624
  (set (make-local-variable 'outline-level) 'perl-outline-level))
Jim Blandy's avatar
Jim Blandy committed
625 626 627 628 629 630 631

;; This is used by indent-for-comment
;; to decide how much to indent a comment in Perl code
;; based on its context.
(defun perl-comment-indent ()
  (if (and (bolp) (not (eolp)))
      0					;Existing comment at bol stays there.
632 633 634 635
    comment-column))

(defalias 'electric-perl-terminator 'perl-electric-terminator)
(defun perl-electric-terminator (arg)
Glenn Morris's avatar
Glenn Morris committed
636 637
  "Insert character and maybe adjust indentation.
If at end-of-line, and not in a comment or a quote, correct the indentation."
Jim Blandy's avatar
Jim Blandy committed
638 639 640 641 642 643 644
  (interactive "P")
  (let ((insertpos (point)))
    (and (not arg)			; decide whether to indent
	 (eolp)
	 (save-excursion
	   (beginning-of-line)
	   (and (not			; eliminate comments quickly
645 646
		 (and comment-start-skip
		      (re-search-forward comment-start-skip insertpos t)) )
647
		(or (/= last-command-event ?:)
Jim Blandy's avatar
Jim Blandy committed
648 649
		    ;; Colon is special only after a label ....
		    (looking-at "\\s-*\\(\\w\\|\\s_\\)+$"))
650
		(let ((pps (parse-partial-sexp
Jim Blandy's avatar
Jim Blandy committed
651 652 653
			    (perl-beginning-of-function) insertpos)))
		  (not (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))
	 (progn				; must insert, indent, delete
654
	   (insert-char last-command-event 1)
Jim Blandy's avatar
Jim Blandy committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
	   (perl-indent-line)
	   (delete-char -1))))
  (self-insert-command (prefix-numeric-value arg)))

;; not used anymore, but may be useful someday:
;;(defun perl-inside-parens-p ()
;;  (condition-case ()
;;      (save-excursion
;;	(save-restriction
;;	  (narrow-to-region (point)
;;			    (perl-beginning-of-function))
;;	  (goto-char (point-max))
;;	  (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
;;    (error nil)))

(defun perl-indent-command (&optional arg)
671 672 673 674
  "Indent Perl code in the active region or current line.
In Transient Mark mode, when the region is active, reindent the region.
Otherwise, with a prefix argument, reindent the current line
unconditionally.
Jim Blandy's avatar
Jim Blandy committed
675

676 677
Otherwise, if `perl-tab-always-indent' is nil and point is not in
the indentation area at the beginning of the line, insert a tab.
Jim Blandy's avatar
Jim Blandy committed
678

679 680 681 682 683 684
Otherwise, indent the current line.  If point was within the
indentation area, it is moved to the end of the indentation area.
If the line was already indented properly and point was not
within the indentation area, and if `perl-tab-to-comment' is
non-nil (the default), then do the first possible action from the
following list:
Jim Blandy's avatar
Jim Blandy committed
685 686 687 688 689 690 691

  1) delete an empty comment
  2) move forward to start of comment, indenting if necessary
  3) move forward to end of line
  4) create an empty comment
  5) move backward to start of comment, indenting if necessary."
  (interactive "P")
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
  (cond ((use-region-p)            ; indent the active region
	 (indent-region (region-beginning) (region-end)))
	(arg
	 (perl-indent-line "\f"))  ; just indent this line
	((and (not perl-tab-always-indent)
	      (> (current-column) (current-indentation)))
	 (insert-tab))
	(t
	 (let* ((oldpnt (point))
		(lsexp (progn (beginning-of-line) (point)))
		(bof (perl-beginning-of-function))
		(delta (progn
			 (goto-char oldpnt)
			 (perl-indent-line "\f\\|;?#" bof))))
	   (and perl-tab-to-comment
		(= oldpnt (point))   ; done if point moved
		(if (listp delta)    ; if line starts in a quoted string
		    (setq lsexp (or (nth 2 delta) bof))
		  (= delta 0))	     ; done if indenting occurred
		(let ((eol (progn (end-of-line) (point)))
		      state)
		  (cond ((= (char-after bof) ?=)
			 (if (= oldpnt eol)
			     (message "In a format statement")))
			((progn (setq state (parse-partial-sexp lsexp eol))
				(nth 3 state))
			 (if (= oldpnt eol) ; already at eol in a string
			     (message "In a string which starts with a %c."
				      (nth 3 state))))
			((not (nth 4 state))
			 (if (= oldpnt eol) ; no comment, create one?
			     (indent-for-comment)))
			((progn (beginning-of-line)
				(and comment-start-skip
				     (re-search-forward
				      comment-start-skip eol 'move)))
Jim Blandy's avatar
Jim Blandy committed
728
			 (if (eolp)
729
			     (progn	    ; delete existing comment
Jim Blandy's avatar
Jim Blandy committed
730 731
			       (goto-char (match-beginning 0))
			       (skip-chars-backward " \t")
732
			       (delete-region (point) eol))
Jim Blandy's avatar
Jim Blandy committed
733 734
			   (if (or (< oldpnt (point)) (= oldpnt eol))
			       (indent-for-comment) ; indent existing comment
735 736 737 738
			     (end-of-line))))
			((/= oldpnt eol)
			 (end-of-line))
			(t
Jim Blandy's avatar
Jim Blandy committed
739
			 (message "Use backslash to quote # characters.")
740
			 (ding t)))))))))
Jim Blandy's avatar
Jim Blandy committed
741 742

(defun perl-indent-line (&optional nochange parse-start)
743
  "Indent current line as Perl code.
744
Return the amount the indentation
Jim Blandy's avatar
Jim Blandy committed
745 746 747 748 749 750 751 752
changed by, or (parse-state) if line starts in a quoted string."
  (let ((case-fold-search nil)
	(pos (- (point-max) (point)))
	(bof (or parse-start (save-excursion (perl-beginning-of-function))))
	beg indent shift-amt)
    (beginning-of-line)
    (setq beg (point))
    (setq shift-amt
753
	  (cond ((eq (char-after bof) ?=) 0)
754
		((listp (setq indent (perl-calculate-indent bof))) indent)
Jim Blandy's avatar
Jim Blandy committed
755 756 757
		((looking-at (or nochange perl-nochange)) 0)
		(t
		 (skip-chars-forward " \t\f")
758
		 (setq indent (perl-indent-new-calculate nil indent bof))
Jim Blandy's avatar
Jim Blandy committed
759 760 761 762 763 764 765 766 767 768 769
		 (- indent (current-column)))))
    (skip-chars-forward " \t\f")
    (if (and (numberp shift-amt) (/= 0 shift-amt))
	(progn (delete-region beg (point))
	       (indent-to indent)))
    ;; If initial point was within line's indentation,
    ;; position after the indentation.  Else stay at same point in text.
    (if (> (- (point-max) pos) (point))
	(goto-char (- (point-max) pos)))
    shift-amt))

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
(defun perl-continuation-line-p (limit)
  "Move to end of previous line and return non-nil if continued."
  ;; Statement level.  Is it a continuation or a new statement?
  ;; Find previous non-comment character.
  (perl-backward-to-noncomment)
  ;; Back up over label lines, since they don't
  ;; affect whether our line is a continuation.
  (while (or (eq (preceding-char) ?\,)
	     (and (eq (preceding-char) ?:)
		  (memq (char-syntax (char-after (- (point) 2)))
			'(?w ?_))))
    (if (eq (preceding-char) ?\,)
	(perl-backward-to-start-of-continued-exp limit)
      (beginning-of-line))
    (perl-backward-to-noncomment))
  ;; Now we get the answer.
  (not (memq (preceding-char) '(?\; ?\} ?\{))))

788 789 790 791 792 793
(defun perl-hanging-paren-p ()
  "Non-nil if we are right after a hanging parenthesis-like char."
  (and (looking-at "[ \t]*$")
       (save-excursion
	 (skip-syntax-backward " (") (not (bolp)))))

794 795 796 797 798 799 800 801 802 803 804
(defun perl-indent-new-calculate (&optional virtual default parse-start)
  (or
   (and virtual (save-excursion (skip-chars-backward " \t") (bolp))
	(current-column))
   (and (looking-at "\\(\\w\\|\\s_\\)+:[^:]")
	(max 1 (+ (or default (perl-calculate-indent parse-start))
		  perl-label-offset)))
   (and (= (char-syntax (following-char)) ?\))
	(save-excursion
	  (forward-char 1)
	  (forward-sexp -1)
805 806 807 808
	  (perl-indent-new-calculate
           ;; Recalculate the parsing-start, since we may have jumped
           ;; dangerously close (typically in the case of nested functions).
           'virtual nil (save-excursion (perl-beginning-of-function)))))
809 810 811 812 813 814
   (and (and (= (following-char) ?{)
	     (save-excursion (forward-char) (perl-hanging-paren-p)))
	(+ (or default (perl-calculate-indent parse-start))
	   perl-brace-offset))
   (or default (perl-calculate-indent parse-start))))

815
(defun perl-calculate-indent (&optional parse-start)
Jim Blandy's avatar
Jim Blandy committed
816 817
  "Return appropriate indentation for current line as Perl code.
In usual case returns an integer: the column to indent to.
818 819
Returns (parse-state) if line starts inside a string.
Optional argument PARSE-START should be the position of `beginning-of-defun'."
Jim Blandy's avatar
Jim Blandy committed
820 821 822 823 824 825 826 827
  (save-excursion
    (let ((indent-point (point))
	  (case-fold-search nil)
	  (colon-line-end 0)
	  state containing-sexp)
      (if parse-start			;used to avoid searching
	  (goto-char parse-start)
	(perl-beginning-of-function))
828 829 830 831 832 833 834
      ;; We might be now looking at a local function that has nothing to
      ;; do with us because `indent-point' is past it.  In this case
      ;; look further back up for another `perl-beginning-of-function'.
      (while (and (looking-at "{")
		  (save-excursion
		    (beginning-of-line)
		    (looking-at "\\s-+sub\\>"))
Glenn Morris's avatar
Glenn Morris committed
835 836 837 838 839
		  (> indent-point (save-excursion
				    (condition-case nil
					(forward-sexp 1)
				      (scan-error nil))
				    (point))))
840
	(perl-beginning-of-function))
Jim Blandy's avatar
Jim Blandy committed
841 842
      (while (< (point) indent-point)	;repeat until right sexp
	(setq state (parse-partial-sexp (point) indent-point 0))
843 844 845 846
	;; state = (depth_in_parens innermost_containing_list
	;;          last_complete_sexp string_terminator_or_nil inside_commentp
	;;          following_quotep minimum_paren-depth_this_scan)
	;; Parsing stops if depth in parentheses becomes equal to third arg.
Jim Blandy's avatar
Jim Blandy committed
847 848 849 850 851
	(setq containing-sexp (nth 1 state)))
      (cond ((nth 3 state) state)	; In a quoted string?
	    ((null containing-sexp)	; Line is at top level.
	     (skip-chars-forward " \t\f")
	     (if (= (following-char) ?{)
852
		 0  ; move to beginning of line if it starts a function body
Jim Blandy's avatar
Jim Blandy committed
853 854 855 856 857 858 859 860 861
	       ;; indent a little if this is a continuation line
	       (perl-backward-to-noncomment)
	       (if (or (bobp)
		       (memq (preceding-char) '(?\; ?\})))
		   0 perl-continued-statement-offset)))
	    ((/= (char-after containing-sexp) ?{)
	     ;; line is expression, not statement:
	     ;; indent to just after the surrounding open.
	     (goto-char (1+ containing-sexp))
862 863 864 865 866 867 868 869
	     (if (perl-hanging-paren-p)
		 ;; We're indenting an arg of a call like:
		 ;;    $a = foobarlongnamefun (
		 ;;             arg1
		 ;;             arg2
		 ;;         );
		 (progn
		   (skip-syntax-backward "(")
870
		   (condition-case nil
871 872 873 874 875 876 877 878 879
		       (while (save-excursion
				(skip-syntax-backward " ") (not (bolp)))
			 (forward-sexp -1))
		     (scan-error nil))
		   (+ (current-column) perl-indent-level))
	       (if perl-indent-continued-arguments
		   (+ perl-indent-continued-arguments (current-indentation))
		 (skip-chars-forward " \t")
		 (current-column))))
Jim Blandy's avatar
Jim Blandy committed
880 881
	    (t
	     ;; Statement level.  Is it a continuation or a new statement?
882
	     (if (perl-continuation-line-p containing-sexp)
Jim Blandy's avatar
Jim Blandy committed
883 884 885 886 887
		 ;; This line is continuation of preceding line's statement;
		 ;; indent  perl-continued-statement-offset  more than the
		 ;; previous line of the statement.
		 (progn
		   (perl-backward-to-start-of-continued-exp containing-sexp)
888 889 890 891 892 893
		   (+ (if (save-excursion
			    (perl-continuation-line-p containing-sexp))
			  ;; If the continued line is itself a continuation
			  ;; line, then align, otherwise add an offset.
			  0 perl-continued-statement-offset)
		      (current-column)
Jim Blandy's avatar
Jim Blandy committed
894 895 896 897 898 899 900
		      (if (save-excursion (goto-char indent-point)
					  (looking-at "[ \t]*{"))
			  perl-continued-brace-offset 0)))
	       ;; This line starts a new statement.
	       ;; Position at last unclosed open.
	       (goto-char containing-sexp)
	       (or
901 902 903
		;; Is line first statement after an open-brace?
		;; If no, find that first statement and indent like it.
		(save-excursion
904 905 906 907 908 909
		  (forward-char 1)
		  ;; Skip over comments and labels following openbrace.
		  (while (progn
			   (skip-chars-forward " \t\f\n")
			   (cond ((looking-at ";?#")
				  (forward-line 1) t)
910
				 ((looking-at "\\(\\w\\|\\s_\\)+:[^:]")
911
				  (setq colon-line-end (line-end-position))
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
				  (search-forward ":")))))
		  ;; The first following code counts
		  ;; if it is before the line we want to indent.
		  (and (< (point) indent-point)
		       (if (> colon-line-end (point))
			   (- (current-indentation) perl-label-offset)
			 (current-column))))
		;; If no previous statement,
		;; indent it relative to line brace is on.
		;; For open paren in column zero, don't let statement
		;; start there too.  If perl-indent-level is zero,
		;; use perl-brace-offset + perl-continued-statement-offset
		;; For open-braces not the first thing in a line,
		;; add in perl-brace-imaginary-offset.
		(+ (if (and (bolp) (zerop perl-indent-level))
		       (+ perl-brace-offset perl-continued-statement-offset)
		     perl-indent-level)
		   ;; Move back over whitespace before the openbrace.
		   ;; If openbrace is not first nonwhite thing on the line,
		   ;; add the perl-brace-imaginary-offset.
		   (progn (skip-chars-backward " \t")
			  (if (bolp) 0 perl-brace-imaginary-offset))
		   ;; If the openbrace is preceded by a parenthesized exp,
		   ;; move to the beginning of that;
		   ;; possibly a different line
		   (progn
		     (if (eq (preceding-char) ?\))
			 (forward-sexp -1))
		     ;; Get initial indentation of the line we are on.
		     (current-indentation))))))))))
Jim Blandy's avatar
Jim Blandy committed
942 943 944

(defun perl-backward-to-noncomment ()
  "Move point backward to after the first non-white-space, skipping comments."
945
  (interactive)
946
  (forward-comment (- (point-max))))
Jim Blandy's avatar
Jim Blandy committed
947 948 949 950 951 952 953 954 955 956

(defun perl-backward-to-start-of-continued-exp (lim)
  (if (= (preceding-char) ?\))
      (forward-sexp -1))
  (beginning-of-line)
  (if (<= (point) lim)
      (goto-char (1+ lim)))
  (skip-chars-forward " \t\f"))

;; note: this may be slower than the c-mode version, but I can understand it.
957 958
(defalias 'indent-perl-exp 'perl-indent-exp)
(defun perl-indent-exp ()
Jim Blandy's avatar
Jim Blandy committed
959 960 961 962 963 964 965 966 967 968 969 970
  "Indent each line of the Perl grouping following point."
  (interactive)
  (let* ((case-fold-search nil)
	 (oldpnt (point-marker))
	 (bof-mark (save-excursion
		     (end-of-line 2)
		     (perl-beginning-of-function)
		     (point-marker)))
	 eol last-mark lsexp-mark delta)
    (if (= (char-after (marker-position bof-mark)) ?=)
	(message "Can't indent a format statement")
      (message "Indenting Perl expression...")
971
      (setq eol (line-end-position))
Jim Blandy's avatar
Jim Blandy committed
972 973 974 975 976 977 978 979 980
      (save-excursion			; locate matching close paren
	(while (and (not (eobp)) (<= (point) eol))
	  (parse-partial-sexp (point) (point-max) 0))
	(setq last-mark (point-marker)))
      (setq lsexp-mark bof-mark)
      (beginning-of-line)
      (while (< (point) (marker-position last-mark))
	(setq delta (perl-indent-line nil (marker-position bof-mark)))
	(if (numberp delta)		; unquoted start-of-line?
981
	    (progn
Jim Blandy's avatar
Jim Blandy committed
982 983 984 985 986 987 988 989 990 991 992 993
	      (if (eolp)
		  (delete-horizontal-space))
	      (setq lsexp-mark (point-marker))))
	(end-of-line)
	(setq eol (point))
	(if (nth 4 (parse-partial-sexp (marker-position lsexp-mark) eol))
	    (progn			; line ends in a comment
	      (beginning-of-line)
	      (if (or (not (looking-at "\\s-*;?#"))
		      (listp delta)
		      (and (/= 0 delta)
			   (= (- (current-indentation) delta) comment-column)))
994 995
		  (if (and comment-start-skip
			   (re-search-forward comment-start-skip eol t))
Jim Blandy's avatar
Jim Blandy committed
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
		      (indent-for-comment))))) ; indent existing comment
	(forward-line 1))
      (goto-char (marker-position oldpnt))
      (message "Indenting Perl expression...done"))))

(defun perl-beginning-of-function (&optional arg)
  "Move backward to next beginning-of-function, or as far as possible.
With argument, repeat that many times; negative args move forward.
Returns new value of point in all cases."
  (interactive "p")
  (or arg (setq arg 1))
  (if (< arg 0) (forward-char 1))
  (and (/= arg 0)
1009 1010 1011
       (re-search-backward
        "^\\s(\\|^\\s-*sub\\b[ \t\n]*\\_<[^{]+{\\|^\\s-*format\\b[^=]*=\\|^\\."
        nil 'move arg)
Jim Blandy's avatar
Jim Blandy committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
       (goto-char (1- (match-end 0))))
  (point))

;; note: this routine is adapted directly from emacs lisp.el, end-of-defun;
;; no bugs have been removed :-)
(defun perl-end-of-function (&optional arg)
  "Move forward to next end-of-function.
The end of a function is found by moving forward from the beginning of one.
With argument, repeat that many times; negative args move backward."
  (interactive "p")
  (or arg (setq arg 1))
  (let ((first t))
    (while (and (> arg 0) (< (point) (point-max)))
1025
      (let ((pos (point)))
Jim Blandy's avatar
Jim Blandy committed
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
	(while (progn
		(if (and first
			 (progn
			  (forward-char 1)
			  (perl-beginning-of-function 1)
			  (not (bobp))))
		    nil
		  (or (bobp) (forward-char -1))
		  (perl-beginning-of-function -1))
		(setq first nil)
		(forward-list 1)
		(skip-chars-forward " \t")
		(if (looking-at "[#\n]")
		    (forward-line 1))
		(<= (point) pos))))
      (setq arg (1- arg)))
    (while (< arg 0)
      (let ((pos (point)))
	(perl-beginning-of-function 1)
	(forward-sexp 1)
	(forward-line 1)
	(if (>= (point) pos)
	    (if (progn (perl-beginning-of-function 2) (not (bobp)))
		(progn
		  (forward-list 1)
		  (skip-chars-forward " \t")
		  (if (looking-at "[#\n]")
		      (forward-line 1)))
	      (goto-char (point-min)))))
      (setq arg (1+ arg)))))

1057 1058
(defalias 'mark-perl-function 'perl-mark-function)
(defun perl-mark-function ()
Jim Blandy's avatar
Jim Blandy committed
1059 1060 1061 1062 1063 1064 1065 1066
  "Put mark at end of Perl function, point at beginning."
  (interactive)
  (push-mark (point))
  (perl-end-of-function)
  (push-mark (point))
  (perl-beginning-of-function)
  (backward-paragraph))

Richard M. Stallman's avatar
Richard M. Stallman committed
1067 1068 1069
(provide 'perl-mode)

;;; perl-mode.el ends here