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