xsubpp 1.924
[p5sagit/p5-mst-13.2.git] / emacs / cperl-mode.el
1 ;;; This code started from the following message of long time ago (IZ):
2
3 ;;; From: olson@mcs.anl.gov (Bob Olson)
4 ;;; Newsgroups: comp.lang.perl
5 ;;; Subject: cperl-mode: Another perl mode for Gnuemacs
6 ;;; Date: 14 Aug 91 15:20:01 GMT
7
8 ;; Perl code editing commands for Emacs
9 ;; Copyright (C) 1985, 1986, 1987 Free Software Foundation, Inc.
10
11 ;; This file is not (yet) part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to
25 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
26
27 ;;; Corrections made by Ilya Zakharevich ilya@math.mps.ohio-state.edu
28 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
29
30 ;; $Id: cperl-mode.el,v 1.15 1995/10/07 22:23:37 ilya Exp ilya $
31
32 ;;; To use this mode put the following into your .emacs file:
33
34 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
35
36 ;;; You can either fine-tune the bells and whistles of this mode or
37 ;;; bulk enable them by putting
38
39 ;; (setq cperl-hairy t)
40
41 ;;; in your .emacs file. (Emacs rulers do not consider it politically
42 ;;; correct to make whistles enabled by default.)
43
44 ;;; Additional useful commands to put into your .emacs file:
45
46 ;; (setq auto-mode-alist
47 ;;       (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
48 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
49 ;;                                      '(("miniperl" . perl-mode))))
50
51 ;;; The mode information (on C-h m) provides customization help.
52 ;;; If you use font-lock feature of this mode, it is advisable to use
53 ;;; eather lazy-lock-mode or fast-lock-mode (available on ELisp
54 ;;; archive in files lazy-lock.el and fast-lock.el). I prefer lazy-lock.
55
56 ;;; Faces used now: three faces for first-class and second-class keywords
57 ;;; and control flow words, one for each: comments, string, labels,
58 ;;; functions definitions and packages, arrays, hashes, and variable
59 ;;; definitions. If you do not see all these faces, your font-lock does
60 ;;; not define them, so you need to define them manually. Maybe you have 
61 ;;; an obsolete font-lock from 19.28 or earlier. Upgrade.
62
63 ;;; If you have grayscale monitor, and do not have the variable
64 ;;; font-lock-display-type bound to 'grayscale, insert 
65
66 ;;; (setq font-lock-display-type 'grayscale)
67
68 ;;; to your .emacs file.
69
70 ;;;; This mode supports font-lock, imenu and compile-mode. In the
71 ;;;; hairy version font-lock is on, but you should activate imenu
72 ;;;; yourself (note that compile-mode is not standard yet). Well, you
73 ;;;; can use imenu from keyboard anyway (M-x imenu), but it is better
74 ;;;; to bind it like that:
75
76 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
77
78 ;;; In fact the version of font-lock that this version supports can be
79 ;;; much newer than the version you actually have. This means that a
80 ;;; lot of faces can be set up, but are not visible on your screen
81 ;;; since the coloring rules for this faces are not defined.
82
83 ;;; Tips: ========================================
84
85 ;;; get newest version of this package from
86 ;;; ftp://ftp.math.ohio-state.edu/pub/users/ilya/lisp
87 ;;; and/or
88 ;;; ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
89
90 ;;; Get support packages font-lock-extra.el, imenu-go.el from the same place.
91 ;;; (Look for other files there too... ;-) Get a patch for imenu.el.
92
93 ;;; Get perl5-info from 
94 ;;   http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz
95 ;;; (may be quite obsolete, but still useful).
96
97 ;;; If you use imenu-go, run imenu on perl5-info buffer (can do it from
98 ;;; CPerl menu).
99
100 ;;;; Known problems: ========================================
101
102 ;;; The very new pod
103 ;;; features. The rules are:
104  
105 ;;; /\n=/ should start comment mode, and
106 ;;; /\n=cut\s/ should stop comment mode
107
108 ;;; Expansion of keywords tries to detect this kind of commenting, but
109 ;;; a "=" that starts a perl row (as in multiline comment and here
110 ;;; document) can confuse it.
111  
112 ;;; The main trick (to
113 ;;; make $ a "backslash") makes constructions like ${aaa} look like
114 ;;; unbalanced braces. The only  trick I can think out is to insert it as
115 ;;; $ {aaa} (legal in perl5, not in perl4). 
116
117 ;;;; Known non-problems: ========================================
118
119 ;;; Perl quoting rules are too hard for CPerl. Try to help it: add
120 ;;; comments with embedded quotes to fix CPerl misunderstandings:
121
122 ;;; $a='500$';      # ';
123
124 ;;; You won't need it too often.
125
126 ;;; Now the indentation code is pretty wise. If you still get wrong
127 ;;; indentation in situation that you think the code should be able to
128 ;;; parse, try:
129
130 ;;; a) Check what Emacs thinks about balance of your parentheses.
131 ;;; b) Supply the code to me (IZ).
132
133 ;;; Updates: ========================================
134
135 ;;; Made less hairy by default: parentheses not electric, 
136 ;;; linefeed not magic. Bug with abbrev-mode corrected.
137
138 ;;;; After 1.4:
139 ;;;  Better indentation:
140 ;;;  subs inside braces should work now, 
141 ;;;  Toplevel braces obey customization.
142 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
143 ;;;  moves cursor to a correct place.
144 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-( 
145 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
146 ;;;  Minor documentation fixes.
147 ;;;  Imenu understands packages as prefixes (including nested).
148 ;;;  Hairy options can be switched off one-by-one by setting to null.
149 ;;;  Names of functions and variables changed to conform to `cperl-' style.
150
151 ;;;; After 1.5:
152 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
153 ;;;  `cperl-indent-region' done (slow :-()).
154 ;;;  `cperl-fill-paragraph' done.
155 ;;;  Better package support for `imenu'.
156 ;;;  Progress indicator for indentation (with `imenu' loaded).
157 ;;;  `Cperl-set' was busted, now setting the individual hairy option 
158 ;;;     should be better.
159
160 ;;;; After 1.6:
161 ;;; `cperl-set-style' done.
162 ;;; `cperl-check-syntax' done.
163 ;;; Menu done.
164 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
165 ;;; Bugs with `cperl-auto-newline' corrected.
166 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation 
167 ;;; like $hash{.
168
169 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
170 ;;; - use `next-command-event', if `next-command-events' does not exist
171 ;;; - use `find-face' as def. of `is-face'
172 ;;; - corrected def. of `x-color-defined-p'
173 ;;; - added const defs for font-lock-comment-face,
174 ;;;   font-lock-keyword-face and font-lock-function-name-face
175 ;;; - added def. of font-lock-variable-name-face
176 ;;; - added (require 'easymenu) inside an `eval-when-compile'
177 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
178 ;;;   `define-key's
179 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
180 ;;; Todo (at least):
181 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
182 ;;;   for portable code?
183 ;;; - should `cperl-mode' do a 
184 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
185 ;;;   or should this be left to the user's `cperl-mode-hook'?
186
187 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
188 ;;; Some bugs under XEmacs introduced by the correction corrected.
189
190 ;;; Some more can remain since there are two many different variants. 
191 ;;; Please feedback!
192
193 ;;; We do not support fontification of arrays and hashes under 
194 ;;; obsolete font-lock any more. Upgrade.
195
196 ;;;; after 1.8 Minor bug with parentheses.
197 ;;;; after 1.9 Improvements from Joe Marzot.
198 ;;;; after 1.10
199 ;;;  Does not need easymenu to compile under XEmacs.
200 ;;;  `vc-insert-headers' should work better.
201 ;;;  Should work with 19.29 and 19.12.
202 ;;;  Small improvements to fontification.
203 ;;;  Expansion of keywords does not depend on C-? being backspace.
204
205 ;;; after 1.10+
206 ;;; 19.29 and 19.12 supported.
207 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
208 ;;; Support for font-lock-extra.el.
209
210 ;;;; After 1.11:
211 ;;; Tools submenu.
212 ;;; Support for perl5-info.
213 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
214 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
215 ;;; Fontifies `require a if b;', __DATA__.
216 ;;; Arglist for auto-fill-mode was incorrect.
217
218 ;;;; After 1.12:
219 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions 
220 ;;; vertically.
221 ;;; `cperl-do-auto-fill' updated for 19.29 style.
222 ;;; `cperl-info-on-command' now has a default.
223 ;;; Workaround for broken C-h on XEmacs.
224 ;;; VC strings escaped.
225 ;;; C-h f now may prompt for function name instead of going on,
226 ;;; controlled by `cperl-info-on-command-no-prompt'.
227
228 ;;;; After 1.13:
229 ;;; Msb buffer list includes perl files
230 ;;; Indent-for-comment uses indent-to
231 ;;; Can write tag files using etags.
232
233 ;;;; After 1.14:
234 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
235 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
236
237 (defvar cperl-extra-newline-before-brace nil
238   "*Non-nil means that if, elsif, while, until, else, for, foreach
239 and do constructs look like:
240
241         if ()
242         {
243         }
244
245 instead of:
246
247         if () {
248         }
249 ")
250 (defvar cperl-indent-level 2
251   "*Indentation of CPerl statements with respect to containing block.")
252 (defvar cperl-lineup-step nil
253   "*`cperl-lineup' will always lineup at multiple of this number.
254 If `nil', the value of `cperl-indent-level' will be used.")
255 (defvar cperl-brace-imaginary-offset 0
256   "*Imagined indentation of a Perl open brace that actually follows a statement.
257 An open brace following other text is treated as if it were this far
258 to the right of the start of its line.")
259 (defvar cperl-brace-offset 0
260   "*Extra indentation for braces, compared with other text in same context.")
261 (defvar cperl-label-offset -2
262   "*Offset of CPerl label lines relative to usual indentation.")
263 (defvar cperl-min-label-indent 1
264   "*Minimal offset of CPerl label lines.")
265 (defvar cperl-continued-statement-offset 2
266   "*Extra indent for lines not starting new statements.")
267 (defvar cperl-continued-brace-offset 0
268   "*Extra indent for substatements that start with open-braces.
269 This is in addition to cperl-continued-statement-offset.")
270 (defvar cperl-close-paren-offset -1
271   "*Extra indent for substatements that start with close-parenthesis.")
272
273 (defvar cperl-auto-newline nil
274   "*Non-nil means automatically newline before and after braces,
275 and after colons and semicolons, inserted in CPerl code.")
276
277 (defvar cperl-tab-always-indent t
278   "*Non-nil means TAB in CPerl mode should always reindent the current line,
279 regardless of where in the line point is when the TAB command is used.")
280
281 (defvar cperl-font-lock nil
282   "*Non-nil (and non-null) means CPerl buffers will use font-lock-mode.
283 Can be overwritten by `cperl-hairy' if nil.")
284
285 (defvar cperl-electric-lbrace-space nil
286   "*Non-nil (and non-null) means { after $ in CPerl buffers should be preceeded by ` '.
287 Can be overwritten by `cperl-hairy' if nil.")
288
289 (defvar cperl-electric-parens ""
290   "*List of parentheses that should be electric in CPerl, or null.
291 Can be overwritten by `cperl-hairy' to \"({[<\" if not 'null.")
292
293 (defvar cperl-electric-linefeed nil
294   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
295 In any case these two mean plain and hairy linefeeds together.
296 Can be overwritten by `cperl-hairy' if nil.")
297
298 (defvar cperl-electric-keywords nil
299   "*Not-nil (and non-null) means keywords are electric in CPerl.
300 Can be overwritten by `cperl-hairy' if nil.")
301
302 (defvar cperl-hairy nil
303   "*Not-nil means all the bells and whistles are enabled in CPerl.")
304
305 (defvar cperl-comment-column 32
306   "*Column to put comments in CPerl (use \\[cperl-indent]' to lineup with code).")
307
308 (defvar cperl-vc-header-alist '((SCCS "$sccs = '%W\%' ;")
309                                 (RCS "$rcs = ' $Id\$ ' ;"))
310   "*What to use as `vc-header-alist' in CPerl.")
311
312 (defvar cperl-info-on-command-no-prompt nil
313   "*Not-nil (and non-null) means not to prompt on C-h f.
314 The opposite behaviour is always available if prefixed with C-c.
315 Can be overwritten by `cperl-hairy' if nil.")
316 \f
317
318 ;;; Portability stuff:
319
320 (defsubst cperl-xemacs-p ()
321   (string-match "XEmacs\\|Lucid" emacs-version))
322
323 (defvar del-back-ch (car (append (where-is-internal 'delete-backward-char)
324                                  (where-is-internal 'backward-delete-char-untabify)))
325   "Character generated by key bound to delete-backward-char.")
326
327 (and (vectorp del-back-ch) (= (length del-back-ch) 1) 
328      (setq del-back-ch (aref del-back-ch 0)))
329
330 (if (cperl-xemacs-p)
331     ;; "Active regions" are on: use region only if active
332     ;; "Active regions" are off: use region unconditionally
333     (defun cperl-use-region-p ()
334       (if zmacs-regions (mark) t))
335   (defun cperl-use-region-p ()
336     (if transient-mark-mode mark-active t)))
337
338 (defsubst cperl-enable-font-lock ()
339   (or (cperl-xemacs-p) window-system))
340
341 (if (boundp 'unread-command-events)
342     (if (cperl-xemacs-p)
343         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
344           (setq unread-command-events (list (character-to-event c))))
345       (defun cperl-putback-char (c)     ; Emacs 19
346         (setq unread-command-events (list c))))
347   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
348     (setq unread-command-event (character-to-event c))))
349
350 (or (fboundp 'uncomment-region)
351     (defun uncomment-region (beg end)
352       (interactive "r")
353       (comment-region beg end -1)))
354
355 ;;; Probably it is too late to set these guys already, but it can help later:
356
357 (setq auto-mode-alist
358       (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
359 (and (boundp 'interpreter-mode-alist)
360      (setq interpreter-mode-alist (append interpreter-mode-alist
361                                           '(("miniperl" . perl-mode)))))
362 (if (fboundp 'eval-when-compile)
363     (eval-when-compile
364       (condition-case nil
365           (require 'imenu)
366         (error nil))
367       (condition-case nil
368           (require 'easymenu)
369         (error nil))
370       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
371       ;; macros instead of defsubsts don't work on Emacs, so we do the
372       ;; expansion manually. Any other suggestions?
373       (if (or (string-match "XEmacs\\|Lucid" emacs-version)
374               window-system)
375           (require 'font-lock))
376       (require 'cl)
377       ))
378
379 (defvar cperl-mode-abbrev-table nil
380   "Abbrev table in use in Cperl-mode buffers.")
381
382 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
383
384 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
385
386 (if cperl-mode-map nil
387   (setq cperl-mode-map (make-sparse-keymap))
388   (define-key cperl-mode-map "{" 'cperl-electric-lbrace)
389   (define-key cperl-mode-map "[" 'cperl-electric-paren)
390   (define-key cperl-mode-map "(" 'cperl-electric-paren)
391   (define-key cperl-mode-map "<" 'cperl-electric-paren)
392   (define-key cperl-mode-map "}" 'cperl-electric-brace)
393   (define-key cperl-mode-map ";" 'cperl-electric-semi)
394   (define-key cperl-mode-map ":" 'cperl-electric-terminator)
395   (define-key cperl-mode-map "\C-j" 'newline-and-indent)
396   (define-key cperl-mode-map "\C-c\C-j" 'cperl-linefeed)
397   (define-key cperl-mode-map "\e\C-q" 'cperl-indent-exp) ; Usually not bound
398   ;;(define-key cperl-mode-map "\M-q" 'cperl-fill-paragraph)
399   ;;(define-key cperl-mode-map "\e;" 'cperl-indent-for-comment)
400   (define-key cperl-mode-map "\177" 'backward-delete-char-untabify)
401   (define-key cperl-mode-map "\t" 'cperl-indent-command)
402   (if (cperl-xemacs-p)
403       ;; don't clobber the backspace binding:
404       (define-key cperl-mode-map [(control h) f] 'cperl-info-on-command)
405     (define-key cperl-mode-map "\C-hf" 'cperl-info-on-command))
406   (if (cperl-xemacs-p)
407       ;; don't clobber the backspace binding:
408       (define-key cperl-mode-map [(control c) (control h) f]
409         'cperl-info-on-current-command)
410     (define-key cperl-mode-map "\C-c\C-hf" 'cperl-info-on-current-command))
411   (if (and (cperl-xemacs-p) 
412            (<= emacs-minor-version 11) (<= emacs-major-version 19))
413       (progn
414         ;; substitute-key-definition is usefulness-deenhanced...
415         (define-key cperl-mode-map "\M-q" 'cperl-fill-paragraph)
416         (define-key cperl-mode-map "\e;" 'cperl-indent-for-comment)
417         (define-key cperl-mode-map "\e\C-\\" 'cperl-indent-region))
418     (substitute-key-definition
419      'indent-sexp 'cperl-indent-exp
420      cperl-mode-map global-map)
421     (substitute-key-definition
422      'fill-paragraph 'cperl-fill-paragraph
423      cperl-mode-map global-map)
424     (substitute-key-definition
425      'indent-region 'cperl-indent-region
426      cperl-mode-map global-map)
427     (substitute-key-definition
428      'indent-for-comment 'cperl-indent-for-comment
429      cperl-mode-map global-map)))
430
431 (condition-case nil
432     (progn
433       (require 'easymenu)
434       (easy-menu-define cperl-menu cperl-mode-map "Menu for CPerl mode"
435          '("Perl"
436            ["Beginning of function" beginning-of-defun t]
437            ["End of function" end-of-defun t]
438            ["Mark function" mark-defun t]
439            ["Indent expression" cperl-indent-exp t]
440            ["Fill paragraph/comment" cperl-fill-paragraph t]
441            ["Line up a construction" cperl-lineup (cperl-use-region-p)]
442            "----"
443            ["Indent region" cperl-indent-region (cperl-use-region-p)]
444            ["Comment region" comment-region (cperl-use-region-p)]
445            ["Uncomment region" uncomment-region (cperl-use-region-p)]
446            "----"
447            ["Run" mode-compile (fboundp 'mode-compile)]
448            ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
449                                           (get-buffer "*compilation*"))]
450            ["Next error" next-error (get-buffer "*compilation*")]
451            ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
452            "----"
453            ["Debugger" perldb t]
454            "----"
455            ("Tools"
456             ["Imenu" imenu (fboundp 'imenu)]
457             ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
458             ("Tags"
459              ["Create tags for current file" cperl-etags t]
460              ["Add tags for current file" (cperl-etags t) t]
461              ["Create tags for Perl files in directory" (cperl-etags nil t) t]
462              ["Add tags for Perl files in directory" (cperl-etags t t) t]
463              ["Create tags for Perl files in (sub)directories" 
464               (cperl-etags nil 'recursive) t]
465              ["Add tags for Perl files in (sub)directories"
466               (cperl-etags t 'recursive) t])
467             ["Define word at point" imenu-go-find-at-position 
468              (fboundp 'imenu-go-find-at-position)]
469             ["Help on function" cperl-info-on-command t]
470             ["Help on function at point" cperl-info-on-current-command t])
471            ("Indent styles..."
472             ["GNU" (cperl-set-style "GNU") t]
473             ["C++" (cperl-set-style "C++") t]
474             ["FSF" (cperl-set-style "FSF") t]
475             ["BSD" (cperl-set-style "BSD") t]
476             ["Whitesmith" (cperl-set-style "Whitesmith") t]))))
477   (error nil))
478
479 (autoload 'c-macro-expand "cmacexp"
480   "Display the result of expanding all C macros occurring in the region.
481 The expansion is entirely correct because it uses the C preprocessor."
482   t)
483
484 (defvar cperl-mode-syntax-table nil
485   "Syntax table in use in Cperl-mode buffers.")
486
487 (if cperl-mode-syntax-table
488     ()
489   (setq cperl-mode-syntax-table (make-syntax-table))
490   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
491   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
492   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
493   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
494   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
495   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
496   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
497   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
498   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
499   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
500   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
501   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
502   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
503   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
504   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
505   (modify-syntax-entry ?_ "w" cperl-mode-syntax-table)
506   (modify-syntax-entry ?| "." cperl-mode-syntax-table))
507
508
509 \f
510 ;; Make customization possible "in reverse"
511 ;;(defun cperl-set (symbol to)
512 ;;  (or (eq (symbol-value symbol) 'null) (set symbol to)))
513 (defsubst cperl-val (symbol &optional default hairy)
514   (cond
515    ((eq (symbol-value symbol) 'null) default)
516    (cperl-hairy (or hairy t))
517    (t (symbol-value symbol))))
518 \f
519 ;; provide an alias for working with emacs 19.  the perl-mode that comes
520 ;; with it is really bad, and this lets us seamlessly replace it.
521 (fset 'perl-mode 'cperl-mode)
522 (defun cperl-mode ()
523   "Major mode for editing Perl code.
524 Expression and list commands understand all C brackets.
525 Tab indents for Perl code.
526 Paragraphs are separated by blank lines only.
527 Delete converts tabs to spaces as it moves back.
528
529 Various characters in Perl almost always come in pairs: {}, (), [],
530 sometimes <>. When the user types the first, she gets the second as
531 well, with optional special formatting done on {}.  (Disabled by
532 default.)  You can always quote (with \\[quoted-insert]) the left
533 \"paren\" to avoid the expansion. The processing of < is special,
534 since most the time you mean \"less\". Cperl mode tries to guess
535 whether you want to type pair <>, and inserts is if it
536 appropriate. You can set `cperl-electric-parens' to the string that
537 contains the parenths from the above list you want to be electrical.
538
539 CPerl mode provides expansion of the Perl control constructs:
540    if, else, elsif, unless, while, until, for, and foreach.
541 =========(Disabled by default, see `cperl-electric-keywords'.)
542 The user types the keyword immediately followed by a space, which causes
543 the construct to be expanded, and the user is positioned where she is most
544 likely to want to be.
545 eg. when the user types a space following \"if\" the following appears in
546 the buffer:
547             if () {     or   if ()
548             }                 {
549                               }
550 and the cursor is between the parentheses.  The user can then type some
551 boolean expression within the parens.  Having done that, typing
552 \\[cperl-linefeed] places you, appropriately indented on a new line
553 between the braces. If CPerl decides that you want to insert
554 \"English\" style construct like
555             bite if angry;
556 it will not do any expansion. See also help on variable 
557 `cperl-extra-newline-before-brace'.
558
559 \\[cperl-linefeed] is a convinience replacement for typing carriage
560 return. It places you in the next line with proper indentation, or if
561 you type it inside the inline block of control construct, like
562             foreach (@lines) {print; print}
563 and you are on a boundary of a statement inside braces, it will
564 transform the construct into a multiline and will place you into an
565 apporpriately indented blank line. If you need a usual 
566 `newline-and-indent' behaviour, it is on \\[newline-and-indent], 
567 see documentation on `cperl-electric-linefeed'.
568
569 \\{cperl-mode-map}
570
571 Setting the variable `cperl-font-lock' to t switches on
572 font-lock-mode, `cperl-electric-lbrace-space' to t switches on
573 electric space between $ and {, `cperl-electric-parens' is the string
574 that contains parentheses that should be electric in CPerl, setting
575 `cperl-electric-keywords' enables electric expansion of control
576 structures in CPerl. `cperl-electric-linefeed' governs which one of
577 two linefeed behavior is preferable. You can enable all these options
578 simultaneously (recommended mode of use) by setting `cperl-hairy' to
579 t. In this case you can switch separate options off by setting them 
580 to `null'.
581
582 If your site has perl5 documentation in info format, you can use commands
583 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
584 These keys run commands `cperl-info-on-current-command' and
585 `cperl-info-on-command', which one is which is controlled by variable
586 `cperl-info-on-command-no-prompt' (in turn affected by `cperl-hairy').
587
588 Variables controlling indentation style:
589  `cperl-tab-always-indent'
590     Non-nil means TAB in CPerl mode should always reindent the current line,
591     regardless of where in the line point is when the TAB command is used.
592  `cperl-auto-newline'
593     Non-nil means automatically newline before and after braces,
594     and after colons and semicolons, inserted in Perl code.
595  `cperl-indent-level'
596     Indentation of Perl statements within surrounding block.
597     The surrounding block's indentation is the indentation
598     of the line on which the open-brace appears.
599  `cperl-continued-statement-offset'
600     Extra indentation given to a substatement, such as the
601     then-clause of an if, or body of a while, or just a statement continuation.
602  `cperl-continued-brace-offset'
603     Extra indentation given to a brace that starts a substatement.
604     This is in addition to `cperl-continued-statement-offset'.
605  `cperl-brace-offset'
606     Extra indentation for line if it starts with an open brace.
607  `cperl-brace-imaginary-offset'
608     An open brace following other text is treated as if it the line started
609     this far to the right of the actual line indentation.
610  `cperl-label-offset'
611     Extra indentation for line that is a label.
612  `cperl-min-label-indent'
613     Minimal indentation for line that is a label.
614
615 Settings for K&R and BSD indentation styles are
616   `cperl-indent-level'                5    8
617   `cperl-continued-statement-offset'  5    8
618   `cperl-brace-offset'               -5   -8
619   `cperl-label-offset'               -5   -8
620
621 If `cperl-indent-level' is 0, the statement after opening brace in column 0 is indented on `cperl-brace-offset'+`cperl-continued-statement-offset'.
622
623 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
624 with no args."
625   (interactive)
626   (kill-all-local-variables)
627   ;;(if cperl-hairy
628   ;;    (progn
629   ;;    (cperl-set 'cperl-font-lock cperl-hairy)
630   ;;    (cperl-set 'cperl-electric-lbrace-space cperl-hairy)
631   ;;    (cperl-set 'cperl-electric-parens "{[(<")
632   ;;    (cperl-set 'cperl-electric-keywords cperl-hairy)
633   ;;    (cperl-set 'cperl-electric-linefeed cperl-hairy)))
634   (use-local-map cperl-mode-map)
635   (if (cperl-val 'cperl-electric-linefeed)
636       (progn
637         (local-set-key "\C-J" 'cperl-linefeed)
638         (local-set-key "\C-C\C-J" 'newline-and-indent)))
639   (if (cperl-val 'cperl-info-on-command-no-prompt)
640       (progn
641         (if (cperl-xemacs-p)
642             ;; don't clobber the backspace binding:
643             (local-set-key [(control h) f] 'cperl-info-on-current-command)
644           (local-set-key "\C-hf" 'cperl-info-on-current-command))
645         (if (cperl-xemacs-p)
646             ;; don't clobber the backspace binding:
647             (local-set-key [(control c) (control h) f]
648                            'cperl-info-on-command)
649           (local-set-key "\C-c\C-hf" 'cperl-info-on-command))))
650   (setq major-mode 'perl-mode)
651   (setq mode-name "CPerl")
652   (if (not cperl-mode-abbrev-table)
653       (let ((prev-a-c abbrevs-changed))
654         (define-abbrev-table 'cperl-mode-abbrev-table '(
655                 ("if" "if" cperl-electric-keyword 0)
656                 ("elsif" "elsif" cperl-electric-keyword 0)
657                 ("while" "while" cperl-electric-keyword 0)
658                 ("until" "until" cperl-electric-keyword 0)
659                 ("unless" "unless" cperl-electric-keyword 0)
660                 ("else" "else" cperl-electric-else 0)
661                 ("for" "for" cperl-electric-keyword 0)
662                 ("foreach" "foreach" cperl-electric-keyword 0)
663                 ("do" "do" cperl-electric-keyword 0)))
664         (setq abbrevs-changed prev-a-c)))
665   (setq local-abbrev-table cperl-mode-abbrev-table)
666   (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
667   (set-syntax-table cperl-mode-syntax-table)
668   (make-local-variable 'paragraph-start)
669   (setq paragraph-start (concat "^$\\|" page-delimiter))
670   (make-local-variable 'paragraph-separate)
671   (setq paragraph-separate paragraph-start)
672   (make-local-variable 'paragraph-ignore-fill-prefix)
673   (setq paragraph-ignore-fill-prefix t)
674   (make-local-variable 'indent-line-function)
675   (setq indent-line-function 'cperl-indent-line)
676   (make-local-variable 'require-final-newline)
677   (setq require-final-newline t)
678   (make-local-variable 'comment-start)
679   (setq comment-start "# ")
680   (make-local-variable 'comment-end)
681   (setq comment-end "")
682   (make-local-variable 'comment-column)
683   (setq comment-column cperl-comment-column)
684   (make-local-variable 'comment-start-skip)
685   (setq comment-start-skip "#+ *")
686   (make-local-variable 'defun-prompt-regexp)
687   (setq defun-prompt-regexp "[ \t]*sub\\s +\\([^ \t\n{;]+\\)\\s *")
688   (make-local-variable 'comment-indent-function)
689   (setq comment-indent-function 'cperl-comment-indent)
690   (make-local-variable 'parse-sexp-ignore-comments)
691   (setq parse-sexp-ignore-comments t)
692   (make-local-variable 'indent-region-function)
693   (setq indent-region-function 'cperl-indent-region)
694   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
695   (make-local-variable 'imenu-create-index-function)
696   (setq imenu-create-index-function
697         (function imenu-example--create-perl-index))
698   (make-local-variable 'vc-header-alist)
699   (setq vc-header-alist cperl-vc-header-alist)
700   (or (fboundp 'cperl-old-auto-fill-mode)
701       (progn
702         (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
703         (defun auto-fill-mode (&optional arg)
704           (interactive "P")
705           (cperl-old-auto-fill-mode arg)
706           (and auto-fill-function (eq major-mode 'perl-mode)
707                (setq auto-fill-function 'cperl-do-auto-fill)))))
708   (if (cperl-enable-font-lock)
709       (if (cperl-val 'cperl-font-lock) (font-lock-mode 1)))
710   (and (boundp 'msb-menu-cond)
711        (not cperl-msb-fixed)
712        (cperl-msb-fix))
713   (run-hooks 'cperl-mode-hook))
714 \f
715 ;; Fix for msb.el
716 (defvar cperl-msb-fixed nil)
717
718 (defun cperl-msb-fix ()
719   ;; Adds perl files to msb menu, supposes that msb is already loaded
720   (setq cperl-msb-fixed t)
721   (let* ((l (length msb-menu-cond))
722          (last (nth (1- l) msb-menu-cond))
723          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
724          (handle (1- (nth 1 last))))
725     (setcdr precdr (list
726                     (list
727                      '(eq major-mode 'perl-mode)
728                      handle
729                      "Perl Files (%d)")
730                     last))))
731 \f
732 ;; This is used by indent-for-comment
733 ;; to decide how much to indent a comment in CPerl code
734 ;; based on its context. Do fallback if comment is found wrong.
735
736 (defvar cperl-wrong-comment)
737
738 (defun cperl-comment-indent ()
739   (let ((p (point)) (c (current-column)) was)
740     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
741       ;; Wrong comment found
742       (save-excursion
743         (setq was (cperl-to-comment-or-eol))
744         (if (= (point) p)
745             (progn
746               (skip-chars-backward " \t")
747               (max (1+ (current-column)) ; Else indent at comment column
748                    comment-column))
749           (if was nil
750             (insert comment-start)
751             (backward-char (length comment-start)))
752           (setq cperl-wrong-comment t)
753           (indent-to comment-column 1)  ; Indent minimum 1
754           c)))))                        ; except leave at least one space.
755
756 ;;;(defun cperl-comment-indent-fallback ()
757 ;;;  "Is called if the standard comment-search procedure fails.
758 ;;;Point is at start of real comment."
759 ;;;  (let ((c (current-column)) target cnt prevc)
760 ;;;    (if (= c comment-column) nil
761 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
762 ;;;      (setq target (max (1+ (setq prevc 
763 ;;;                          (current-column))) ; Else indent at comment column
764 ;;;                comment-column))
765 ;;;      (if (= c comment-column) nil
766 ;;;     (delete-backward-char cnt)
767 ;;;     (while (< prevc target)
768 ;;;       (insert "\t")
769 ;;;       (setq prevc (current-column)))
770 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
771 ;;;     (while (< prevc target)
772 ;;;       (insert " ")
773 ;;;       (setq prevc (current-column)))))))
774
775 (defun cperl-indent-for-comment ()
776   "Substite for `indent-for-comment' in CPerl."
777   (interactive)
778   (let (cperl-wrong-comment)
779     (indent-for-comment)
780     (if cperl-wrong-comment
781         (progn (cperl-to-comment-or-eol)
782                (forward-char (length comment-start))))))
783
784 (defun cperl-electric-brace (arg &optional only-before)
785   "Insert character and correct line's indentation.
786 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
787 place (even in empty line), but not after."
788   (interactive "P")
789   (let (insertpos)
790     (if (and (not arg)                  ; No args, end (of empty line or auto)
791              (eolp)
792              (or (and (null only-before)
793                       (save-excursion
794                         (skip-chars-backward " \t")
795                         (bolp)))
796                  (if cperl-auto-newline 
797                      (progn (cperl-indent-line) (newline) t) nil)))
798         (progn
799           (if cperl-auto-newline
800               (setq insertpos (point)))
801           (insert last-command-char)
802           (cperl-indent-line)
803           (if (and cperl-auto-newline (null only-before))
804               (progn
805                 (newline)
806                 (cperl-indent-line)))
807           (save-excursion
808             (if insertpos (progn (goto-char insertpos)
809                                  (search-forward (make-string 
810                                                   1 last-command-char))
811                                  (setq insertpos (1- (point)))))
812             (delete-char -1))))
813     (if insertpos
814         (save-excursion
815           (goto-char insertpos)
816           (self-insert-command (prefix-numeric-value arg)))
817       (self-insert-command (prefix-numeric-value arg)))))
818
819 (defun cperl-electric-lbrace (arg)
820   "Insert character, correct line's indentation, correct quoting by space."
821   (interactive "P")
822   (let (pos after (cperl-auto-newline cperl-auto-newline))
823     (and (cperl-val 'cperl-electric-lbrace-space)
824          (eq (preceding-char) ?$)
825          (save-excursion
826            (skip-chars-backward "$")
827            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
828          (insert ? ))
829     (if (cperl-after-expr) nil (setq cperl-auto-newline nil))
830     (cperl-electric-brace arg)
831     (and (eq last-command-char ?{)
832          (memq last-command-char 
833                (append (cperl-val 'cperl-electric-parens "" "([{<") nil))
834          (setq last-command-char ?} pos (point))
835          (progn (cperl-electric-brace arg t)
836                 (goto-char pos)))))
837
838 (defun cperl-electric-paren (arg)
839   "Insert a matching pair of parentheses."
840   (interactive "P")
841   (let ((beg (save-excursion (beginning-of-line) (point))))
842     (if (and (memq last-command-char
843                    (append (cperl-val 'cperl-electric-parens "" "([{<") nil))
844              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
845              ;;(not (save-excursion (search-backward "#" beg t)))
846              (if (eq last-command-char ?<)
847                  (cperl-after-expr nil "{};(,:=")
848                1))
849         (progn
850           (insert last-command-char)
851           (insert (cdr (assoc last-command-char '((?{ .?})
852                                                   (?[ . ?])
853                                                   (?( . ?))
854                                                   (?< . ?>)))))
855           (forward-char -1))
856       (insert last-command-char)
857       )))
858
859 (defun cperl-electric-keyword ()
860   "Insert a construction appropriate after a keyword."
861   (let ((beg (save-excursion (beginning-of-line) (point))))
862     (and (save-excursion
863            (backward-sexp 1)
864            (cperl-after-expr nil "{};:"))
865          (save-excursion 
866            (not 
867             (re-search-backward
868              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
869              beg t)))
870          (save-excursion (or (not (re-search-backward "^=" nil t))
871                              (looking-at "=cut")))
872          (progn
873            (cperl-indent-line)
874            ;;(insert " () {\n}")
875            (cond
876             (cperl-extra-newline-before-brace
877              (insert " ()\n")
878              (insert "{")
879              (cperl-indent-line)
880              (insert "\n")
881              (cperl-indent-line)
882              (insert "\n}"))
883             (t
884              (insert " () {\n}"))
885             )
886            (or (looking-at "[ \t]\\|$") (insert " "))
887            (cperl-indent-line)
888            (search-backward ")")
889            (cperl-putback-char del-back-ch)))))
890
891 (defun cperl-electric-else ()
892   "Insert a construction appropriate after a keyword."
893   (let ((beg (save-excursion (beginning-of-line) (point))))
894     (and (save-excursion
895            (backward-sexp 1)
896            (cperl-after-expr nil "{};:"))
897          (save-excursion 
898            (not 
899             (re-search-backward
900              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
901              beg t)))
902          (save-excursion (or (not (re-search-backward "^=" nil t))
903                              (looking-at "=cut")))
904          (progn
905            (cperl-indent-line)
906            ;;(insert " {\n\n}")
907            (cond
908             (cperl-extra-newline-before-brace
909              (insert "\n")
910              (insert "{")
911              (cperl-indent-line)
912              (insert "\n\n}"))
913             (t
914              (insert " {\n\n}"))
915             )
916            (or (looking-at "[ \t]\\|$") (insert " "))
917            (cperl-indent-line)
918            (forward-line -1)
919            (cperl-indent-line)
920            (cperl-putback-char del-back-ch)))))
921
922 (defun cperl-linefeed ()
923   "Go to end of line, open a new line and indent appropriately."
924   (interactive)
925   (let ((beg (save-excursion (beginning-of-line) (point)))
926         (end (save-excursion (end-of-line) (point)))
927         (pos (point)) start)
928     (if (and                            ; Check if we need to split:
929                                         ; i.e., on a boundary and inside "{...}" 
930          ;;(not (search-backward "\\(^\\|[^$\\\\]\\)#" beg t))
931          (save-excursion (cperl-to-comment-or-eol)
932            (>= (point) pos))
933          (or (save-excursion
934                (skip-chars-backward " \t" beg)
935                (forward-char -1)
936                (looking-at "[;{]"))
937              (looking-at "[ \t]*}")
938              (re-search-forward "\\=[ \t]*;" end t))
939          (save-excursion
940            (and
941             (eq (car (parse-partial-sexp pos end -1)) -1)
942             (looking-at "[ \t]*\\($\\|#\\)")
943             ;;(setq finish (point-marker))
944             (progn
945               (backward-sexp 1)
946               (setq start (point-marker))
947               (<= start pos))
948             ;;(looking-at "[^{}\n]*}[ \t]*$") ; Will fail if there are intervening {}'s
949             ;;(search-backward "{" beg t)
950             ;;(looking-at "{[^{}\n]*}[ \t]*$")
951             )))
952          ;;(or (looking-at "[ \t]*}")   ; and on a boundary of statements
953          ;;    (save-excursion
954          ;;      (skip-chars-backward " \t")
955          ;;      (forward-char -1)
956          ;;      (looking-at "[{;]"))))
957         (progn
958           (skip-chars-backward " \t")
959           (or (memq (preceding-char) (append ";{" nil))
960               (insert ";"))
961           (insert "\n")
962           (forward-line -1)
963           (cperl-indent-line)
964           ;;(end-of-line)
965           ;;(search-backward "{" beg)
966           (goto-char start)
967           (or (looking-at "{[ \t]*$")   ; If there is a statement
968                                         ; before, move it to separate line
969               (progn
970                 (forward-char 1)
971                 (insert "\n")
972                 (cperl-indent-line)))
973           (forward-line 1)              ; We are on the target line
974           (cperl-indent-line)
975           (beginning-of-line)
976           (or (looking-at "[ \t]*}[ \t]*$") ; If there is a statement
977                                             ; after, move it to separate line
978               (progn
979                 (end-of-line)
980                 (search-backward "}" beg)
981                 (skip-chars-backward " \t")
982                 (or (memq (preceding-char) (append ";{" nil))
983                     (insert ";"))
984                 (insert "\n")
985                 (cperl-indent-line)
986                 (forward-line -1)))
987           (forward-line -1)             ; We are on the line before target 
988           (end-of-line)
989           (newline-and-indent))
990       (end-of-line)                     ; else
991       (if (not (looking-at "\n[ \t]*$"))
992           (newline-and-indent)
993         (forward-line 1)
994         (cperl-indent-line)))))
995
996 (defun cperl-electric-semi (arg)
997   "Insert character and correct line's indentation."
998   (interactive "P")
999   (if cperl-auto-newline
1000       (cperl-electric-terminator arg)
1001     (self-insert-command (prefix-numeric-value arg))))
1002
1003 (defun cperl-electric-terminator (arg)
1004   "Insert character and correct line's indentation."
1005   (interactive "P")
1006   (let (insertpos (end (point)))
1007     (if (and (not arg) (eolp)
1008              (not (save-excursion
1009                     (beginning-of-line)
1010                     (skip-chars-forward " \t")
1011                     (or (= (following-char) ?#)
1012                         ;; Colon is special only after a label, or case ....
1013                         ;; So quickly rule out most other uses of colon
1014                         ;; and do no indentation for them.
1015                         (and (eq last-command-char ?:)
1016                              (not (looking-at "case[ \t]"))
1017                              (save-excursion
1018                                (forward-word 1)
1019                                (skip-chars-forward " \t")
1020                                (and (< (point) end)
1021                                    (progn (goto-char (- end 1))
1022                                           (not (looking-at ":"))))))
1023                         (progn
1024                           (beginning-of-defun)
1025                           (let ((pps (parse-partial-sexp (point) end)))
1026                             (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
1027         (progn
1028           (if cperl-auto-newline
1029               (setq insertpos (point)))
1030           (insert last-command-char)
1031           (cperl-indent-line)
1032           (if cperl-auto-newline
1033               (progn
1034                 (newline)
1035                 (cperl-indent-line)))
1036           (save-excursion
1037             (if insertpos (progn (goto-char insertpos)
1038                                  (search-forward (make-string 
1039                                                   1 last-command-char))
1040                                  (setq insertpos (1- (point)))))
1041             (delete-char -1))))
1042     (if insertpos
1043         (save-excursion
1044           (goto-char insertpos)
1045           (self-insert-command (prefix-numeric-value arg)))
1046       (self-insert-command (prefix-numeric-value arg)))))
1047
1048 (defun cperl-inside-parens-p ()
1049   (condition-case ()
1050       (save-excursion
1051         (save-restriction
1052           (narrow-to-region (point)
1053                             (progn (beginning-of-defun) (point)))
1054           (goto-char (point-max))
1055           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
1056     (error nil)))
1057 \f
1058 (defun cperl-indent-command (&optional whole-exp)
1059   (interactive "P")
1060   "Indent current line as Perl code, or in some cases insert a tab character.
1061 If `cperl-tab-always-indent' is non-nil (the default), always indent current line.
1062 Otherwise, indent the current line only if point is at the left margin
1063 or in the line's indentation; otherwise insert a tab.
1064
1065 A numeric argument, regardless of its value,
1066 means indent rigidly all the lines of the expression starting after point
1067 so that this line becomes properly indented.
1068 The relative indentation among the lines of the expression are preserved."
1069   (if whole-exp
1070       ;; If arg, always indent this line as Perl
1071       ;; and shift remaining lines of expression the same amount.
1072       (let ((shift-amt (cperl-indent-line))
1073             beg end)
1074         (save-excursion
1075           (if cperl-tab-always-indent
1076               (beginning-of-line))
1077           (setq beg (point))
1078           (forward-sexp 1)
1079           (setq end (point))
1080           (goto-char beg)
1081           (forward-line 1)
1082           (setq beg (point)))
1083         (if (> end beg)
1084             (indent-code-rigidly beg end shift-amt "#")))
1085     (if (and (not cperl-tab-always-indent)
1086              (save-excursion
1087                (skip-chars-backward " \t")
1088                (not (bolp))))
1089         (insert-tab)
1090       (cperl-indent-line))))
1091
1092 (defun cperl-indent-line (&optional symbol)
1093   "Indent current line as Perl code.
1094 Return the amount the indentation changed by."
1095   (let (indent
1096         beg shift-amt
1097         (case-fold-search nil)
1098         (pos (- (point-max) (point))))
1099     (setq indent (cperl-calculate-indent nil symbol))
1100     (beginning-of-line)
1101     (setq beg (point))
1102     (cond ((eq indent nil)
1103            (setq indent (current-indentation)))
1104           ;;((eq indent t)    ; Never?
1105           ;; (setq indent (cperl-calculate-indent-within-comment)))
1106           ;;((looking-at "[ \t]*#")
1107           ;; (setq indent 0))
1108           (t
1109            (skip-chars-forward " \t")
1110            (if (listp indent) (setq indent (car indent)))
1111            (cond ((looking-at "[A-Za-z]+:[^:]")
1112                   (and (> indent 0)
1113                        (setq indent (max cperl-min-label-indent
1114                                          (+ indent cperl-label-offset)))))
1115                  ;;((and (looking-at "els\\(e\\|if\\)\\b")
1116                  ;;      (not (looking-at "else\\s_")))
1117                  ;; (setq indent (save-excursion
1118                  ;;              (cperl-backward-to-start-of-if)
1119                  ;;              (current-indentation))))
1120                  ((= (following-char) ?})
1121                   (setq indent (- indent cperl-indent-level)))
1122                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
1123                   (setq indent (+ indent cperl-close-paren-offset)))
1124                  ((= (following-char) ?{)
1125                   (setq indent (+ indent cperl-brace-offset))))))
1126     (skip-chars-forward " \t")
1127     (setq shift-amt (- indent (current-column)))
1128     (if (zerop shift-amt)
1129         (if (> (- (point-max) pos) (point))
1130             (goto-char (- (point-max) pos)))
1131       (delete-region beg (point))
1132       (indent-to indent)
1133       ;; If initial point was within line's indentation,
1134       ;; position after the indentation.  Else stay at same point in text.
1135       (if (> (- (point-max) pos) (point))
1136           (goto-char (- (point-max) pos))))
1137     shift-amt))
1138
1139 (defsubst cperl-after-label ()
1140   ;; Returns true if the point is after label. Does not do save-excursion.
1141   (and (eq (preceding-char) ?:)
1142        (memq (char-syntax (char-after (- (point) 2)))
1143              '(?w ?_))
1144        (progn
1145          (backward-sexp)
1146          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:"))))
1147
1148 (defun cperl-calculate-indent (&optional parse-start symbol)
1149   "Return appropriate indentation for current line as Perl code.
1150 In usual case returns an integer: the column to indent to.
1151 Returns nil if line starts inside a string, t if in a comment."
1152   (save-excursion
1153     (beginning-of-line)
1154     (let ((indent-point (point))
1155           (case-fold-search nil)
1156           (char-after (save-excursion
1157                         (skip-chars-forward " \t")
1158                         (following-char)))
1159           state start-indent start start-state moved
1160           containing-sexp old-containing-sexp old-indent)
1161       (or parse-start (null symbol)
1162           (setq parse-start (symbol-value symbol) 
1163                 start-state (cadr parse-start)
1164                 start-indent (nth 2 parse-start) 
1165                 parse-start (car parse-start)
1166                 old-containing-sexp (nth 1 start-state)))
1167       (if parse-start
1168           (goto-char parse-start)
1169         (beginning-of-defun))
1170       (if start-state nil
1171         ;; Try to go out
1172         (while (< (point) indent-point)
1173           (setq start (point) parse-start start moved nil
1174                 state (parse-partial-sexp start indent-point -1))
1175           (if (> (car state) -1) nil
1176             ;; The current line could start like }}}, so the indentation
1177             ;; corresponds to a different level than what we reached
1178             (setq moved t)
1179             (beginning-of-line 2)))     ; Go to the next line.
1180         (if start                       ; Not at the start of file
1181             (progn
1182               (goto-char start)
1183               (setq start-indent (current-indentation))
1184               (if moved                 ; Should correct...
1185                   (setq start-indent (- start-indent cperl-indent-level))))
1186           (setq start-indent 0)))
1187       (if (< (point) indent-point) (setq parse-start (point)))
1188       (or state (setq state (parse-partial-sexp 
1189                              (point) indent-point -1 nil start-state)))
1190       (setq containing-sexp 
1191             (or (car (cdr state)) 
1192                 (and (>= (nth 6 state) 0) old-containing-sexp))
1193             old-containing-sexp nil start-state nil)
1194 ;;      (while (< (point) indent-point)
1195 ;;      (setq parse-start (point))
1196 ;;      (setq state (parse-partial-sexp (point) indent-point -1 nil start-state))
1197 ;;      (setq containing-sexp 
1198 ;;            (or (car (cdr state)) 
1199 ;;                (and (>= (nth 6 state) 0) old-containing-sexp))
1200 ;;            old-containing-sexp nil start-state nil))
1201       (if symbol (set symbol (list indent-point state start-indent)))
1202       (goto-char indent-point)
1203       (cond ((or (nth 3 state) (nth 4 state))
1204              ;; return nil or t if should not change this line
1205              (nth 4 state))
1206             ((null containing-sexp)
1207              ;; Line is at top level.  May be data or function definition,
1208              ;; or may be function argument declaration.
1209              ;; Indent like the previous top level line
1210              ;; unless that ends in a closeparen without semicolon,
1211              ;; in which case this line is the first argument decl.
1212              (skip-chars-forward " \t")
1213              (+ start-indent
1214                 (if (= (following-char) ?{) cperl-continued-brace-offset 0)
1215                 (progn
1216                   (cperl-backward-to-noncomment (or parse-start (point-min)))
1217                   (skip-chars-backward " \t\f\n")
1218                   ;; Look at previous line that's at column 0
1219                   ;; to determine whether we are in top-level decls
1220                   ;; or function's arg decls.  Set basic-indent accordingly.
1221                   ;; Now add a little if this is a continuation line.
1222                   (if (or (bobp)
1223                           (memq (preceding-char) (append ");}" nil))
1224                           (memq char-after (append ")]}" nil))) 
1225                       0
1226                     cperl-continued-statement-offset))))
1227             ((/= (char-after containing-sexp) ?{)
1228              ;; line is expression, not statement:
1229              ;; indent to just after the surrounding open.
1230              (goto-char (1+ containing-sexp))
1231              (current-column))
1232             ((progn
1233               ;; Containing-expr starts with \{. Check whether it is a hash.
1234               (goto-char containing-sexp)
1235               (cperl-backward-to-noncomment (or parse-start (point-min)))
1236               (skip-chars-backward " \t\n\f")
1237               (not 
1238                (or (memq (preceding-char) (append ";)}$@&%" nil)) ; Or label!
1239                                         ; Label may be mixed up with `$blah :'
1240                    (save-excursion (cperl-after-label))
1241                    (and (eq (char-syntax (preceding-char)) ?w)
1242                     (progn
1243                      (backward-sexp)
1244                      (or (looking-at "\\sw+[ \t\n\f]*{") ; Method call syntax
1245                          (progn
1246                            (skip-chars-backward " \t\n\f")
1247                            (and (eq (char-syntax (preceding-char)) ?w)
1248                                 (progn
1249                                   (backward-sexp)
1250                                   (looking-at 
1251                                    "sub[ \t]+\\sw+[ \t\n\f]*{"))))))))))
1252              (goto-char containing-sexp)
1253              (+ (current-column) 1      ; Correct indentation of trailing ?\}
1254                 (if (eq char-after ?\}) (+ cperl-indent-level
1255                                            cperl-close-paren-offset) 
1256                   0)))
1257             (t
1258              ;; Statement level.  Is it a continuation or a new statement?
1259              ;; Find previous non-comment character.
1260              (goto-char indent-point)
1261              (cperl-backward-to-noncomment containing-sexp)
1262              ;; Back up over label lines, since they don't
1263              ;; affect whether our line is a continuation.
1264              (while (or (eq (preceding-char) ?\,)
1265                         (and (eq (preceding-char) ?:)
1266                              (or ;;(eq (char-after (- (point) 2)) ?\') ; ????
1267                                  (memq (char-syntax (char-after (- (point) 2)))
1268                                        '(?w ?_)))))
1269                (if (eq (preceding-char) ?\,)
1270                    (cperl-backward-to-start-of-continued-exp containing-sexp))
1271                (beginning-of-line)
1272                (cperl-backward-to-noncomment containing-sexp))
1273              ;; Now we get the answer.
1274              (if (not (memq (preceding-char) (append ",;}{" '(nil)))) ; Was ?\,
1275                  ;; This line is continuation of preceding line's statement;
1276                  ;; indent  `cperl-continued-statement-offset'  more than the
1277                  ;; previous line of the statement.
1278                  (progn
1279                    (cperl-backward-to-start-of-continued-exp containing-sexp)
1280                    (+ (if (memq char-after (append "}])" nil))
1281                           0 ; Closing parenth
1282                           cperl-continued-statement-offset)
1283                       (current-column)
1284                       (if (eq char-after ?\{)
1285                           cperl-continued-brace-offset 0)))
1286                ;; This line starts a new statement.
1287                ;; Position following last unclosed open.
1288                (goto-char containing-sexp)
1289                ;; Is line first statement after an open-brace?
1290                (or
1291                 ;; If no, find that first statement and indent like
1292                 ;; it.  If the first statement begins with label, do
1293                 ;; not belive when the indentation of the label is too
1294                 ;; small.
1295                 (save-excursion
1296                   (forward-char 1)
1297                   (setq old-indent (current-indentation))
1298                   (let ((colon-line-end 0))
1299                     (while (progn (skip-chars-forward " \t\n")
1300                                   (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]"))
1301                       ;; Skip over comments and labels following openbrace.
1302                       (cond ((= (following-char) ?\#)
1303                              (forward-line 1))
1304                             ;; label:
1305                             (t
1306                              (save-excursion (end-of-line)
1307                                              (setq colon-line-end (point)))
1308                              (search-forward ":"))))
1309                     ;; The first following code counts
1310                     ;; if it is before the line we want to indent.
1311                     (and (< (point) indent-point)
1312                          (if (> colon-line-end (point)) ; After label
1313                              (if (> (current-indentation) 
1314                                     cperl-min-label-indent)
1315                                  (- (current-indentation) cperl-label-offset)
1316                                ;; Do not belive: `max' is involved
1317                                (+ old-indent cperl-indent-level))
1318                            (current-column)))))
1319                 ;; If no previous statement,
1320                 ;; indent it relative to line brace is on.
1321                 ;; For open brace in column zero, don't let statement
1322                 ;; start there too.  If cperl-indent-level is zero,
1323                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
1324                 ;; For open-braces not the first thing in a line,
1325                 ;; add in cperl-brace-imaginary-offset.
1326
1327                 ;; If first thing on a line:  ?????
1328                 (+ (if (and (bolp) (zerop cperl-indent-level))
1329                        (+ cperl-brace-offset cperl-continued-statement-offset)
1330                      cperl-indent-level)
1331                    ;; Move back over whitespace before the openbrace.
1332                    ;; If openbrace is not first nonwhite thing on the line,
1333                    ;; add the cperl-brace-imaginary-offset.
1334                    (progn (skip-chars-backward " \t")
1335                           (if (bolp) 0 cperl-brace-imaginary-offset))
1336                    ;; If the openbrace is preceded by a parenthesized exp,
1337                    ;; move to the beginning of that;
1338                    ;; possibly a different line
1339                    (progn
1340                      (if (eq (preceding-char) ?\))
1341                          (forward-sexp -1))
1342                      ;; Get initial indentation of the line we are on.
1343                      ;; If line starts with label, calculate label indentation
1344                      (if (save-excursion
1345                            (beginning-of-line)
1346                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_]*:[^:]"))
1347                          (if (> (current-indentation) cperl-min-label-indent)
1348                              (- (current-indentation) cperl-label-offset)
1349                            (cperl-calculate-indent 
1350                             (if (<= parse-start (point)) parse-start)))
1351                        (current-indentation)))))))))))
1352
1353 (defvar cperl-indent-alist
1354   '((string nil)
1355     (comment nil)
1356     (toplevel 0)
1357     (toplevel-after-parenth 2)
1358     (toplevel-continued 2)
1359     (expression 1))
1360   "Alist of indentation rules for CPerl mode.
1361 The values mean:
1362   nil: do not indent;
1363   number: add this amount of indentation.")
1364
1365 (defun cperl-where-am-i (&optional parse-start start-state)
1366   ;; Unfinished
1367   "Return a list (TYPE POS) of the start of enclosing construction.
1368 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'."
1369   (save-excursion
1370     (let ((start-point (point))
1371           (case-fold-search nil)
1372           state start-indent start moved
1373           containing-sexp old-containing-sexp old-indent)
1374       (if parse-start
1375           (goto-char parse-start)
1376         (beginning-of-defun))
1377       (if start-state nil
1378         ;; Try to go out, if sub is not on the outermost level
1379         (while (< (point) start-point)
1380           (setq start (point) parse-start start moved nil
1381                 state (parse-partial-sexp start start-point -1))
1382           (if (> (car state) -1) nil
1383             ;; The current line could start like }}}, so the indentation
1384             ;; corresponds to a different level than what we reached
1385             (setq moved t)
1386             (beginning-of-line 2)))     ; Go to the next line.
1387         (if start (goto-char start)))   ; Not at the start of file
1388       (skip-chars-forward " \t")
1389       (setq start (point))
1390       (if (< (point) start-point) (setq parse-start (point)))
1391       (or state (setq state (parse-partial-sexp 
1392                              (point) start-point -1 nil start-state)))
1393       (setq containing-sexp 
1394             (or (car (cdr state)) 
1395                 (and (>= (nth 6 state) 0) old-containing-sexp))
1396             old-containing-sexp nil start-state nil)
1397 ;;      (while (< (point) start-point)
1398 ;;      (setq parse-start (point))
1399 ;;      (setq state (parse-partial-sexp (point) start-point -1 nil start-state))
1400 ;;      (setq containing-sexp 
1401 ;;            (or (car (cdr state)) 
1402 ;;                (and (>= (nth 6 state) 0) old-containing-sexp))
1403 ;;            old-containing-sexp nil start-state nil))
1404       (goto-char start-point)
1405       (cond ((nth 3 state)              ; In string
1406              (list 'string nil (nth 3 state))) ; What started string
1407             ((nth 4 state)              ; In comment
1408              '(comment))
1409             ((null containing-sexp)
1410              ;; Line is at top level.  
1411              ;; Indent like the previous top level line
1412              ;; unless that ends in a closeparen without semicolon,
1413              ;; in which case this line is the first argument decl.
1414              (cperl-backward-to-noncomment (or parse-start (point-min)))
1415              (skip-chars-backward " \t\f\n") ; Why???
1416              (cond
1417               ((or (bobp)
1418                    (memq (preceding-char) (append ";}" nil)))
1419                (list 'toplevel start))
1420               ((eq (preceding-char) ?\) )
1421                (list 'toplevel-after-parenth start))
1422               (t (list 'toplevel-continued start))))
1423             ((/= (char-after containing-sexp) ?{)
1424              ;; line is expression, not statement:
1425              ;; indent to just after the surrounding open.
1426              (list 'expression containing-sexp))
1427             ((progn
1428               ;; Containing-expr starts with \{. Check whether it is a hash.
1429               (goto-char containing-sexp)
1430               (cperl-backward-to-noncomment (or parse-start (point-min)))
1431               (skip-chars-backward " \t\n\f")
1432               (not 
1433                (or (memq (preceding-char) (append ";)}$@&%" nil)) ; Or label!
1434                                         ; Label may be mixed up with `$blah :'
1435                    (save-excursion (cperl-after-label))
1436                    (and (eq (char-syntax (preceding-char)) ?w)
1437                     (progn
1438                      (backward-sexp)
1439                      (looking-at "\\sw+[ \t\n\f]*{")))))) ; Method call syntax
1440              (list 'expression containing-sexp))
1441             (t
1442              ;; Statement level.  Is it a continuation or a new statement?
1443              ;; Find previous non-comment character.
1444              (cperl-backward-to-noncomment containing-sexp)
1445              ;; Back up over label lines, since they don't
1446              ;; affect whether our line is a continuation.
1447              (while (or (eq (preceding-char) ?\,)
1448                         (cperl-after-label))
1449                (if (eq (preceding-char) ?\,)
1450                    (cperl-backward-to-start-of-continued-exp containing-sexp))
1451                (beginning-of-line)
1452                (cperl-backward-to-noncomment containing-sexp))
1453              ;; Now we get the answer.
1454              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
1455                  ;; This line is continuation of preceding line's statement.
1456                  '(statement-continued containing-sexp)
1457                ;; This line starts a new statement.
1458                ;; Position following last unclosed open.
1459                (goto-char containing-sexp)
1460                ;; Is line first statement after an open-brace?
1461                (or
1462                 ;; If no, find that first statement and indent like
1463                 ;; it.  If the first statement begins with label, do
1464                 ;; not belive when the indentation of the label is too
1465                 ;; small.
1466                 (save-excursion
1467                   (forward-char 1)
1468                   (setq old-indent (current-indentation))
1469                   (let ((colon-line-end 0))
1470                     (while (progn (skip-chars-forward " \t\n")
1471                                   (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]"))
1472                       ;; Skip over comments and labels following openbrace.
1473                       (cond ((= (following-char) ?\#)
1474                              (forward-line 1))
1475                             ;; label:
1476                             (t
1477                              (save-excursion (end-of-line)
1478                                              (setq colon-line-end (point)))
1479                              (search-forward ":"))))
1480                     ;; The first following code counts
1481                     ;; if it is before the line we want to indent.
1482                     (and (< (point) start-point)
1483                          (if (> colon-line-end (point)) ; After label
1484                              (if (> (current-indentation) 
1485                                     cperl-min-label-indent)
1486                                  (- (current-indentation) cperl-label-offset)
1487                                ;; Do not belive: `max' is involved
1488                                (+ old-indent cperl-indent-level))
1489                            (current-column)))))
1490                 ;; If no previous statement,
1491                 ;; indent it relative to line brace is on.
1492                 ;; For open brace in column zero, don't let statement
1493                 ;; start there too.  If cperl-indent-level is zero,
1494                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
1495                 ;; For open-braces not the first thing in a line,
1496                 ;; add in cperl-brace-imaginary-offset.
1497
1498                 ;; If first thing on a line:  ?????
1499                 (+ (if (and (bolp) (zerop cperl-indent-level))
1500                        (+ cperl-brace-offset cperl-continued-statement-offset)
1501                      cperl-indent-level)
1502                    ;; Move back over whitespace before the openbrace.
1503                    ;; If openbrace is not first nonwhite thing on the line,
1504                    ;; add the cperl-brace-imaginary-offset.
1505                    (progn (skip-chars-backward " \t")
1506                           (if (bolp) 0 cperl-brace-imaginary-offset))
1507                    ;; If the openbrace is preceded by a parenthesized exp,
1508                    ;; move to the beginning of that;
1509                    ;; possibly a different line
1510                    (progn
1511                      (if (eq (preceding-char) ?\))
1512                          (forward-sexp -1))
1513                      ;; Get initial indentation of the line we are on.
1514                      ;; If line starts with label, calculate label indentation
1515                      (if (save-excursion
1516                            (beginning-of-line)
1517                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_]*:[^:]"))
1518                          (if (> (current-indentation) cperl-min-label-indent)
1519                              (- (current-indentation) cperl-label-offset)
1520                            (cperl-calculate-indent 
1521                             (if (<= parse-start (point)) parse-start)))
1522                        (current-indentation)))))))))))
1523
1524 (defun cperl-calculate-indent-within-comment ()
1525   "Return the indentation amount for line, assuming that
1526 the current line is to be regarded as part of a block comment."
1527   (let (end star-start)
1528     (save-excursion
1529       (beginning-of-line)
1530       (skip-chars-forward " \t")
1531       (setq end (point))
1532       (and (= (following-char) ?#)
1533            (forward-line -1)
1534            (cperl-to-comment-or-eol)
1535            (setq end (point)))
1536       (goto-char end)
1537       (current-column))))
1538
1539
1540 (defun cperl-to-comment-or-eol ()
1541   "Goes to position before comment on the current line, or to end of line.
1542 Returns true if comment is found."
1543   (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
1544       (beginning-of-line)
1545       (if (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t) 
1546           (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
1547         ;; Else
1548         (while (not stop-in)
1549           (setq state (parse-partial-sexp (point) lim nil nil nil t))
1550                                         ; stop at comment
1551           ;; If fails (beginning-of-line inside sexp), then contains not-comment
1552           ;; Do simplified processing
1553           ;;(if (re-search-forward "[^$]#" lim 1)
1554           ;;      (progn
1555           ;;    (forward-char -1)
1556           ;;    (skip-chars-backward " \t\n\f" lim))
1557           ;;    (goto-char lim))                ; No `#' at all
1558           ;;)
1559           (if (nth 4 state)             ; After `#';
1560                                         ; (nth 2 state) can be
1561                                         ; beginning of m,s,qq and so
1562                                         ; on
1563               (if (nth 2 state)
1564                   (progn
1565                     (setq cpoint (point))
1566                     (goto-char (nth 2 state))
1567                     (cond
1568                      ((looking-at "\\(s\\|tr\\)\\>")
1569                       (or (re-search-forward
1570                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
1571                            lim 'move)
1572                           (setq stop-in t)))
1573                      ((looking-at "\\(m\\|q\\([qxw]\\)?\\)\\>")
1574                       (or (re-search-forward
1575                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
1576                            lim 'move)
1577                           (setq stop-in t)))
1578                      (t                 ; It was fair comment
1579                       (setq stop-in t)  ; Finish
1580                       (goto-char (1- cpoint)))))
1581                 (setq stop-in t)        ; Finish
1582                 (forward-char -1))
1583             (setq stop-in t))           ; Finish
1584           )
1585         (nth 4 state))))
1586
1587 (defun cperl-backward-to-noncomment (lim) 
1588   (let (stop p)
1589     (while (and (not stop) (> (point) (or lim 1)))
1590       (skip-chars-backward " \t\n\f" lim)
1591       (setq p (point))
1592       (beginning-of-line)
1593       (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
1594         ;; Else
1595         (cperl-to-comment-or-eol) 
1596         (skip-chars-backward " \t")
1597         (if (< p (point)) (goto-char p))
1598         (setq stop t)))))
1599
1600 (defun cperl-after-expr (&optional lim chars test)
1601   "Returns true if the position is good for start of expression.
1602 TEST is the expression to evaluate at the found position. If absent,
1603 CHARS is a string that contains good characters to have before us."
1604   (let (stop p)
1605     (save-excursion
1606       (while (and (not stop) (> (point) (or lim 1)))
1607         (skip-chars-backward " \t\n\f" lim)
1608         (setq p (point))
1609         (beginning-of-line)
1610         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
1611           ;; Else: last iteration (What to do with labels?)
1612           (cperl-to-comment-or-eol) 
1613           (skip-chars-backward " \t")
1614           (if (< p (point)) (goto-char p))
1615           (setq stop t)))
1616       (or (bobp)
1617           (progn
1618             (backward-char 1)
1619             (if test (eval test)
1620               (memq (following-char) (append (or chars "{};") nil))))))))
1621
1622 (defun cperl-backward-to-start-of-continued-exp (lim)
1623   (if (memq (preceding-char) (append ")]}" nil))
1624       (forward-sexp -1))
1625   (beginning-of-line)
1626   (if (<= (point) lim)
1627       (goto-char (1+ lim)))
1628   (skip-chars-forward " \t"))
1629
1630 (defun cperl-backward-to-start-of-if (&optional limit)
1631   "Move to the start of the last ``unbalanced'' if."
1632   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
1633   (let ((if-level 1)
1634         (case-fold-search nil))
1635     (while (not (zerop if-level))
1636       (backward-sexp 1)
1637       (cond ((looking-at "else\\b")
1638              (setq if-level (1+ if-level)))
1639             ((looking-at "if\\b")
1640              (setq if-level (1- if-level)))
1641             ((<= (point) limit)
1642              (setq if-level 0)
1643              (goto-char limit))))))
1644
1645
1646 \f
1647 (defvar innerloop-done nil)
1648 (defvar last-depth nil)
1649
1650 (defun cperl-indent-exp ()
1651   "Simple variant of indentation of continued-sexp.
1652 Should be slow. Will not indent comment if it starts at `comment-indent'
1653 or looks like continuation of the comment on the previous line."
1654   (interactive)
1655   (save-excursion
1656     (let ((tmp-end (progn (end-of-line) (point))) top done)
1657       (save-excursion
1658         (while (null done)
1659           (beginning-of-line)
1660           (setq top (point))
1661           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
1662                                                -1)) -1)
1663             (setq top (point)))         ; Get the outermost parenths in line
1664           (goto-char top)
1665           (while (< (point) tmp-end)
1666             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
1667             (or (eolp) (forward-sexp 1)))
1668           (if (> (point) tmp-end) (progn (end-of-line) (setq tmp-end (point)))
1669             (setq done t)))
1670         (goto-char tmp-end)
1671         (setq tmp-end (point-marker)))
1672       (cperl-indent-region (point) tmp-end))))
1673
1674 (defun cperl-indent-region (start end)
1675   "Simple variant of indentation of region in CPerl mode.
1676 Should be slow. Will not indent comment if it starts at `comment-indent' 
1677 or looks like continuation of the comment on the previous line.
1678 Indents all the lines whose first character is between START and END 
1679 inclusive."
1680   (interactive "r")
1681   (save-excursion
1682     (let (st comm indent-info old-comm-indent new-comm-indent 
1683              (pm 0) (imenu-scanning-message "Indenting... (%3d%%)"))
1684       (goto-char start)
1685       (setq old-comm-indent (and (cperl-to-comment-or-eol)
1686                                  (current-column))
1687             new-comm-indent old-comm-indent)
1688       (goto-char start)
1689       (or (bolp) (beginning-of-line 2))
1690       (or (fboundp 'imenu-progress-message)
1691           (message "Indenting... For feedback load `imenu'..."))
1692       (while (and (<= (point) end) (not (eobp))) ; bol to check start
1693         (and (fboundp 'imenu-progress-message)
1694              (imenu-progress-message 
1695               pm (/ (* 100 (- (point) start)) (- end start -1))))
1696         (setq st (point) 
1697               indent-info nil
1698               ) ; Believe indentation of the current
1699         (if (and (setq comm (looking-at "[ \t]*#"))
1700                  (or (eq (current-indentation) (or old-comm-indent 
1701                                                    comment-column))
1702                      (setq old-comm-indent nil)))
1703             (if (and old-comm-indent
1704                      (= (current-indentation) old-comm-indent))
1705                 (let ((comment-column new-comm-indent))
1706                   (indent-for-comment)))
1707           (progn 
1708             (cperl-indent-line 'indent-info)
1709             (or comm
1710                 (progn
1711                   (if (setq old-comm-indent (and (cperl-to-comment-or-eol)
1712                                                  (current-column)))
1713                       (progn (indent-for-comment)
1714                              (skip-chars-backward " \t")
1715                              (skip-chars-backward "#")
1716                              (setq new-comm-indent (current-column))))))))
1717         (beginning-of-line 2))
1718         (if (fboundp 'imenu-progress-message)
1719              (imenu-progress-message pm 100)
1720           (message nil)))))
1721
1722 (defun cperl-slash-is-regexp (&optional pos)
1723   (save-excursion
1724     (goto-char (if pos pos (1- (point))))
1725     (and
1726      (not (memq (get-text-property (point) 'face)
1727                 '(font-lock-string-face font-lock-comment-face)))
1728      (cperl-after-expr nil nil '
1729                        (or (looking-at "[^]a-zA-Z0-9_)}]")
1730                            (eq (get-text-property (point) 'face)
1731                                'font-lock-keyword-face))))))
1732
1733 ;; Stolen from lisp-mode with a lot of improvements
1734
1735 (defun cperl-fill-paragraph (&optional justify iteration)
1736   "Like \\[fill-paragraph], but handle CPerl comments.
1737 If any of the current line is a comment, fill the comment or the
1738 block of it that point is in, preserving the comment's initial
1739 indentation and initial hashes. Behaves usually outside of comment."
1740   (interactive "P")
1741   (let (
1742         ;; Non-nil if the current line contains a comment.
1743         has-comment
1744
1745         ;; If has-comment, the appropriate fill-prefix for the comment.
1746         comment-fill-prefix
1747         ;; Line that contains code and comment (or nil)
1748         start
1749         c spaces len dc (comment-column comment-column))
1750     ;; Figure out what kind of comment we are looking at.
1751     (save-excursion
1752       (beginning-of-line)
1753       (cond
1754
1755        ;; A line with nothing but a comment on it?
1756        ((looking-at "[ \t]*#[# \t]*")
1757         (setq has-comment t
1758               comment-fill-prefix (buffer-substring (match-beginning 0)
1759                                                     (match-end 0))))
1760
1761        ;; A line with some code, followed by a comment?  Remember that the
1762        ;; semi which starts the comment shouldn't be part of a string or
1763        ;; character.
1764        ((cperl-to-comment-or-eol)
1765         (setq has-comment t)
1766         (looking-at "#+[ \t]*")
1767         (setq start (point) c (current-column) 
1768               comment-fill-prefix
1769               (concat (make-string (current-column) ?\ )
1770                       (buffer-substring (match-beginning 0) (match-end 0)))
1771               spaces (progn (skip-chars-backward " \t") 
1772                             (buffer-substring (point) start))
1773               dc (- c (current-column)) len (- start (point)) 
1774               start (point-marker))
1775         (delete-char len)
1776         (insert (make-string dc ?-)))))
1777     (if (not has-comment)
1778         (fill-paragraph justify)        ; Do the usual thing outside of comment
1779       ;; Narrow to include only the comment, and then fill the region.
1780       (save-restriction
1781         (narrow-to-region
1782          ;; Find the first line we should include in the region to fill.
1783          (if start (progn (beginning-of-line) (point))
1784            (save-excursion
1785              (while (and (zerop (forward-line -1))
1786                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n]")))
1787              ;; We may have gone to far.  Go forward again.
1788              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n]")
1789                  (forward-line 1))
1790              (point)))
1791          ;; Find the beginning of the first line past the region to fill.
1792          (save-excursion
1793            (while (progn (forward-line 1)
1794                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n]")))
1795            (point)))
1796         ;; Remove existing hashes
1797         (goto-char (point-min))
1798         (while (progn (forward-line 1) (< (point) (point-max)))
1799           (skip-chars-forward " \t")
1800           (and (looking-at "#+") 
1801                (delete-char (- (match-end 0) (match-beginning 0)))))
1802
1803         ;; Lines with only hashes on them can be paragraph boundaries.
1804         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
1805               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
1806               (fill-prefix comment-fill-prefix))
1807           (fill-paragraph justify)))
1808       (if (and start)
1809           (progn 
1810             (goto-char start)
1811             (if (> dc 0)
1812               (progn (delete-char dc) (insert spaces)))
1813             (if (or (= (current-column) c) iteration) nil
1814               (setq comment-column c)
1815               (indent-for-comment)
1816               ;; Repeat once more, flagging as iteration
1817               (cperl-fill-paragraph justify t)))))))
1818
1819 (defun cperl-do-auto-fill ()
1820   ;; Break out if the line is short enough
1821   (if (> (save-excursion
1822            (end-of-line)
1823            (current-column))
1824          fill-column)
1825   (let ((c (save-excursion (beginning-of-line)
1826                            (cperl-to-comment-or-eol) (point)))
1827         (s (memq (following-char) '(?\ ?\t))) marker)
1828     (if (>= c (point)) nil
1829       (setq marker (point-marker))
1830       (cperl-fill-paragraph)
1831       (goto-char marker)
1832       ;; Is not enough, sometimes marker is a start of line
1833       (if (bolp) (progn (re-search-forward "#+[ \t]*") 
1834                         (goto-char (match-end 0))))
1835       ;; Following space could have gone:
1836       (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
1837         (insert " ")
1838         (backward-char 1))
1839       ;; Previous space could have gone:
1840       (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
1841
1842 (defvar imenu-example--function-name-regexp-perl
1843       "^[ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*")
1844
1845 (defun imenu-example--create-perl-index (&optional regexp)
1846   (require 'cl)
1847   (let ((index-alist '()) (index-pack-alist '()) packages ends-ranges p
1848         (prev-pos 0) char fchar index name (end-range 0) package)
1849     (goto-char (point-min))
1850     (imenu-progress-message prev-pos 0)
1851     ;; Search for the function
1852     (save-match-data
1853       (while (re-search-forward
1854               (or regexp imenu-example--function-name-regexp-perl)
1855               nil t)
1856         (imenu-progress-message prev-pos)
1857         ;;(backward-up-list 1)
1858         (save-excursion
1859           (goto-char (match-beginning 1))
1860           (setq fchar (following-char))
1861           )
1862         (setq char (following-char))
1863         (setq p (point))
1864         (while (and ends-ranges (>= p (car ends-ranges)))
1865                 ;; delete obsolete entries
1866                 (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
1867         (setq package (or (car packages) "")
1868               end-range (or (car ends-ranges) 0))
1869         (if (eq fchar ?p)
1870             (progn 
1871               (setq name (buffer-substring (match-beginning 2) (match-end 2))
1872                     package (concat name "::") 
1873                     name (concat "package " name)
1874                     end-range 
1875                     (save-excursion
1876                       (parse-partial-sexp (point) (point-max) -1) (point))
1877                     ends-ranges (cons end-range ends-ranges)
1878                     packages (cons package packages))))
1879         ;;   )
1880         ;; Skip this function name if it is a prototype declaration.
1881         (if (and (eq fchar ?s) (eq char ?\;)) nil
1882           (if (eq fchar ?p) nil
1883             (setq name (buffer-substring (match-beginning 2) (match-end 2)))
1884             (if (or (> p end-range) (string-match "[:']" name)) nil
1885               (setq name (concat package name))))
1886           (setq index (imenu-example--name-and-position))
1887           (setcar index name)
1888           (if (eq fchar ?p) 
1889             (push index index-pack-alist)
1890             (push index index-alist)))))
1891     (imenu-progress-message prev-pos 100)
1892     (and index-pack-alist
1893          (push (cons (imenu-create-submenu-name "Packages") index-pack-alist)
1894                index-alist))
1895     (nreverse index-alist)))
1896
1897 (defvar cperl-compilation-error-regexp-alist 
1898   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
1899   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
1900      2 3))
1901   "Alist that specifies how to match errors in perl output.")
1902
1903 (if (fboundp 'eval-after-load)
1904     (eval-after-load
1905      "mode-compile"
1906      '(setq perl-compilation-error-regexp-alist
1907            cperl-compilation-error-regexp-alist)))
1908
1909
1910 (defvar cperl-faces-init nil)
1911
1912 (defun cperl-windowed-init ()
1913   "Initialization under windowed version."
1914   (add-hook 'font-lock-mode-hook
1915             (function
1916              (lambda ()
1917                (if (or
1918                     (eq major-mode 'perl-mode)
1919                     (eq major-mode 'cperl-mode))
1920                    (progn
1921                      (or cperl-faces-init (cperl-init-faces))
1922                      (setq font-lock-keywords perl-font-lock-keywords
1923                            cperl-faces-init t)))))))
1924
1925 (defun cperl-init-faces ()
1926   (condition-case nil
1927       (progn
1928         (require 'font-lock)
1929         (let (t-font-lock-keywords)
1930           ;;(defvar cperl-font-lock-enhanced nil
1931           ;;  "Set to be non-nil if font-lock allows active highlights.")
1932           (setq 
1933            t-font-lock-keywords
1934            (list
1935             (cons
1936              (concat
1937               "\\(^\\|[^$@%&\\]\\)\\<\\("
1938               (mapconcat
1939                'identity
1940                '("if" "until" "while" "elsif" "else" "unless" "for"
1941                  "foreach" "continue" "exit" "die" "last" "goto" "next"
1942                  "redo" "return" "local" "exec" "sub" "do" "dump" "use"
1943                  "require" "package" "eval" "my" "BEGIN" "END")
1944                "\\|")                   ; Flow control
1945               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
1946                                         ; In what follows we use `type' style
1947                                         ; for overwritable buildins
1948             (list
1949              (concat
1950               "\\(^\\|[^$@%&\\]\\)\\<\\("
1951               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm" "and" "atan2"
1952               ;; "bind" "binmode" "bless" "caller" "chdir" "chmod" "chown" "chr"
1953               ;; "chroot" "close" "closedir" "cmp" "connect" "continue" "cos"
1954               ;; "crypt" "dbmclose" "dbmopen" "die" "dump" "endgrent" "endhostent"
1955               ;; "endnetent" "endprotoent" "endpwent" "endservent" "eof" "eq" "exec"
1956               ;; "exit" "exp" "fcntl" "fileno" "flock" "fork" "formline" "ge" "getc"
1957               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr" "gethostbyname"
1958               ;; "gethostent" "getlogin" "getnetbyaddr" "getnetbyname" "getnetent"
1959               ;; "getpeername" "getpgrp" "getppid" "getpriority" "getprotobyname"
1960               ;; "getprotobynumber" "getprotoent" "getpwent" "getpwnam" "getpwuid"
1961               ;; "getservbyname" "getservbyport" "getservent" "getsockname"
1962               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int" "ioctl"
1963               ;; "join" "kill" "lc" "lcfirst" "le" "length" "link" "listen"
1964               ;; "localtime" "log" "lstat" "lt" "mkdir" "msgctl" "msgget" "msgrcv"
1965               ;; "msgsnd" "ne" "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
1966               ;; "quotemeta" "rand" "read" "readdir" "readline" "readlink"
1967               ;; "readpipe" "recv" "ref" "rename" "require" "reset" "reverse"
1968               ;; "rewinddir" "rindex" "rmdir" "seek" "seekdir" "select" "semctl"
1969               ;; "semget" "semop" "send" "setgrent" "sethostent" "setnetent"
1970               ;; "setpgrp" "setpriority" "setprotoent" "setpwent" "setservent"
1971               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite" "shutdown"
1972               ;; "sin" "sleep" "socket" "socketpair" "sprintf" "sqrt" "srand" "stat"
1973               ;; "substr" "symlink" "syscall" "sysread" "system" "syswrite" "tell"
1974               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst" "umask" "unlink"
1975               ;; "unpack" "utime" "values" "vec" "wait" "waitpid" "wantarray" "warn"
1976               ;; "write" "x" "xor"
1977               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|" 
1978               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
1979               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
1980               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
1981               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
1982               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
1983               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
1984               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
1985               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
1986               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
1987               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
1988               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
1989               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
1990               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
1991               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
1992               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
1993               "\\(\\|ngth\\)\\|o\\(caltime\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
1994               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
1995               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
1996               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
1997               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
1998               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
1999               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
2000               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
2001               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
2002               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|tem\\|write\\)\\|"
2003               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
2004               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
2005               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
2006               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
2007               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\)"
2008               "\\)\\>") 2 'font-lock-type-face)
2009             ;; In what follows we use `other' style
2010             ;; for nonoverwritable buildins
2011             ;; Somehow 's', 'm' are not autogenerated???
2012             (list
2013              (concat
2014               "\\(^\\|[^$@%&\\]\\)\\<\\("
2015               ;; "AUTOLOAD" "BEGIN" "DESTROY" "END" "__END__" "chomp" "chop"
2016               ;; "defined" "delete" "do" "each" "else" "elsif" "eval" "exists" "for"
2017               ;; "foreach" "format" "goto" "grep" "if" "keys" "last" "local" "map"
2018               ;; "my" "next" "no" "package" "pop" "pos" "print" "printf" "push" "q"
2019               ;; "qq" "qw" "qx" "redo" "return" "scalar" "shift" "sort" "splice"
2020               ;; "split" "study" "sub" "tie" "tr" "undef" "unless" "unshift" "untie"
2021               ;; "until" "use" "while" "y"
2022               "AUTOLOAD\\|BEGIN\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
2023               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
2024               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|if\\|keys\\|"
2025               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|"
2026               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
2027               "q\\(\\|q\\|w\\|x\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
2028               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
2029               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
2030               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
2031               "\\|[sm]"                 ; Added manually
2032               "\\)\\>") 2 'font-lock-other-type-face)
2033             ;;          (mapconcat 'identity
2034             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
2035             ;;                       "#include" "#define" "#undef")
2036             ;;                     "\\|")
2037             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
2038               font-lock-function-name-face) ; Not very good, triggers at "[a-z]"
2039             '("\\<sub[ \t]+\\([^ \t{]+\\)[ \t]*[{\n]" 1
2040               font-lock-function-name-face)
2041             '("\\<\\(package\\|require\\|use\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
2042               2 font-lock-function-name-face)
2043             (if (featurep 'font-lock-extra)
2044                 '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\([a-zA-Z0-9_:]+\\)[ \t]*}" 
2045                   (2 font-lock-string-face t)
2046                   (0 '(restart 2 t)))   ; To highlight $a{bc}{ef}
2047               '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\([a-zA-Z0-9_:]+\\)[ \t]*}"
2048                 2 font-lock-string-face t))
2049             '("[ \t{,(]\\([a-zA-Z0-9_:]+\\)[ \t]*=>" 1
2050               font-lock-string-face t)
2051             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1 
2052               font-lock-reference-face) ; labels
2053             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
2054               2 font-lock-reference-face)
2055             (if (featurep 'font-lock-extra)
2056                 '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%][a-zA-Z0-9_]+\\)\\([ \t]*,\\)?"
2057                   (3 font-lock-variable-name-face)
2058                   (4 '(another 4 nil
2059                                ("[ \t]*,[ \t]*\\([$@%][a-zA-Z0-9_]+\\)\\([ \t]*,\\)?"
2060                                 (1 font-lock-variable-name-face)
2061                                 (2 '(restart 2 nil) nil t))) 
2062                      nil t))            ; local variables, multiple
2063               '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%][a-zA-Z0-9_]+\\)"
2064                 3 font-lock-variable-name-face))
2065             '("\\<for\\(each\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
2066               2 font-lock-variable-name-face)))
2067           (if (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
2068                    (not (cperl-xemacs-p))) ; not yet as of XEmacs 19.12
2069               (setq t-font-lock-keywords
2070                     (append 
2071                      t-font-lock-keywords
2072                      '(("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
2073                         1
2074                         (if (= (- (match-end 2) (match-beginning 2)) 1) 
2075                             (if (eq (char-after (match-beginning 3)) ?{)
2076                                 font-lock-other-emphasized-face
2077                               font-lock-emphasized-face) ; arrays and hashes
2078                           font-lock-variable-name-face) ; Just to put something
2079                         t)
2080                        ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
2081                         (if (eq (char-after (match-beginning 2)) ?%)
2082                             font-lock-other-emphasized-face
2083                           font-lock-emphasized-face)
2084                         t)              ; arrays and hashes
2085                        ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
2086                        ;;; Too much noise from \s* @s[ and friends
2087                        ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)" 
2088                         ;;(3 font-lock-function-name-face t t)
2089                         ;;(4
2090                         ;; (if (cperl-slash-is-regexp)
2091                         ;;    font-lock-function-name-face 'default) nil t))
2092                        ))))
2093           (defconst perl-font-lock-keywords t-font-lock-keywords
2094             "Additional expressions to highlight in Perl mode."))
2095         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
2096         (if (featurep 'font-lock-extra)
2097             (font-lock-require-faces
2098              (list
2099               ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
2100               (list 'font-lock-comment-face
2101                     ["Firebrick"        "OrangeRed"     "DimGray"       "Gray80"]
2102                     nil
2103                     [nil                nil             t               t       t]
2104                     [nil                nil             t               t       t]
2105                     nil)
2106               (list 'font-lock-string-face
2107                     ["RosyBrown"        "LightSalmon"   "Gray50"        "LightGray"]
2108                     nil
2109                     nil
2110                     [nil                nil             t               t       t]
2111                     nil)
2112               (list 'font-lock-keyword-face
2113                     ["Purple"           "LightSteelBlue" "DimGray"      "Gray90"]
2114                     nil
2115                     [nil                nil             t               t       t]
2116                     nil
2117                     nil)
2118               (list 'font-lock-function-name-face
2119                     (vector
2120                      "Blue"             "LightSkyBlue"  "Gray50"        "LightGray"
2121                      (cdr (assq 'background-color ; if mono
2122                                 (frame-parameters))))
2123                     (vector
2124                      nil                nil             nil             nil
2125                      (cdr (assq 'foreground-color ; if mono
2126                                 (frame-parameters))))
2127                     [nil                nil             t               t       t]
2128                     nil
2129                     nil)
2130               (list 'font-lock-variable-name-face
2131                     ["DarkGoldenrod"    "LightGoldenrod" "DimGray"      "Gray90"]
2132                     nil
2133                     [nil                nil             t               t       t]
2134                     [nil                nil             t               t       t]
2135                     nil)
2136               (list 'font-lock-type-face
2137                     ["DarkOliveGreen"   "PaleGreen"     "DimGray"       "Gray80"]
2138                     nil
2139                     [nil                nil             t               t       t]
2140                     nil
2141                     [nil                nil             t               t       t]
2142                     )
2143               (list 'font-lock-reference-face
2144                     ["CadetBlue"        "Aquamarine"    "Gray50"        "LightGray"]
2145                     nil
2146                     [nil                nil             t               t       t]
2147                     nil
2148                     [nil                nil             t               t       t]
2149                     )
2150               (list 'font-lock-other-type-face
2151                     ["chartreuse3"      ("orchid1" "orange")
2152                      nil                "Gray80"]
2153                     [nil                nil             "gray90"]
2154                     [nil                nil             nil             t       t]
2155                     [nil                nil             t               t]
2156                     [nil                nil             t               t       t]
2157                     )
2158               (list 'font-lock-emphasized-face
2159                     ["blue"             "yellow"        nil             "Gray80"]
2160                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
2161                      "gray90"]
2162                     t
2163                     nil
2164                     nil)
2165               (list 'font-lock-other-emphasized-face
2166                     ["red"              "red"           nil             "Gray80"]
2167                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
2168                      "gray90"]
2169                     t
2170                     t
2171                     nil)))
2172           (defvar cperl-guessed-background nil
2173             "Display characteristics as guessed by cperl.")
2174           (or (fboundp 'x-color-defined-p)
2175               (defalias 'x-color-defined-p 
2176                 (cond ((fboundp 'color-defined-p) 'color-defined-p)
2177                       ;; XEmacs >= 19.12
2178                       ((fboundp 'valid-color-name-p) 'valid-color-name-p)
2179                       ;; XEmacs 19.11
2180                       (t 'x-valid-color-name-p))))
2181           (defvar font-lock-reference-face 'font-lock-reference-face)
2182           (defvar font-lock-variable-name-face 'font-lock-variable-name-face)
2183           (or (boundp 'font-lock-type-face)
2184               (defconst font-lock-type-face
2185                 'font-lock-type-face
2186                 "Face to use for data types.")
2187               )
2188           (or (boundp 'font-lock-other-type-face)
2189               (defconst font-lock-other-type-face
2190                 'font-lock-other-type-face
2191                 "Face to use for data types from another group.")
2192               )
2193           (if (not (cperl-xemacs-p)) nil
2194             (or (boundp 'font-lock-comment-face)
2195                 (defconst font-lock-comment-face
2196                   'font-lock-comment-face
2197                   "Face to use for comments.")
2198                 )
2199             (or (boundp 'font-lock-keyword-face)
2200                 (defconst font-lock-keyword-face
2201                   'font-lock-keyword-face
2202                   "Face to use for keywords.")
2203                 )
2204             (or (boundp 'font-lock-function-name-face)
2205                 (defconst font-lock-function-name-face
2206                   'font-lock-function-name-face
2207                   "Face to use for function names.")
2208                 )
2209             )
2210           ;;(if (featurep 'font-lock)
2211           (if (face-equal font-lock-type-face font-lock-comment-face)
2212               (defconst font-lock-type-face
2213                 'font-lock-type-face
2214                 "Face to use for basic data types.")
2215             )
2216 ;;;       (if (fboundp 'eval-after-load)
2217 ;;;           (eval-after-load "font-lock"
2218 ;;;                            '(if (face-equal font-lock-type-face
2219 ;;;                                             font-lock-comment-face)
2220 ;;;                                 (defconst font-lock-type-face
2221 ;;;                                   'font-lock-type-face
2222 ;;;                                   "Face to use for basic data types.")
2223 ;;;                               )))   ; This does not work :-( Why?!
2224 ;;;                                     ; Workaround: added to font-lock-m-h
2225 ;;;       )
2226           (or (boundp 'font-lock-other-emphasized-face)
2227               (defconst font-lock-other-emphasized-face
2228                 'font-lock-other-emphasized-face
2229                 "Face to use for another type of emphasizing.")
2230               )
2231           (or (boundp 'font-lock-emphasized-face)
2232               (defconst font-lock-emphasized-face
2233                 'font-lock-emphasized-face
2234                 "Face to use for emphasizing.")
2235               )
2236           ;; Here we try to guess background
2237           (let ((background
2238                  (if (boundp 'font-lock-background-mode)
2239                      font-lock-background-mode
2240                    'light)) 
2241                 (face-list (and (fboundp 'face-list) (face-list)))
2242                 is-face)
2243             (fset 'is-face
2244                   (cond ((fboundp 'find-face)
2245                          (symbol-function 'find-face))
2246                         (face-list
2247                          (function (lambda (face) (member face face-list))))
2248                         (t
2249                          (function (lambda (face) (boundp face))))))
2250             (defvar cperl-guessed-background
2251               (if (and (boundp 'font-lock-display-type)
2252                        (eq font-lock-display-type 'grayscale))
2253                   'gray
2254                 background)
2255               "Background as guessed by CPerl mode")
2256             (if (is-face 'font-lock-type-face) nil
2257               (copy-face 'default 'font-lock-type-face)
2258               (cond
2259                ((eq background 'light)
2260                 (set-face-foreground 'font-lock-type-face
2261                                      (if (x-color-defined-p "seagreen")
2262                                          "seagreen"
2263                                        "sea green")))
2264                ((eq background 'dark)
2265                 (set-face-foreground 'font-lock-type-face
2266                                      (if (x-color-defined-p "os2pink")
2267                                          "os2pink"
2268                                        "pink")))
2269                (t
2270                 (set-face-background 'font-lock-type-face "gray90"))))
2271             (if (is-face 'font-lock-other-type-face)
2272                 nil
2273               (copy-face 'font-lock-type-face 'font-lock-other-type-face)
2274               (cond
2275                ((eq background 'light)
2276                 (set-face-foreground 'font-lock-other-type-face
2277                                      (if (x-color-defined-p "chartreuse3")
2278                                          "chartreuse3"
2279                                        "chartreuse")))
2280                ((eq background 'dark)
2281                 (set-face-foreground 'font-lock-other-type-face
2282                                      (if (x-color-defined-p "orchid1")
2283                                          "orchid1"
2284                                        "orange")))))
2285             (if (is-face 'font-lock-other-emphasized-face) nil
2286               (copy-face 'bold-italic 'font-lock-other-emphasized-face)
2287               (cond
2288                ((eq background 'light)
2289                 (set-face-background 'font-lock-other-emphasized-face
2290                                      (if (x-color-defined-p "lightyellow2")
2291                                          "lightyellow2"
2292                                        (if (x-color-defined-p "lightyellow")
2293                                            "lightyellow"
2294                                          "light yellow"))))
2295                ((eq background 'dark)
2296                 (set-face-background 'font-lock-other-emphasized-face
2297                                      (if (x-color-defined-p "navy")
2298                                          "navy"
2299                                        (if (x-color-defined-p "darkgreen")
2300                                            "darkgreen"
2301                                          "dark green"))))
2302                (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
2303             (if (is-face 'font-lock-emphasized-face) nil
2304               (copy-face 'bold 'font-lock-emphasized-face)
2305               (cond
2306                ((eq background 'light)
2307                 (set-face-background 'font-lock-emphasized-face
2308                                      (if (x-color-defined-p "lightyellow2")
2309                                          "lightyellow2"
2310                                        "lightyellow")))
2311                ((eq background 'dark)
2312                 (set-face-background 'font-lock-emphasized-face
2313                                      (if (x-color-defined-p "navy")
2314                                          "navy"
2315                                        (if (x-color-defined-p "darkgreen")
2316                                            "darkgreen"
2317                                          "dark green"))))
2318                (t (set-face-background 'font-lock-emphasized-face "gray90"))))
2319             (if (is-face 'font-lock-variable-name-face) nil
2320               (copy-face 'italic 'font-lock-variable-name-face))
2321             (if (is-face 'font-lock-reference-face) nil
2322               (copy-face 'italic 'font-lock-reference-face)))))
2323     (error nil)))
2324
2325
2326 (defun cperl-ps-print-init ()
2327   "Initialization of `ps-print' components for faces used in CPerl."
2328   ;; Guard against old versions
2329   (defvar ps-underlined-faces nil)
2330   (defvar ps-bold-faces nil)
2331   (defvar ps-italic-faces nil)
2332   (setq ps-bold-faces
2333         (append '(font-lock-emphasized-face
2334                   font-lock-keyword-face 
2335                   font-lock-variable-name-face 
2336                   font-lock-reference-face 
2337                   font-lock-other-emphasized-face) 
2338                 ps-bold-faces))
2339   (setq ps-italic-faces
2340         (append '(font-lock-other-type-face
2341                   font-lock-reference-face 
2342                   font-lock-other-emphasized-face)
2343                 ps-italic-faces))
2344   (setq ps-underlined-faces
2345         (append '(font-lock-emphasized-face
2346                   font-lock-other-emphasized-face 
2347                   font-lock-other-type-face font-lock-type-face)
2348                 ps-underlined-faces))
2349   (cons 'font-lock-type-face ps-underlined-faces))
2350
2351
2352 (if (cperl-enable-font-lock) (cperl-windowed-init))
2353
2354 (defun cperl-set-style (style)
2355   "Set CPerl-mode variables to use one of several different indentation styles.
2356 The arguments are a string representing the desired style.
2357 Available styles are GNU, K&R, BSD and Whitesmith."
2358   (interactive 
2359    (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
2360                        c-style-alist)))
2361      (list (completing-read "Enter style: " list nil 'insist))))
2362   (let ((style (cdr (assoc style c-style-alist))) setting str sym)
2363     (while style
2364       (setq setting (car style) style (cdr style))
2365       (setq str (symbol-name (car setting)))
2366       (and (string-match "^c-" str)
2367            (setq str (concat "cperl-" (substring str 2)))
2368            (setq sym (intern-soft str))
2369            (boundp sym)
2370            (set sym (cdr setting))))))
2371
2372 (defun cperl-check-syntax ()
2373   (interactive)
2374   (require 'mode-compile)
2375   (let ((perl-dbg-flags "-wc"))
2376     (mode-compile)))
2377
2378 (defun cperl-info-buffer ()
2379   ;; Returns buffer with documentation. Creats if missing
2380   (let ((info (get-buffer "*info-perl*")))
2381     (if info info
2382       (save-window-excursion
2383         ;; Get Info running
2384         (require 'info)
2385         (save-window-excursion
2386           (info))
2387         (Info-find-node "perl5" "perlfunc")
2388         (set-buffer "*info*")
2389         (rename-buffer "*info-perl*")
2390         (current-buffer)))))
2391
2392 (defun cperl-word-at-point (&optional p)
2393   ;; Returns the word at point or at P.
2394   (save-excursion
2395     (if p (goto-char p))
2396     (require 'etags)
2397     (funcall (or (and (boundp 'find-tag-default-function)
2398                       find-tag-default-function)
2399                  (get major-mode 'find-tag-default-function)
2400                  ;; XEmacs 19.12 has `find-tag-default-hook'; it is
2401                  ;; automatically used within `find-tag-default':
2402                  'find-tag-default))))
2403
2404 (defun cperl-info-on-command (command)
2405   "Shows documentation for Perl command in other window."
2406   (interactive 
2407    (let* ((default (cperl-word-at-point))
2408           (read (read-string 
2409                      (format "Find doc for Perl function (default %s): " 
2410                              default))))
2411      (list (if (equal read "") 
2412                    default 
2413                  read))))
2414
2415   (let ((buffer (current-buffer))
2416         (cmd-desc (concat "^" (regexp-quote command) "[ \t\n]"))
2417         pos)
2418     (if (string-match "^-[a-zA-Z]$" command)
2419         (setq cmd-desc "^-X[ \t\n]"))
2420     (set-buffer (cperl-info-buffer))
2421     (beginning-of-buffer)
2422     (re-search-forward "^-X[ \t\n]")
2423     (forward-line -1)
2424     (if (re-search-forward cmd-desc nil t)
2425         (progn
2426           (setq pos (progn (beginning-of-line)
2427                            (point)))
2428           (pop-to-buffer (cperl-info-buffer))
2429           (set-window-start (selected-window) pos))
2430       (message "No entry for %s found." command))
2431       (pop-to-buffer buffer)))
2432
2433 (defun cperl-info-on-current-command ()
2434   "Shows documentation for Perl command at point in other window."
2435   (interactive)
2436   (cperl-info-on-command (cperl-word-at-point)))
2437
2438 (defun cperl-imenu-info-imenu-search ()
2439   (if (looking-at "^-X[ \t\n]") nil
2440     (re-search-backward
2441      "^\n\\([-a-zA-Z]+\\)[ \t\n]")
2442     (forward-line 1)))
2443
2444 (defun cperl-imenu-info-imenu-name ()  
2445   (buffer-substring
2446    (match-beginning 1) (match-end 1)))
2447
2448 (defun cperl-imenu-on-info ()
2449   (interactive)
2450   (let* ((buffer (current-buffer))
2451          imenu-create-index-function
2452          imenu-prev-index-position-function 
2453          imenu-extract-index-name-function 
2454          (index-item (save-restriction
2455                        (save-window-excursion
2456                          (set-buffer (cperl-info-buffer))
2457                          (setq imenu-create-index-function 
2458                                'imenu-default-create-index-function
2459                                imenu-prev-index-position-function
2460                                'cperl-imenu-info-imenu-search
2461                                imenu-extract-index-name-function
2462                                'cperl-imenu-info-imenu-name)
2463                          (imenu-choose-buffer-index)))))
2464     (and index-item
2465          (progn
2466            (push-mark)
2467            (pop-to-buffer "*info-perl*")
2468            (cond
2469             ((markerp (cdr index-item))
2470              (goto-char (marker-position (cdr index-item))))
2471             (t
2472              (goto-char (cdr index-item))))
2473            (set-window-start (selected-window) (point))
2474            (pop-to-buffer buffer)))))
2475
2476 (defun cperl-lineup (beg end &optional step minshift)
2477   "Lineup construction in a region.
2478 Beginning of region should be at the start of a construction.
2479 All first occurences of this construction in the lines that are
2480 partially contained in the region are lined up at the same column.
2481
2482 MINSHIFT is the minimal amount of space to insert before the construction.
2483 STEP is the tabwidth to position constructions.
2484 If STEP is `nil', `cperl-lineup-step' will be used 
2485 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
2486 Will not move the position at the start to the left."
2487   (interactive "r")
2488   (let (search col tcol seen b e)
2489     (save-excursion
2490       (goto-char end)
2491       (end-of-line)
2492       (setq end (point-marker))
2493       (goto-char beg)
2494       (skip-chars-forward " \t\f")
2495       (setq beg (point-marker))
2496       (indent-region beg end nil)
2497       (goto-char beg)
2498       (setq col (current-column))
2499       (if (looking-at "\\sw")
2500           (if (looking-at "\\<\\sw+\\>")
2501               (setq search
2502                     (concat "\\<" 
2503                             (regexp-quote 
2504                              (buffer-substring (match-beginning 0)
2505                                                (match-end 0))) "\\>"))
2506             (error "Cannot line up in a middle of the word"))
2507         (if (looking-at "$")
2508             (error "Cannot line up end of line"))
2509         (setq search (regexp-quote (char-to-string (following-char)))))
2510       (setq step (or step cperl-lineup-step cperl-indent-level))
2511       (or minshift (setq minshift 1))
2512       (while (progn
2513                (beginning-of-line 2)
2514                (and (< (point) end) 
2515                     (re-search-forward search end t)
2516                     (goto-char (match-beginning 0))))
2517         (setq tcol (current-column) seen t)
2518         (if (> tcol col) (setq col tcol)))
2519       (or seen
2520           (error "The construction to line up occured only once"))
2521       (goto-char beg)
2522       (setq col (+ col minshift))
2523       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
2524       (while 
2525           (progn
2526             (setq e (point))
2527             (skip-chars-backward " \t")
2528             (delete-region (point) e)
2529             (indent-to-column col); (make-string (- col (current-column)) ?\ ))
2530             (beginning-of-line 2) 
2531             (and (< (point) end) 
2532                  (re-search-forward search end t)
2533                  (goto-char (match-beginning 0)))))))) ; No body
2534
2535 (defun cperl-etags (&optional add all files)
2536   "Run etags with appropriate options for Perl files.
2537 If optional argument ALL is `recursive', will process Perl files
2538 in subdirectories too."
2539   (interactive)
2540   (let ((cmd "etags")
2541         (args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\([{#]\\|$\\)\\)/\\4/"))
2542         res)
2543     (if add (setq args (cons "-a" args)))
2544     (or files (setq files (list buffer-file-name)))
2545     (cond
2546      ((eq all 'recursive)
2547       ;;(error "Not implemented: recursive")
2548       (setq args (append (list "-e" 
2549                                "sub wanted {push @ARGV, $File::Find::name if /\\.[Pp][Llm]$/}
2550                                 use File::Find;
2551                                 find(\\&wanted, '.');
2552                                 exec @ARGV;" 
2553                                cmd) args)
2554             cmd "perl"))
2555      (all 
2556       ;;(error "Not implemented: all")
2557       (setq args (append (list "-e" 
2558                                "push @ARGV, <*.PL *.pl *.pm>;
2559                                 exec @ARGV;" 
2560                                cmd) args)
2561             cmd "perl"))
2562      (t
2563       (setq args (append args files))))
2564     (setq res (apply 'call-process cmd nil nil nil args))
2565     (or (eq res 0)
2566         (message "etags returned \"%s\"" res))))