Run embed.pl and keywords.pl to complete RESTART -> INIT change
[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-1996 Bob Olson, Ilya Zakharevich
10
11 ;; This file is not (yet) part of GNU Emacs. It may be distributed
12 ;; either under the same terms as GNU Emacs, or under the same terms
13 ;; as Perl. You should have received a copy of Perl Artistic license
14 ;; along with the Perl distribution.
15
16 ;; GNU Emacs is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
28 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
29 ;; Boston, MA 02111-1307, USA.
30
31
32 ;;; Corrections made by Ilya Zakharevich ilya@math.mps.ohio-state.edu
33 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
34
35 ;; $Id: cperl-mode.el,v 1.33 1997/03/14 06:45:51 ilya Exp ilya $
36
37 ;;; To use this mode put the following into your .emacs file:
38
39 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
40
41 ;;; You can either fine-tune the bells and whistles of this mode or
42 ;;; bulk enable them by putting
43
44 ;; (setq cperl-hairy t)
45
46 ;;; in your .emacs file. (Emacs rulers do not consider it politically
47 ;;; correct to make whistles enabled by default.)
48
49 ;;; DO NOT FORGET to read micro-docs. (available from `Perl' menu). <<<<<<
50 ;;; or as help on variables `cperl-tips', `cperl-problems',         <<<<<<
51 ;;; `cperl-non-problems', `cperl-praise'.                           <<<<<<
52
53 ;;; Additional useful commands to put into your .emacs file:
54
55 ;; (setq auto-mode-alist
56 ;;       (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
57 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
58 ;;                                      '(("miniperl" . perl-mode))))
59
60 ;;; The mode information (on C-h m) provides some customization help.
61 ;;; If you use font-lock feature of this mode, it is advisable to use
62 ;;; either lazy-lock-mode or fast-lock-mode (available on ELisp
63 ;;; archive in files lazy-lock.el and fast-lock.el). I prefer lazy-lock.
64
65 ;;; Faces used now: three faces for first-class and second-class keywords
66 ;;; and control flow words, one for each: comments, string, labels,
67 ;;; functions definitions and packages, arrays, hashes, and variable
68 ;;; definitions. If you do not see all these faces, your font-lock does
69 ;;; not define them, so you need to define them manually. Maybe you have 
70 ;;; an obsolete font-lock from 19.28 or earlier. Upgrade.
71
72 ;;; If you have a grayscale monitor, and do not have the variable
73 ;;; font-lock-display-type bound to 'grayscale, insert 
74
75 ;;; (setq font-lock-display-type 'grayscale)
76
77 ;;; into your .emacs file.
78
79 ;;;; This mode supports font-lock, imenu and mode-compile. In the
80 ;;;; hairy version font-lock is on, but you should activate imenu
81 ;;;; yourself (note that mode-compile is not standard yet). Well, you
82 ;;;; can use imenu from keyboard anyway (M-x imenu), but it is better
83 ;;;; to bind it like that:
84
85 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
86
87 ;;; In fact the version of font-lock that this version supports can be
88 ;;; much newer than the version you actually have. This means that a
89 ;;; lot of faces can be set up, but are not visible on your screen
90 ;;; since the coloring rules for this faces are not defined.
91
92 ;;; Updates: ========================================
93
94 ;;; Made less hairy by default: parentheses not electric, 
95 ;;; linefeed not magic. Bug with abbrev-mode corrected.
96
97 ;;;; After 1.4:
98 ;;;  Better indentation:
99 ;;;  subs inside braces should work now, 
100 ;;;  Toplevel braces obey customization.
101 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
102 ;;;  moves cursor to a correct place.
103 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-( 
104 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
105 ;;;  Minor documentation fixes.
106 ;;;  Imenu understands packages as prefixes (including nested).
107 ;;;  Hairy options can be switched off one-by-one by setting to null.
108 ;;;  Names of functions and variables changed to conform to `cperl-' style.
109
110 ;;;; After 1.5:
111 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
112 ;;;  `cperl-indent-region' done (slow :-()).
113 ;;;  `cperl-fill-paragraph' done.
114 ;;;  Better package support for `imenu'.
115 ;;;  Progress indicator for indentation (with `imenu' loaded).
116 ;;;  `Cperl-set' was busted, now setting the individual hairy option 
117 ;;;     should be better.
118
119 ;;;; After 1.6:
120 ;;; `cperl-set-style' done.
121 ;;; `cperl-check-syntax' done.
122 ;;; Menu done.
123 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
124 ;;; Bugs with `cperl-auto-newline' corrected.
125 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation 
126 ;;; like $hash{.
127
128 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
129 ;;; - use `next-command-event', if `next-command-events' does not exist
130 ;;; - use `find-face' as def. of `is-face'
131 ;;; - corrected def. of `x-color-defined-p'
132 ;;; - added const defs for font-lock-comment-face,
133 ;;;   font-lock-keyword-face and font-lock-function-name-face
134 ;;; - added def. of font-lock-variable-name-face
135 ;;; - added (require 'easymenu) inside an `eval-when-compile'
136 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
137 ;;;   `define-key's
138 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
139 ;;; Todo (at least):
140 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
141 ;;;   for portable code?
142 ;;; - should `cperl-mode' do a 
143 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
144 ;;;   or should this be left to the user's `cperl-mode-hook'?
145
146 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
147 ;;; Some bugs under XEmacs introduced by the correction corrected.
148
149 ;;; Some more can remain since there are two many different variants. 
150 ;;; Please feedback!
151
152 ;;; We do not support fontification of arrays and hashes under 
153 ;;; obsolete font-lock any more. Upgrade.
154
155 ;;;; after 1.8 Minor bug with parentheses.
156 ;;;; after 1.9 Improvements from Joe Marzot.
157 ;;;; after 1.10
158 ;;;  Does not need easymenu to compile under XEmacs.
159 ;;;  `vc-insert-headers' should work better.
160 ;;;  Should work with 19.29 and 19.12.
161 ;;;  Small improvements to fontification.
162 ;;;  Expansion of keywords does not depend on C-? being backspace.
163
164 ;;; after 1.10+
165 ;;; 19.29 and 19.12 supported.
166 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
167 ;;; Support for font-lock-extra.el.
168
169 ;;;; After 1.11:
170 ;;; Tools submenu.
171 ;;; Support for perl5-info.
172 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
173 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
174 ;;; Fontifies `require a if b;', __DATA__.
175 ;;; Arglist for auto-fill-mode was incorrect.
176
177 ;;;; After 1.12:
178 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions 
179 ;;; vertically.
180 ;;; `cperl-do-auto-fill' updated for 19.29 style.
181 ;;; `cperl-info-on-command' now has a default.
182 ;;; Workaround for broken C-h on XEmacs.
183 ;;; VC strings escaped.
184 ;;; C-h f now may prompt for function name instead of going on,
185 ;;; controlled by `cperl-info-on-command-no-prompt'.
186
187 ;;;; After 1.13:
188 ;;; Msb buffer list includes perl files
189 ;;; Indent-for-comment uses indent-to
190 ;;; Can write tag files using etags.
191
192 ;;;; After 1.14:
193 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
194 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
195 ;;; Bug with auto-filling comments started with "##" corrected.
196
197 ;;;; Very slow now: on DB::DB 0.91, 486/66:
198
199 ;;;Function Name                             Call Count  Elapsed Time  Average Time
200 ;;;========================================  ==========  ============  ============
201 ;;;cperl-block-p                             469         3.7799999999  0.0080597014
202 ;;;cperl-get-state                           505         163.39000000  0.3235445544
203 ;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
204 ;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
205 ;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
206 ;;;cperl-indent-line                         505         172.88000000  0.3423366336
207 ;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
208 ;;;cperl-indent-exp                          1           177.97000000  177.97000000
209 ;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
210 ;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
211 ;;;cperl-indent-region                       1           177.94000000  177.94000000
212
213 ;;;; After 1.15:
214 ;;; Takes into account white space after opening parentheses during indent.
215 ;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
216 ;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
217 ;;; for indentation so far.
218 ;;; Fontification updated to 19.30 style. 
219 ;;; The change 19.29->30 did not add all the required functionality,
220 ;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
221 ;;;       ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
222
223 ;;;; After 1.16:
224 ;;;       else # comment
225 ;;;    recognized as a start of a block.
226 ;;;  Two different font-lock-levels provided.
227 ;;;  `cperl-pod-head-face' introduced. Used for highlighting.
228 ;;;  `imenu' marks pods, +Packages moved to the head. 
229
230 ;;;; After 1.17:
231 ;;;  Scan for pods highlights here-docs too.
232 ;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
233 ;;;  Only one here-doc-tag per line is supported, and one in comment
234 ;;;  or a string may break fontification.
235 ;;;  POD headers were supposed to fill one line only.
236
237 ;;;; After 1.18:
238 ;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme 
239 ;;;    may  break under XEmacs.
240 ;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
241 ;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
242 ;;;    compatibility with older lazy-lock.el) (older one overfontifies
243 ;;;    something nevertheless :-().
244 ;;;  Will not indent something inside pod and here-documents.
245 ;;;  Fontifies the package name after import/no/bootstrap.
246 ;;;  Added new entry to menu with meta-info about the mode.
247
248 ;;;; After 1.19:
249 ;;;  Prefontification works much better with 19.29. Should be checked
250 ;;;   with 19.30 as well.
251 ;;;  Some misprints in docs corrected.
252 ;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
253 ;;;  Now the pod search is much stricter, so it can help you to find
254 ;;;    pod sections which are broken because of whitespace before =blah
255 ;;;    - just observe the fontification.
256
257 ;;;; After 1.20
258 ;;;  Anonymous subs are indented with respect to the level of
259 ;;;    indentation of `sub' now.
260 ;;;  {} is recognized as hash after `bless' and `return'.
261 ;;;  Anonymous subs are split by `cperl-linefeed' as well.
262 ;;;  Electric parens embrace a region if present.
263 ;;;  To make `cperl-auto-newline' useful,
264 ;;;    `cperl-auto-newline-after-colon' is introduced.
265 ;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
266 ;;;  `cperl-electric-parens-string'.
267 ;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
268 ;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
269 ;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
270 ;;;  Beginning-of-defun-regexp was not anchored.
271
272 ;;;; After 1.21
273 ;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
274 ;;;    after ")".
275 ;;;  {} is recognized as expression after `tr' and friends.
276
277 ;;;; After 1.22
278 ;;;  Entry Hierarchy added to imenu. Very primitive so far.
279 ;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
280 ;;;  Writes its own TAGS files.
281 ;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
282 ;;;  19.31: Problems with scan for PODs corrected.
283 ;;;  First POD header correctly fontified.
284 ;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
285 ;;;  Apparently it makes a lot of hierarchy code obsolete...
286
287 ;;;; After 1.23
288 ;;;  Tags filler now scans *.xs as well.
289 ;;;  The info from *.xs scan is used by the hierarchy viewer.
290 ;;;  Hierarchy viewer documented.
291 ;;;  Bug in 19.31 imenu documented.
292
293 ;;;; After 1.24
294 ;;;  New location for info-files mentioned,
295 ;;;  Electric-; should work better.
296 ;;;  Minor bugs with POD marking.
297
298 ;;;; After 1.25 (probably not...)
299 ;;;  `cperl-info-page' introduced.  
300 ;;;  To make `uncomment-region' working, `comment-region' would
301 ;;;  not insert extra space.
302 ;;;  Here documents delimiters better recognized 
303 ;;;  (empty one, and non-alphanums in quotes handled). May be wrong with 1<<14?
304 ;;;  `cperl-db' added, used in menu.
305 ;;;  imenu scan removes text-properties, for better debugging
306 ;;;    - but the bug is in 19.31 imenu.
307 ;;;  formats highlighted by font-lock and prescan, embedded comments
308 ;;;  are not treated.
309 ;;;  POD/friends scan merged in one pass.
310 ;;;  Syntax class is not used for analyzing the code, only char-syntax
311 ;;;  may be checked against _ or'ed with w.
312 ;;;  Syntax class of `:' changed to be _.
313 ;;;  `cperl-find-bad-style' added.
314
315 ;;;; After 1.25
316 ;;;  When search for here-documents, we ignore commented << in simplest cases.
317 ;;;  `cperl-get-help' added, available on C-h v and from menu.
318 ;;;  Auto-help added. Default with `cperl-hairy', switchable on/off
319 ;;;   with startup variable `cperl-lazy-help-time' and from
320 ;;;   menu. Requires `run-with-idle-timer'.
321 ;;;  Highlighting of @abc{@efg} was wrong - interchanged two regexps.
322
323 ;;;; After 1.27
324 ;;;  Indentation: At toplevel after a label - fixed.
325 ;;;  1.27 was put to archives in binary mode ===> DOSish :-(
326
327 ;;;; After 1.28
328 ;;;  Thanks to Martin Buchholz <mrb@Eng.Sun.COM>: misprints in
329 ;;;  comments and docstrings corrected, XEmacs support cleaned up.
330 ;;;  The closing parenths would enclose the region into matching
331 ;;;  parens under the same conditions as the opening ones.
332 ;;;  Minor updates to `cperl-short-docs'.
333 ;;;  Will not consider <<= as start of here-doc.
334
335 ;;;; After 1.29
336 ;;;  Added an extra advice to look into Micro-docs. ;-).
337 ;;;  Enclosing of region when you press a closing parenth is regulated by
338 ;;;  `cperl-electric-parens-string'.
339 ;;;  Minor updates to `cperl-short-docs'.
340 ;;;  `initialize-new-tags-table' called only if present (Does this help
341 ;;;     with generation of tags under XEmacs?).
342 ;;;  When creating/updating tag files, new info is written at the old place,
343 ;;;     or at the end (is this a wanted behaviour? I need this in perl build directory).
344
345 ;;;; After 1.30
346 ;;;  All the keywords from keywords.pl included (maybe with dummy explanation).
347 ;;;  No auto-help inside strings, comment, here-docs, formats, and pods.
348 ;;;  Shrinkwrapping of info, regulated by `cperl-max-help-size',
349 ;;;  `cperl-shrink-wrap-info-frame'.
350 ;;;  Info on variables as well.
351 ;;;  Recognision of HERE-DOCS improved yet more.
352 ;;;  Autonewline works on `}' without warnings.
353 ;;;  Autohelp works again on $_[0].
354
355 ;;;; After 1.31
356 ;;;  perl-descr.el found its author - hi, Johan!
357 ;;;  Some support for correct indent after here-docs and friends (may
358 ;;;  be superseeded by eminent change to Emacs internals).
359 ;;;  Should work with older Emaxen as well ( `-style stuff removed).
360
361 ;;;; After 1.32
362
363 ;;;  Started to add support for `syntax-table' property (should work
364 ;;;  with patched Emaxen), controlled by
365 ;;;  `cperl-use-syntax-table-text-property'. Currently recognized:
366 ;;;    All quote-like operators: m, s, y, tr, qq, qw, qx, q,
367 ;;;    // in most frequent context: 
368 ;;;          after block or
369 ;;;                    ~ { ( = | & + - * ! , ;
370 ;;;          or 
371 ;;;                    while if unless until and or not xor split grep map
372 ;;;    Here-documents, formats, PODs, 
373 ;;;    ${...}
374 ;;;    'abc$'
375 ;;;    sub a ($); sub a ($) {}
376 ;;;  (provide 'cperl-mode) was missing!
377 ;;;  `cperl-after-expr-p' is now much smarter after `}'.
378 ;;;  `cperl-praise' added to mini-docs.
379 ;;;  Utilities try to support subs-with-prototypes.
380
381 ;;;; After 1.32.1
382 ;;;  `cperl-after-expr-p' is now much smarter after "() {}" and "word {}":
383 ;;;     if word is "else, map, grep".
384 ;;;  Updated for new values of syntax-table constants.
385 ;;;  Uses `help-char' (at last!) (disabled, does not work?!)
386 ;;;  A couple of regexps where missing _ in character classes.
387 ;;;  -s could be considered as start of regexp, 1../blah/ was not,
388 ;;;  as was not /blah/ at start of file.
389
390 ;;;; After 1.32.2
391 ;;;  "\C-hv" was wrongly "\C-hf"
392 ;;;  C-hv was not working on `[index()]' because of [] in skip-chars-*.
393 ;;;  `__PACKAGE__' supported.
394 ;;;  Thanks for Greg Badros: `cperl-lazy-unstall' is more complete,
395 ;;;  `cperl-get-help' is made compatible with `query-replace'.
396
397 ;;;; As of Apr 15, development version of 19.34 supports
398 ;;;; `syntax-table' text properties. Try setting
399 ;;;; `cperl-use-syntax-table-text-property'.
400
401 ;;;; After 1.32.3
402 ;;;  We scan for s{}[] as well.
403 ;;;  We scan for $blah'foo as well.
404 ;;;  The default is to use `syntax-table' text property if Emacs is good enough.
405 ;;;  `cperl-lineup' is put on C-M-| (=C-M-S-\\).
406 ;;;  Start of `cperl-beautify-regexp'.
407
408 ;;;; After 1.32.4
409 ;;; `cperl-tags-hier-init' did not work in text-mode.
410 ;;; `cperl-noscan-files-regexp' had a misprint.
411 ;;; Generation of Class Hierarchy was broken due to a bug in `x-popup-menu'
412 ;;;  in 19.34.
413
414 (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
415 \f
416 (defvar cperl-extra-newline-before-brace nil
417   "*Non-nil means that if, elsif, while, until, else, for, foreach
418 and do constructs look like:
419
420         if ()
421         {
422         }
423
424 instead of:
425
426         if () {
427         }
428 ")
429
430 (defvar cperl-indent-level 2
431   "*Indentation of CPerl statements with respect to containing block.")
432 (defvar cperl-lineup-step nil
433   "*`cperl-lineup' will always lineup at multiple of this number.
434 If `nil', the value of `cperl-indent-level' will be used.")
435 (defvar cperl-brace-imaginary-offset 0
436   "*Imagined indentation of a Perl open brace that actually follows a statement.
437 An open brace following other text is treated as if it were this far
438 to the right of the start of its line.")
439 (defvar cperl-brace-offset 0
440   "*Extra indentation for braces, compared with other text in same context.")
441 (defvar cperl-label-offset -2
442   "*Offset of CPerl label lines relative to usual indentation.")
443 (defvar cperl-min-label-indent 1
444   "*Minimal offset of CPerl label lines.")
445 (defvar cperl-continued-statement-offset 2
446   "*Extra indent for lines not starting new statements.")
447 (defvar cperl-continued-brace-offset 0
448   "*Extra indent for substatements that start with open-braces.
449 This is in addition to cperl-continued-statement-offset.")
450 (defvar cperl-close-paren-offset -1
451   "*Extra indent for substatements that start with close-parenthesis.")
452
453 (defvar cperl-auto-newline nil
454   "*Non-nil means automatically newline before and after braces,
455 and after colons and semicolons, inserted in CPerl code. The following
456 \\[cperl-electric-backspace] will remove the inserted whitespace.
457 Insertion after colons requires both this variable and 
458 `cperl-auto-newline-after-colon' set.")
459
460 (defvar cperl-auto-newline-after-colon nil
461   "*Non-nil means automatically newline even after colons.
462 Subject to `cperl-auto-newline' setting.")
463
464 (defvar cperl-tab-always-indent t
465   "*Non-nil means TAB in CPerl mode should always reindent the current line,
466 regardless of where in the line point is when the TAB command is used.")
467
468 (defvar cperl-font-lock nil
469   "*Non-nil (and non-null) means CPerl buffers will use font-lock-mode.
470 Can be overwritten by `cperl-hairy' if nil.")
471
472 (defvar cperl-electric-lbrace-space nil
473   "*Non-nil (and non-null) means { after $ in CPerl buffers should be preceded by ` '.
474 Can be overwritten by `cperl-hairy' if nil.")
475
476 (defvar cperl-electric-parens-string "({[]})<"
477   "*String of parentheses that should be electric in CPerl.")
478
479 (defvar cperl-electric-parens nil
480   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
481 Can be overwritten by `cperl-hairy' if nil.")
482 (defvar cperl-electric-parens-mark  
483   (and window-system
484        (or (and (boundp 'transient-mark-mode) ; For Emacs
485                 transient-mark-mode)
486            (and (boundp 'zmacs-regions) ; For XEmacs
487                 zmacs-regions)))
488   "*Not-nil means that electric parens look for active mark.
489 Default is yes if there is visual feedback on mark.")
490
491 (defvar cperl-electric-parens-mark (and window-system transient-mark-mode)
492   "*Not-nil means that electric parens look for active mark.
493 Default is yes if there is visual feedback on mark.")
494
495 (defvar cperl-electric-linefeed nil
496   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
497 In any case these two mean plain and hairy linefeeds together.
498 Can be overwritten by `cperl-hairy' if nil.")
499
500 (defvar cperl-electric-keywords nil
501   "*Not-nil (and non-null) means keywords are electric in CPerl.
502 Can be overwritten by `cperl-hairy' if nil.")
503
504 (defvar cperl-hairy nil
505   "*Not-nil means all the bells and whistles are enabled in CPerl.")
506
507 (defvar cperl-comment-column 32
508   "*Column to put comments in CPerl (use \\[cperl-indent]' to lineup with code).")
509
510 (defvar cperl-vc-header-alist '((SCCS "$sccs = '%W\%' ;")
511                                 (RCS "$rcs = ' $Id\$ ' ;"))
512   "*What to use as `vc-header-alist' in CPerl.")
513
514 (defvar cperl-info-on-command-no-prompt nil
515   "*Not-nil (and non-null) means not to prompt on C-h f.
516 The opposite behaviour is always available if prefixed with C-c.
517 Can be overwritten by `cperl-hairy' if nil.")
518
519 (defvar cperl-lazy-help-time nil
520   "*Not-nil (and non-null) means to show lazy help after given idle time.")
521
522 (defvar cperl-pod-face 'font-lock-comment-face
523   "*The result of evaluation of this expression is used for pod highlighting.")
524
525 (defvar cperl-pod-head-face 'font-lock-variable-name-face
526   "*The result of evaluation of this expression is used for pod highlighting.
527 Font for POD headers.")
528
529 (defvar cperl-here-face 'font-lock-string-face
530   "*The result of evaluation of this expression is used for here-docs highlighting.")
531
532 (defvar cperl-pod-here-fontify '(featurep 'font-lock)
533   "*Not-nil after evaluation means to highlight pod and here-docs sections.")
534
535 (defvar cperl-pod-here-scan t
536   "*Not-nil means look for pod and here-docs sections during startup.
537 You can always make lookup from menu or using \\[cperl-find-pods-heres].")
538
539 (defvar cperl-imenu-addback nil
540   "*Not-nil means add backreferences to generated `imenu's.
541 May require patched `imenu' and `imenu-go'.")
542
543 (defvar cperl-max-help-size 66
544   "*Non-nil means shrink-wrapping of info-buffer allowed up to these percents.")
545
546 (defvar cperl-shrink-wrap-info-frame t
547   "*Non-nil means shrink-wrapping of info-buffer-frame allowed.")
548
549 (defvar cperl-info-page "perl"
550   "*Name of the info page containing perl docs.
551 Older version of this page was called `perl5', newer `perl'.")
552
553 (defvar cperl-use-syntax-table-text-property 
554   (and (not cperl-xemacs-p)
555        (string< "19.34.94" emacs-version)) ; Not all .94 are good, but anyway
556   "*Non-nil means CPerl sets up and uses `syntax-table' text property.")
557
558 (defvar cperl-scan-files-regexp "\\.\\([Pp][Llm]\\|xs\\)$"
559   "*Regexp to match files to scan when generating TAGS.")
560
561 (defvar cperl-noscan-files-regexp "/\\(\\.\\.?\\|SCCS\\|RCS\\|blib\\)$"
562   "*Regexp to match files/dirs to skip when generating TAGS.")
563
564 (defvar cperl-regexp-indent-step nil
565   "*indentation used when beautifying regexps.
566 If `nil', the value of `cperl-indent-level' will be used.")
567
568 \f
569
570 ;;; Short extra-docs.
571
572 (defvar cperl-tips 'please-ignore-this-line
573   "Get newest version of this package from
574   ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
575 and/or
576   ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
577
578 Get support packages choose-color.el (or font-lock-extra.el before
579 19.30), imenu-go.el from the same place.  \(Look for other files there
580 too... ;-) Get a patch for imenu.el in 19.29.  Note that for 19.30 and
581 later you should use choose-color.el *instead* of font-lock-extra.el 
582 \(and you will not get smart highlighting in C :-().
583
584 Note that to enable Compile choices in the menu you need to install
585 mode-compile.el.
586
587 Get perl5-info from 
588   $CPAN/doc/manual/info/perl-info.tar.gz
589 older version was on
590   http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz
591
592 If you use imenu-go, run imenu on perl5-info buffer (you can do it
593 from CPerl menu). If many files are related, generate TAGS files from
594 Tools/Tags submenu in CPerl menu.
595
596 If some class structure is too complicated, use Tools/Hierarchy-view
597 from CPerl menu, or hierarchic view of imenu. The second one uses the
598 current buffer only, the first one requires generation of TAGS from
599 CPerl/Tools/Tags menu beforehand.
600
601 Run CPerl/Tools/Insert-spaces-if-needed to fix your lazy typing.
602
603 Switch auto-help on/off with CPerl/Tools/Auto-help.
604
605 Before reporting (non-)problems look in the problem section on what I
606 know about them.")
607
608 (defvar cperl-problems 'please-ignore-this-line
609 "Emacs has a _very_ restricted syntax parsing engine. 
610
611 It may be corrected on the level of C code, please look in the
612 `non-problems' section if you want to volunteer.
613
614 CPerl mode tries to corrects some Emacs misunderstandings, however,
615 for efficiency reasons the degree of correction is different for
616 different operations. The partially corrected problems are: POD
617 sections, here-documents, regexps. The operations are: highlighting,
618 indentation, electric keywords, electric braces. 
619
620 This may be confusing, since the regexp s#//#/#\; may be highlighted
621 as a comment, but it will be recognized as a regexp by the indentation
622 code. Or the opposite case, when a pod section is highlighted, but
623 may break the indentation of the following code (though indentation
624 should work if the balance of delimiters is not broken by POD).
625
626 The main trick (to make $ a \"backslash\") makes constructions like
627 ${aaa} look like unbalanced braces. The only trick I can think of is
628 to insert it as $ {aaa} (legal in perl5, not in perl4). 
629
630 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
631 as /($|\\s)/. Note that such a transposition is not always possible
632 :-(.  " )
633
634 (defvar cperl-non-problems 'please-ignore-this-line
635 "As you know from `problems' section, Perl syntax is too hard for CPerl.
636
637 Most the time, if you write your own code, you may find an equivalent
638 \(and almost as readable) expression.
639
640 Try to help CPerl: add comments with embedded quotes to fix CPerl
641 misunderstandings about the end of quotation:
642
643 $a='500$';      # ';
644
645 You won't need it too often. The reason: $ \"quotes\" the following
646 character (this saves a life a lot of times in CPerl), thus due to
647 Emacs parsing rules it does not consider tick (i.e., ' ) after a
648 dollar as a closing one, but as a usual character.
649
650 Now the indentation code is pretty wise. The only drawback is that it
651 relies on Emacs parsing to find matching parentheses. And Emacs
652 *cannot* match parentheses in Perl 100% correctly. So
653         1 if s#//#/#;
654 will not break indentation, but
655         1 if ( s#//#/# );
656 will.
657
658 By similar reasons
659         s\"abc\"def\";
660 will confuse CPerl a lot.
661
662 If you still get wrong indentation in situation that you think the
663 code should be able to parse, try:
664
665 a) Check what Emacs thinks about balance of your parentheses.
666 b) Supply the code to me (IZ).
667
668 Pods are treated _very_ rudimentally. Here-documents are not treated
669 at all (except highlighting and inhibiting indentation). (This may
670 change some time. RMS approved making syntax lookup recognize text
671 attributes, but volunteers are needed to change Emacs C code.)
672
673 To speed up coloring the following compromises exist:
674    a) sub in $mypackage::sub may be highlighted.
675    b) -z in [a-z] may be highlighted.
676    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
677
678
679 Imenu in 19.31 is broken. Set `imenu-use-keymap-menu' to t, and remove
680 `car' before `imenu-choose-buffer-index' in `imenu'.
681 ")
682
683 (defvar cperl-praise 'please-ignore-this-line
684   "RMS asked me to list good things about CPerl. Here they go:
685
686 0) It uses the newest `syntax-table' property ;-);
687
688 1) It does 99% of Perl syntax correct (as opposed to 80-90% in Perl
689 mode - but the latter number may have improved too in last years) even 
690 without `syntax-table' property; When using this property, it should 
691 handle 99.995% of lines correct - or somesuch.
692
693 2) It is generally belived to be \"the most user-friendly Emacs
694 package\" whatever it may mean (I doubt that the people who say similar
695 things tried _all_ the rest of Emacs ;-), but this was not a lonely
696 voice);
697
698 3) Everything is customizable, one-by-one or in a big sweep;
699
700 4) It has many easily-accessable \"tools\":
701         a) Can run program, check syntax, start debugger;
702         b) Can lineup vertically \"middles\" of rows, like `=' in
703                 a  = b;
704                 cc = d;
705         c) Can insert spaces where this impoves readability (in one
706                 interactive sweep over the buffer);
707         d) Has support for imenu, including:
708                 1) Separate unordered list of \"interesting places\";
709                 2) Separate TOC of POD sections;
710                 3) Separate list of packages;
711                 4) Hierarchical view of methods in (sub)packages;
712                 5) and functions (by the full name - with package);
713         e) Has an interface to INFO docs for Perl; The interface is
714                 very flexible, including shrink-wrapping of
715                 documentation buffer/frame;
716         f) Has a builtin list of one-line explanations for perl constructs.
717         g) Can show these explanations if you stay long enough at the
718                 corresponding place (or on demand);
719         h) Has an enhanced fontification (using 3 or 4 additional faces
720                 comparing to font-lock - basically, different
721                 namespaces in Perl have different colors);
722         i) Can construct TAGS basing on its knowledge of Perl syntax,
723                 the standard menu has 6 different way to generate
724                 TAGS (if by directory, .xs files - with C-language
725                 bindings - are included in the scan);
726         j) Can build a hierarchical view of classes (via imenu) basing
727                 on generated TAGS file;
728         k) Has electric parentheses, electric newlines, uses Abbrev
729                 for electric logical constructs
730                         while () {}
731                 with different styles of expansion (context sensitive
732                 to be not so bothering). Electric parentheses behave
733                 \"as they should\" in a presence of a visible region.
734         l) Changes msb.el \"on the fly\" to insert a group \"Perl files\";
735
736 5) The indentation engine was very smart, but most of tricks may be
737 not needed anymore with the support for `syntax-table' property. Has
738 progress indicator for indentation (with `imenu' loaded).
739
740 6) Indent-region improves inline-comments as well;
741
742 7) Fill-paragraph correctly handles multi-line comments;
743 ")
744
745 \f
746
747 ;;; Portability stuff:
748
749 (defmacro cperl-define-key (fsf-key definition &optional xemacs-key)
750   (` (define-key cperl-mode-map
751        (, (if xemacs-key
752               (` (if cperl-xemacs-p (, xemacs-key) (, fsf-key)))
753             fsf-key))
754        (, definition))))
755
756 (defvar del-back-ch (car (append (where-is-internal 'delete-backward-char)
757                                  (where-is-internal 'backward-delete-char-untabify)))
758   "Character generated by key bound to delete-backward-char.")
759
760 (and (vectorp del-back-ch) (= (length del-back-ch) 1) 
761      (setq del-back-ch (aref del-back-ch 0)))
762
763 (if cperl-xemacs-p
764     (progn
765       ;; "Active regions" are on: use region only if active
766       ;; "Active regions" are off: use region unconditionally
767       (defun cperl-use-region-p ()
768         (if zmacs-regions (mark) t))
769       (defun cperl-mark-active () (mark)))
770   (defun cperl-use-region-p ()
771     (if transient-mark-mode mark-active t))
772   (defun cperl-mark-active () mark-active))
773
774 (defsubst cperl-enable-font-lock ()
775   (or cperl-xemacs-p window-system))
776
777 (if (boundp 'unread-command-events)
778     (if cperl-xemacs-p
779         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
780           (setq unread-command-events (list (character-to-event c))))
781       (defun cperl-putback-char (c)     ; Emacs 19
782         (setq unread-command-events (list c))))
783   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
784     (setq unread-command-event (character-to-event c))))
785
786 (or (fboundp 'uncomment-region)
787     (defun uncomment-region (beg end)
788       (interactive "r")
789       (comment-region beg end -1)))
790
791 (defvar cperl-do-not-fontify
792   (if (string< emacs-version "19.30")
793       'fontified
794     'lazy-lock)
795   "Text property which inhibits refontification.")
796
797 (defsubst cperl-put-do-not-fontify (from to)
798   (put-text-property (max (point-min) (1- from))
799                      to cperl-do-not-fontify t))
800
801 \f
802 ;;; Probably it is too late to set these guys already, but it can help later:
803
804 (setq auto-mode-alist
805       (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
806 (and (boundp 'interpreter-mode-alist)
807      (setq interpreter-mode-alist (append interpreter-mode-alist
808                                           '(("miniperl" . perl-mode)))))
809 (if (fboundp 'eval-when-compile)
810     (eval-when-compile
811       (condition-case nil
812           (require 'imenu)
813         (error nil))
814       (condition-case nil
815           (require 'easymenu)
816         (error nil))
817       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
818       ;; macros instead of defsubsts don't work on Emacs, so we do the
819       ;; expansion manually. Any other suggestions?
820       (if (or (string-match "XEmacs\\|Lucid" emacs-version)
821               window-system)
822           (require 'font-lock))
823       (require 'cl)
824       ))
825
826 (defvar cperl-mode-abbrev-table nil
827   "Abbrev table in use in Cperl-mode buffers.")
828
829 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
830
831 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
832
833 (if cperl-mode-map nil
834   (setq cperl-mode-map (make-sparse-keymap))
835   (cperl-define-key "{" 'cperl-electric-lbrace)
836   (cperl-define-key "[" 'cperl-electric-paren)
837   (cperl-define-key "(" 'cperl-electric-paren)
838   (cperl-define-key "<" 'cperl-electric-paren)
839   (cperl-define-key "}" 'cperl-electric-brace)
840   (cperl-define-key "]" 'cperl-electric-rparen)
841   (cperl-define-key ")" 'cperl-electric-rparen)
842   (cperl-define-key ";" 'cperl-electric-semi)
843   (cperl-define-key ":" 'cperl-electric-terminator)
844   (cperl-define-key "\C-j" 'newline-and-indent)
845   (cperl-define-key "\C-c\C-j" 'cperl-linefeed)
846   (cperl-define-key "\C-c\C-a" 'cperl-toggle-auto-newline)
847   (cperl-define-key "\C-c\C-k" 'cperl-toggle-abbrev)
848   (cperl-define-key "\C-c\C-e" 'cperl-toggle-electric)
849   (cperl-define-key "\e\C-q" 'cperl-indent-exp) ; Usually not bound
850   (cperl-define-key [?\C-\M-\|] 'cperl-lineup)
851   ;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
852   ;;(cperl-define-key "\e;" 'cperl-indent-for-comment)
853   (cperl-define-key "\177" 'cperl-electric-backspace)
854   (cperl-define-key "\t" 'cperl-indent-command)
855   ;; don't clobber the backspace binding:
856   (cperl-define-key "\C-c\C-hf" 'cperl-info-on-current-command
857                     [(control c) (control h) f])
858   (cperl-define-key "\C-hf"
859                     ;;(concat (char-to-string help-char) "f") ; does not work
860                     'cperl-info-on-command
861                     [(control h) f])
862   (cperl-define-key "\C-hv"
863                     ;;(concat (char-to-string help-char) "v") ; does not work
864                     'cperl-get-help
865                     [(control h) v])
866   (if (and cperl-xemacs-p 
867            (<= emacs-minor-version 11) (<= emacs-major-version 19))
868       (progn
869         ;; substitute-key-definition is usefulness-deenhanced...
870         (cperl-define-key "\M-q" 'cperl-fill-paragraph)
871         (cperl-define-key "\e;" 'cperl-indent-for-comment)
872         (cperl-define-key "\e\C-\\" 'cperl-indent-region))
873     (substitute-key-definition
874      'indent-sexp 'cperl-indent-exp
875      cperl-mode-map global-map)
876     (substitute-key-definition
877      'fill-paragraph 'cperl-fill-paragraph
878      cperl-mode-map global-map)
879     (substitute-key-definition
880      'indent-region 'cperl-indent-region
881      cperl-mode-map global-map)
882     (substitute-key-definition
883      'indent-for-comment 'cperl-indent-for-comment
884      cperl-mode-map global-map)))
885
886 (condition-case nil
887     (progn
888       (require 'easymenu)
889       (easy-menu-define cperl-menu cperl-mode-map "Menu for CPerl mode"
890          '("Perl"
891            ["Beginning of function" beginning-of-defun t]
892            ["End of function" end-of-defun t]
893            ["Mark function" mark-defun t]
894            ["Indent expression" cperl-indent-exp t]
895            ["Fill paragraph/comment" cperl-fill-paragraph t]
896            "----"
897            ["Line up a construction" cperl-lineup (cperl-use-region-p)]
898            ["Beautify a regexp" cperl-beautify-regexp
899             cperl-use-syntax-table-text-property]
900            "----"
901            ["Indent region" cperl-indent-region (cperl-use-region-p)]
902            ["Comment region" cperl-comment-region (cperl-use-region-p)]
903            ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
904            "----"
905            ["Run" mode-compile (fboundp 'mode-compile)]
906            ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
907                                           (get-buffer "*compilation*"))]
908            ["Next error" next-error (get-buffer "*compilation*")]
909            ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
910            "----"
911            ["Debugger" cperl-db t]
912            "----"
913            ("Tools"
914             ["Imenu" imenu (fboundp 'imenu)]
915             ["Insert spaces if needed" cperl-find-bad-style t]
916             ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
917             ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
918             ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
919             ("Tags"
920 ;;;          ["Create tags for current file" cperl-etags t]
921 ;;;          ["Add tags for current file" (cperl-etags t) t]
922 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
923 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
924 ;;;          ["Create tags for Perl files in (sub)directories" 
925 ;;;           (cperl-etags nil 'recursive) t]
926 ;;;          ["Add tags for Perl files in (sub)directories"
927 ;;;           (cperl-etags t 'recursive) t]) 
928 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
929              ["Create tags for current file" (cperl-write-tags nil t) t]
930              ["Add tags for current file" (cperl-write-tags) t]
931              ["Create tags for Perl files in directory" 
932               (cperl-write-tags nil t nil t) t]
933              ["Add tags for Perl files in directory" 
934               (cperl-write-tags nil nil nil t) t]
935              ["Create tags for Perl files in (sub)directories" 
936               (cperl-write-tags nil t t t) t]
937              ["Add tags for Perl files in (sub)directories"
938               (cperl-write-tags nil nil t t) t])
939             ["Recalculate PODs and HEREs" cperl-find-pods-heres t]
940             ["Define word at point" imenu-go-find-at-position 
941              (fboundp 'imenu-go-find-at-position)]
942             ["Help on function" cperl-info-on-command t]
943             ["Help on function at point" cperl-info-on-current-command t]
944             ["Help on symbol at point" cperl-get-help t]
945             ["Auto-help on" cperl-lazy-install (fboundp 'run-with-idle-timer)]
946             ["Auto-help off" cperl-lazy-unstall 
947              (fboundp 'run-with-idle-timer)])
948            ("Toggle..."
949             ["Auto newline" cperl-toggle-auto-newline t]
950             ["Electric parens" cperl-toggle-electric t]
951             ["Electric keywords" cperl-toggle-abbrev t]
952             )
953            ("Indent styles..."
954             ["GNU" (cperl-set-style "GNU") t]
955             ["C++" (cperl-set-style "C++") t]
956             ["FSF" (cperl-set-style "FSF") t]
957             ["BSD" (cperl-set-style "BSD") t]
958             ["Whitesmith" (cperl-set-style "Whitesmith") t])
959            ("Micro-docs"
960             ["Tips" (describe-variable 'cperl-tips) t]
961             ["Problems" (describe-variable 'cperl-problems) t]
962             ["Non-problems" (describe-variable 'cperl-non-problems) t]
963             ["Praise" (describe-variable 'cperl-praise) t]))))
964   (error nil))
965
966 (autoload 'c-macro-expand "cmacexp"
967   "Display the result of expanding all C macros occurring in the region.
968 The expansion is entirely correct because it uses the C preprocessor."
969   t)
970
971 (defvar cperl-mode-syntax-table nil
972   "Syntax table in use in Cperl-mode buffers.")
973
974 (defvar cperl-string-syntax-table nil
975   "Syntax table in use in Cperl-mode string-like chunks.")
976
977 (if cperl-mode-syntax-table
978     ()
979   (setq cperl-mode-syntax-table (make-syntax-table))
980   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
981   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
982   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
983   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
984   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
985   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
986   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
987   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
988   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
989   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
990   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
991   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
992   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
993   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
994   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
995   (modify-syntax-entry ?_ "w" cperl-mode-syntax-table)
996   (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
997   (modify-syntax-entry ?| "." cperl-mode-syntax-table)
998   (setq cperl-string-syntax-table (copy-syntax-table cperl-mode-syntax-table))
999   (modify-syntax-entry ?$ "." cperl-string-syntax-table)
1000   (modify-syntax-entry ?# "." cperl-string-syntax-table) ; (?# comment )
1001 )
1002
1003
1004 \f
1005 ;; Make customization possible "in reverse"
1006 ;;(defun cperl-set (symbol to)
1007 ;;  (or (eq (symbol-value symbol) 'null) (set symbol to)))
1008 (defsubst cperl-val (symbol &optional default hairy)
1009   (cond
1010    ((eq (symbol-value symbol) 'null) default)
1011    (cperl-hairy (or hairy t))
1012    (t (symbol-value symbol))))
1013 \f
1014 ;; provide an alias for working with emacs 19.  the perl-mode that comes
1015 ;; with it is really bad, and this lets us seamlessly replace it.
1016 (fset 'perl-mode 'cperl-mode)
1017 (defun cperl-mode ()
1018   "Major mode for editing Perl code.
1019 Expression and list commands understand all C brackets.
1020 Tab indents for Perl code.
1021 Paragraphs are separated by blank lines only.
1022 Delete converts tabs to spaces as it moves back.
1023
1024 Various characters in Perl almost always come in pairs: {}, (), [],
1025 sometimes <>. When the user types the first, she gets the second as
1026 well, with optional special formatting done on {}.  (Disabled by
1027 default.)  You can always quote (with \\[quoted-insert]) the left
1028 \"paren\" to avoid the expansion. The processing of < is special,
1029 since most the time you mean \"less\". Cperl mode tries to guess
1030 whether you want to type pair <>, and inserts is if it
1031 appropriate. You can set `cperl-electric-parens-string' to the string that
1032 contains the parenths from the above list you want to be electrical.
1033 Electricity of parenths is controlled by `cperl-electric-parens'.
1034 You may also set `cperl-electric-parens-mark' to have electric parens
1035 look for active mark and \"embrace\" a region if possible.'
1036
1037 CPerl mode provides expansion of the Perl control constructs:
1038    if, else, elsif, unless, while, until, for, and foreach.
1039 =========(Disabled by default, see `cperl-electric-keywords'.)
1040 The user types the keyword immediately followed by a space, which causes
1041 the construct to be expanded, and the user is positioned where she is most
1042 likely to want to be.
1043 eg. when the user types a space following \"if\" the following appears in
1044 the buffer:
1045             if () {     or   if ()
1046             }                 {
1047                               }
1048 and the cursor is between the parentheses.  The user can then type some
1049 boolean expression within the parens.  Having done that, typing
1050 \\[cperl-linefeed] places you, appropriately indented on a new line
1051 between the braces. If CPerl decides that you want to insert
1052 \"English\" style construct like
1053             bite if angry;
1054 it will not do any expansion. See also help on variable 
1055 `cperl-extra-newline-before-brace'.
1056
1057 \\[cperl-linefeed] is a convenience replacement for typing carriage
1058 return. It places you in the next line with proper indentation, or if
1059 you type it inside the inline block of control construct, like
1060             foreach (@lines) {print; print}
1061 and you are on a boundary of a statement inside braces, it will
1062 transform the construct into a multiline and will place you into an
1063 appropriately indented blank line. If you need a usual 
1064 `newline-and-indent' behaviour, it is on \\[newline-and-indent], 
1065 see documentation on `cperl-electric-linefeed'.
1066
1067 \\{cperl-mode-map}
1068
1069 Setting the variable `cperl-font-lock' to t switches on
1070 font-lock-mode, `cperl-electric-lbrace-space' to t switches on
1071 electric space between $ and {, `cperl-electric-parens-string' is the
1072 string that contains parentheses that should be electric in CPerl (see
1073 also `cperl-electric-parens-mark' and `cperl-electric-parens'),
1074 setting `cperl-electric-keywords' enables electric expansion of
1075 control structures in CPerl. `cperl-electric-linefeed' governs which
1076 one of two linefeed behavior is preferable. You can enable all these
1077 options simultaneously (recommended mode of use) by setting
1078 `cperl-hairy' to t. In this case you can switch separate options off
1079 by setting them to `null'. Note that one may undo the extra whitespace
1080 inserted by semis and braces in `auto-newline'-mode by consequent
1081 \\[cperl-electric-backspace].
1082
1083 If your site has perl5 documentation in info format, you can use commands
1084 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
1085 These keys run commands `cperl-info-on-current-command' and
1086 `cperl-info-on-command', which one is which is controlled by variable
1087 `cperl-info-on-command-no-prompt' (in turn affected by `cperl-hairy').
1088
1089 Even if you have no info-format documentation, short one-liner-style
1090 help is available on \\[cperl-get-help]. 
1091
1092 It is possible to show this help automatically after some idle
1093 time. This is regulated by variable `cperl-lazy-help-time'.  Default
1094 with `cperl-hairy' is 5 secs idle time if the value of this variable
1095 is nil.  It is also possible to switch this on/off from the
1096 menu. Requires `run-with-idle-timer'.
1097
1098 Use \\[cperl-lineup] to vertically lineup some construction - put the
1099 beginning of the region at the start of construction, and make region
1100 span the needed amount of lines.
1101
1102 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
1103 `cperl-pod-face', `cperl-pod-head-face' control processing of pod and
1104 here-docs sections. In a future version results of scan may be used
1105 for indentation too, currently they are used for highlighting only.
1106
1107 Variables controlling indentation style:
1108  `cperl-tab-always-indent'
1109     Non-nil means TAB in CPerl mode should always reindent the current line,
1110     regardless of where in the line point is when the TAB command is used.
1111  `cperl-auto-newline'
1112     Non-nil means automatically newline before and after braces,
1113     and after colons and semicolons, inserted in Perl code. The following
1114     \\[cperl-electric-backspace] will remove the inserted whitespace.
1115     Insertion after colons requires both this variable and 
1116     `cperl-auto-newline-after-colon' set. 
1117  `cperl-auto-newline-after-colon'
1118     Non-nil means automatically newline even after colons.
1119     Subject to `cperl-auto-newline' setting.
1120  `cperl-indent-level'
1121     Indentation of Perl statements within surrounding block.
1122     The surrounding block's indentation is the indentation
1123     of the line on which the open-brace appears.
1124  `cperl-continued-statement-offset'
1125     Extra indentation given to a substatement, such as the
1126     then-clause of an if, or body of a while, or just a statement continuation.
1127  `cperl-continued-brace-offset'
1128     Extra indentation given to a brace that starts a substatement.
1129     This is in addition to `cperl-continued-statement-offset'.
1130  `cperl-brace-offset'
1131     Extra indentation for line if it starts with an open brace.
1132  `cperl-brace-imaginary-offset'
1133     An open brace following other text is treated as if it the line started
1134     this far to the right of the actual line indentation.
1135  `cperl-label-offset'
1136     Extra indentation for line that is a label.
1137  `cperl-min-label-indent'
1138     Minimal indentation for line that is a label.
1139
1140 Settings for K&R and BSD indentation styles are
1141   `cperl-indent-level'                5    8
1142   `cperl-continued-statement-offset'  5    8
1143   `cperl-brace-offset'               -5   -8
1144   `cperl-label-offset'               -5   -8
1145
1146 If `cperl-indent-level' is 0, the statement after opening brace in column 0 is indented on `cperl-brace-offset'+`cperl-continued-statement-offset'.
1147
1148 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
1149 with no args."
1150   (interactive)
1151   (kill-all-local-variables)
1152   ;;(if cperl-hairy
1153   ;;    (progn
1154   ;;    (cperl-set 'cperl-font-lock cperl-hairy)
1155   ;;    (cperl-set 'cperl-electric-lbrace-space cperl-hairy)
1156   ;;    (cperl-set 'cperl-electric-parens "{[(<")
1157   ;;    (cperl-set 'cperl-electric-keywords cperl-hairy)
1158   ;;    (cperl-set 'cperl-electric-linefeed cperl-hairy)))
1159   (use-local-map cperl-mode-map)
1160   (if (cperl-val 'cperl-electric-linefeed)
1161       (progn
1162         (local-set-key "\C-J" 'cperl-linefeed)
1163         (local-set-key "\C-C\C-J" 'newline-and-indent)))
1164   (if (cperl-val 'cperl-info-on-command-no-prompt)
1165       (progn
1166         ;; don't clobber the backspace binding:
1167         (cperl-define-key "\C-hf" 'cperl-info-on-current-command [(control h) f])
1168         (cperl-define-key "\C-c\C-hf" 'cperl-info-on-command
1169                           [(control c) (control h) f])))
1170   (setq major-mode 'perl-mode)
1171   (setq mode-name "CPerl")
1172   (if (not cperl-mode-abbrev-table)
1173       (let ((prev-a-c abbrevs-changed))
1174         (define-abbrev-table 'cperl-mode-abbrev-table '(
1175                 ("if" "if" cperl-electric-keyword 0)
1176                 ("elsif" "elsif" cperl-electric-keyword 0)
1177                 ("while" "while" cperl-electric-keyword 0)
1178                 ("until" "until" cperl-electric-keyword 0)
1179                 ("unless" "unless" cperl-electric-keyword 0)
1180                 ("else" "else" cperl-electric-else 0)
1181                 ("for" "for" cperl-electric-keyword 0)
1182                 ("foreach" "foreach" cperl-electric-keyword 0)
1183                 ("do" "do" cperl-electric-keyword 0)))
1184         (setq abbrevs-changed prev-a-c)))
1185   (setq local-abbrev-table cperl-mode-abbrev-table)
1186   (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
1187   (set-syntax-table cperl-mode-syntax-table)
1188   (make-local-variable 'paragraph-start)
1189   (setq paragraph-start (concat "^$\\|" page-delimiter))
1190   (make-local-variable 'paragraph-separate)
1191   (setq paragraph-separate paragraph-start)
1192   (make-local-variable 'paragraph-ignore-fill-prefix)
1193   (setq paragraph-ignore-fill-prefix t)
1194   (make-local-variable 'indent-line-function)
1195   (setq indent-line-function 'cperl-indent-line)
1196   (make-local-variable 'require-final-newline)
1197   (setq require-final-newline t)
1198   (make-local-variable 'comment-start)
1199   (setq comment-start "# ")
1200   (make-local-variable 'comment-end)
1201   (setq comment-end "")
1202   (make-local-variable 'comment-column)
1203   (setq comment-column cperl-comment-column)
1204   (make-local-variable 'comment-start-skip)
1205   (setq comment-start-skip "#+ *")
1206   (make-local-variable 'defun-prompt-regexp)
1207   (setq defun-prompt-regexp "^[ \t]*sub[ \t]+\\([^ \t\n{(;]+\\)[ \t]*")
1208   (make-local-variable 'comment-indent-function)
1209   (setq comment-indent-function 'cperl-comment-indent)
1210   (make-local-variable 'parse-sexp-ignore-comments)
1211   (setq parse-sexp-ignore-comments t)
1212   (make-local-variable 'indent-region-function)
1213   (setq indent-region-function 'cperl-indent-region)
1214   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
1215   (make-local-variable 'imenu-create-index-function)
1216   (setq imenu-create-index-function
1217         (function imenu-example--create-perl-index))
1218   (make-local-variable 'imenu-sort-function)
1219   (setq imenu-sort-function nil)
1220   (make-local-variable 'vc-header-alist)
1221   (setq vc-header-alist cperl-vc-header-alist)
1222   (make-local-variable 'font-lock-defaults)
1223   (setq font-lock-defaults
1224         (if (string< emacs-version "19.30")
1225             '(perl-font-lock-keywords-2)
1226           '((perl-font-lock-keywords
1227              perl-font-lock-keywords-1
1228              perl-font-lock-keywords-2))))
1229   (if cperl-use-syntax-table-text-property
1230       (progn
1231         (make-variable-buffer-local 'parse-sexp-lookup-properties)
1232         (setq parse-sexp-lookup-properties t)))
1233   (or (fboundp 'cperl-old-auto-fill-mode)
1234       (progn
1235         (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
1236         (defun auto-fill-mode (&optional arg)
1237           (interactive "P")
1238           (cperl-old-auto-fill-mode arg)
1239           (and auto-fill-function (eq major-mode 'perl-mode)
1240                (setq auto-fill-function 'cperl-do-auto-fill)))))
1241   (if (cperl-enable-font-lock)
1242       (if (cperl-val 'cperl-font-lock) 
1243           (progn (or cperl-faces-init (cperl-init-faces))
1244                  (font-lock-mode 1))))
1245   (and (boundp 'msb-menu-cond)
1246        (not cperl-msb-fixed)
1247        (cperl-msb-fix))
1248   (if (featurep 'easymenu)
1249       (easy-menu-add cperl-menu))       ; A NOP under FSF Emacs.
1250   (run-hooks 'cperl-mode-hook)
1251   ;; After hooks since fontification will break this
1252   (if cperl-pod-here-scan (cperl-find-pods-heres)))
1253 \f
1254 ;; Fix for perldb - make default reasonable
1255 (defun cperl-db ()
1256   (interactive)
1257   (require 'gud)
1258   (perldb (read-from-minibuffer "Run perldb (like this): "
1259                                 (if (consp gud-perldb-history)
1260                                     (car gud-perldb-history)
1261                                   (concat "perl " ;;(file-name-nondirectory
1262                                                    ;; I have problems
1263                                                    ;; in OS/2
1264                                                    ;; otherwise
1265                                                    (buffer-file-name)))
1266                                 nil nil
1267                                 '(gud-perldb-history . 1))))
1268 \f
1269 ;; Fix for msb.el
1270 (defvar cperl-msb-fixed nil)
1271
1272 (defun cperl-msb-fix ()
1273   ;; Adds perl files to msb menu, supposes that msb is already loaded
1274   (setq cperl-msb-fixed t)
1275   (let* ((l (length msb-menu-cond))
1276          (last (nth (1- l) msb-menu-cond))
1277          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
1278          (handle (1- (nth 1 last))))
1279     (setcdr precdr (list
1280                     (list
1281                      '(eq major-mode 'perl-mode)
1282                      handle
1283                      "Perl Files (%d)")
1284                     last))))
1285 \f
1286 ;; This is used by indent-for-comment
1287 ;; to decide how much to indent a comment in CPerl code
1288 ;; based on its context. Do fallback if comment is found wrong.
1289
1290 (defvar cperl-wrong-comment)
1291
1292 (defun cperl-comment-indent ()
1293   (let ((p (point)) (c (current-column)) was)
1294     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
1295       ;; Wrong comment found
1296       (save-excursion
1297         (setq was (cperl-to-comment-or-eol))
1298         (if (= (point) p)
1299             (progn
1300               (skip-chars-backward " \t")
1301               (max (1+ (current-column)) ; Else indent at comment column
1302                    comment-column))
1303           (if was nil
1304             (insert comment-start)
1305             (backward-char (length comment-start)))
1306           (setq cperl-wrong-comment t)
1307           (indent-to comment-column 1)  ; Indent minimum 1
1308           c)))))                        ; except leave at least one space.
1309
1310 ;;;(defun cperl-comment-indent-fallback ()
1311 ;;;  "Is called if the standard comment-search procedure fails.
1312 ;;;Point is at start of real comment."
1313 ;;;  (let ((c (current-column)) target cnt prevc)
1314 ;;;    (if (= c comment-column) nil
1315 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
1316 ;;;      (setq target (max (1+ (setq prevc 
1317 ;;;                          (current-column))) ; Else indent at comment column
1318 ;;;                comment-column))
1319 ;;;      (if (= c comment-column) nil
1320 ;;;     (delete-backward-char cnt)
1321 ;;;     (while (< prevc target)
1322 ;;;       (insert "\t")
1323 ;;;       (setq prevc (current-column)))
1324 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
1325 ;;;     (while (< prevc target)
1326 ;;;       (insert " ")
1327 ;;;       (setq prevc (current-column)))))))
1328
1329 (defun cperl-indent-for-comment ()
1330   "Substitute for `indent-for-comment' in CPerl."
1331   (interactive)
1332   (let (cperl-wrong-comment)
1333     (indent-for-comment)
1334     (if cperl-wrong-comment
1335         (progn (cperl-to-comment-or-eol)
1336                (forward-char (length comment-start))))))
1337
1338 (defun cperl-comment-region (b e arg)
1339   "Comment or uncomment each line in the region in CPerl mode.
1340 See `comment-region'."
1341   (interactive "r\np")
1342   (let ((comment-start "#"))
1343     (comment-region b e arg)))
1344
1345 (defun cperl-uncomment-region (b e arg)
1346   "Uncomment or comment each line in the region in CPerl mode.
1347 See `comment-region'."
1348   (interactive "r\np")
1349   (let ((comment-start "#"))
1350     (comment-region b e (- arg))))
1351
1352 (defvar cperl-brace-recursing nil)
1353
1354 (defun cperl-electric-brace (arg &optional only-before)
1355   "Insert character and correct line's indentation.
1356 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
1357 place (even in empty line), but not after. If after \")\" and the inserted
1358 char is \"{\", insert extra newline before only if 
1359 `cperl-extra-newline-before-brace'."
1360   (interactive "P")
1361   (let (insertpos
1362         (other-end (if (and cperl-electric-parens-mark
1363                             (cperl-mark-active) 
1364                             (< (mark) (point)))
1365                        (mark) 
1366                      nil)))
1367     (if (and other-end
1368              (not cperl-brace-recursing)
1369              (cperl-val 'cperl-electric-parens)
1370              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point)))
1371         ;; Need to insert a matching pair
1372         (progn
1373           (save-excursion
1374             (setq insertpos (point-marker))
1375             (goto-char other-end)
1376             (setq last-command-char ?\{)
1377             (cperl-electric-lbrace arg insertpos))
1378           (forward-char 1))
1379       (if (and (not arg)                ; No args, end (of empty line or auto)
1380                (eolp)
1381                (or (and (null only-before)
1382                         (save-excursion
1383                           (skip-chars-backward " \t")
1384                           (bolp)))
1385                    (and (eq last-command-char ?\{) ; Do not insert newline
1386                         ;; if after ")" and `cperl-extra-newline-before-brace'
1387                         ;; is nil, do not insert extra newline.
1388                         (not cperl-extra-newline-before-brace)
1389                         (save-excursion
1390                           (skip-chars-backward " \t")
1391                           (eq (preceding-char) ?\))))
1392                    (if cperl-auto-newline 
1393                        (progn (cperl-indent-line) (newline) t) nil)))
1394           (progn
1395             (insert last-command-char)
1396             (cperl-indent-line)
1397             (if cperl-auto-newline
1398                 (setq insertpos (1- (point))))
1399             (if (and cperl-auto-newline (null only-before))
1400                 (progn
1401                   (newline)
1402                   (cperl-indent-line)))
1403             (save-excursion
1404               (if insertpos (progn (goto-char insertpos)
1405                                    (search-forward (make-string 
1406                                                     1 last-command-char))
1407                                    (setq insertpos (1- (point)))))
1408               (delete-char -1))))
1409       (if insertpos
1410           (save-excursion
1411             (goto-char insertpos)
1412             (self-insert-command (prefix-numeric-value arg)))
1413         (self-insert-command (prefix-numeric-value arg))))))
1414
1415 (defun cperl-electric-lbrace (arg &optional end)
1416   "Insert character, correct line's indentation, correct quoting by space."
1417   (interactive "P")
1418   (let (pos after 
1419             (cperl-brace-recursing t)
1420             (cperl-auto-newline cperl-auto-newline)
1421             (other-end (or end
1422                            (if (and cperl-electric-parens-mark
1423                                     (cperl-mark-active)
1424                                     (> (mark) (point)))
1425                                (save-excursion
1426                                  (goto-char (mark))
1427                                  (point-marker)) 
1428                              nil))))
1429     (and (cperl-val 'cperl-electric-lbrace-space)
1430          (eq (preceding-char) ?$)
1431          (save-excursion
1432            (skip-chars-backward "$")
1433            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
1434          (insert ? ))
1435     (if (cperl-after-expr-p nil "{;)") nil (setq cperl-auto-newline nil))
1436     (cperl-electric-brace arg)
1437     (and (cperl-val 'cperl-electric-parens)
1438          (eq last-command-char ?{)
1439          (memq last-command-char 
1440                (append cperl-electric-parens-string nil))
1441          (or (if other-end (goto-char (marker-position other-end)))
1442              t)
1443          (setq last-command-char ?} pos (point))
1444          (progn (cperl-electric-brace arg t)
1445                 (goto-char pos)))))
1446
1447 (defun cperl-electric-paren (arg)
1448   "Insert a matching pair of parentheses."
1449   (interactive "P")
1450   (let ((beg (save-excursion (beginning-of-line) (point)))
1451         (other-end (if (and cperl-electric-parens-mark
1452                             (cperl-mark-active) 
1453                             (> (mark) (point)))
1454                            (save-excursion
1455                              (goto-char (mark))
1456                              (point-marker)) 
1457                      nil)))
1458     (if (and (cperl-val 'cperl-electric-parens)
1459              (memq last-command-char
1460                    (append cperl-electric-parens-string nil))
1461              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
1462              ;;(not (save-excursion (search-backward "#" beg t)))
1463              (if (eq last-command-char ?<)
1464                  (cperl-after-expr-p nil "{;(,:=")
1465                1))
1466         (progn
1467           (insert last-command-char)
1468           (if other-end (goto-char (marker-position other-end)))
1469           (insert (cdr (assoc last-command-char '((?{ .?})
1470                                                   (?[ . ?])
1471                                                   (?( . ?))
1472                                                   (?< . ?>)))))
1473           (forward-char -1))
1474       (insert last-command-char)
1475       )))
1476
1477 (defun cperl-electric-rparen (arg)
1478   "Insert a matching pair of parentheses if marking is active.
1479 If not, or if we are not at the end of marking range, would self-insert."
1480   (interactive "P")
1481   (let ((beg (save-excursion (beginning-of-line) (point)))
1482         (other-end (if (and cperl-electric-parens-mark
1483                             (cperl-val 'cperl-electric-parens)
1484                             (memq last-command-char
1485                                   (append cperl-electric-parens-string nil))
1486                             (cperl-mark-active) 
1487                             (< (mark) (point)))
1488                        (mark) 
1489                      nil))
1490         p)
1491     (if (and other-end
1492              (cperl-val 'cperl-electric-parens)
1493              (memq last-command-char '( ?\) ?\] ?\} ?\> ))
1494              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
1495              ;;(not (save-excursion (search-backward "#" beg t)))
1496              )
1497         (progn
1498           (insert last-command-char)
1499           (setq p (point))
1500           (if other-end (goto-char other-end))
1501           (insert (cdr (assoc last-command-char '((?\} . ?\{)
1502                                                   (?\] . ?\[)
1503                                                   (?\) . ?\()
1504                                                   (?\> . ?\<)))))
1505           (goto-char (1+ p)))
1506       (call-interactively 'self-insert-command)
1507       )))
1508
1509 (defun cperl-electric-keyword ()
1510   "Insert a construction appropriate after a keyword."
1511   (let ((beg (save-excursion (beginning-of-line) (point))) 
1512         (dollar (eq last-command-char ?$)))
1513     (and (save-excursion
1514            (backward-sexp 1)
1515            (cperl-after-expr-p nil "{;:"))
1516          (save-excursion 
1517            (not 
1518             (re-search-backward
1519              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
1520              beg t)))
1521          (save-excursion (or (not (re-search-backward "^=" nil t))
1522                              (looking-at "=cut")))
1523          (progn
1524            (and dollar (insert " $"))
1525            (cperl-indent-line)
1526            ;;(insert " () {\n}")
1527            (cond
1528             (cperl-extra-newline-before-brace
1529              (insert " ()\n")
1530              (insert "{")
1531              (cperl-indent-line)
1532              (insert "\n")
1533              (cperl-indent-line)
1534              (insert "\n}"))
1535             (t
1536              (insert " () {\n}"))
1537             )
1538            (or (looking-at "[ \t]\\|$") (insert " "))
1539            (cperl-indent-line)
1540            (if dollar (progn (search-backward "$")
1541                              (forward-char 1))
1542              (search-backward ")"))
1543            (cperl-putback-char del-back-ch)))))
1544
1545 (defun cperl-electric-else ()
1546   "Insert a construction appropriate after a keyword."
1547   (let ((beg (save-excursion (beginning-of-line) (point))))
1548     (and (save-excursion
1549            (backward-sexp 1)
1550            (cperl-after-expr-p nil "{;:"))
1551          (save-excursion 
1552            (not 
1553             (re-search-backward
1554              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
1555              beg t)))
1556          (save-excursion (or (not (re-search-backward "^=" nil t))
1557                              (looking-at "=cut")))
1558          (progn
1559            (cperl-indent-line)
1560            ;;(insert " {\n\n}")
1561            (cond
1562             (cperl-extra-newline-before-brace
1563              (insert "\n")
1564              (insert "{")
1565              (cperl-indent-line)
1566              (insert "\n\n}"))
1567             (t
1568              (insert " {\n\n}"))
1569             )
1570            (or (looking-at "[ \t]\\|$") (insert " "))
1571            (cperl-indent-line)
1572            (forward-line -1)
1573            (cperl-indent-line)
1574            (cperl-putback-char del-back-ch)))))
1575
1576 (defun cperl-linefeed ()
1577   "Go to end of line, open a new line and indent appropriately."
1578   (interactive)
1579   (let ((beg (save-excursion (beginning-of-line) (point)))
1580         (end (save-excursion (end-of-line) (point)))
1581         (pos (point)) start)
1582     (if (and                            ; Check if we need to split:
1583                                         ; i.e., on a boundary and inside "{...}" 
1584          (save-excursion (cperl-to-comment-or-eol)
1585            (>= (point) pos))            ; Not in a comment
1586          (or (save-excursion
1587                (skip-chars-backward " \t" beg)
1588                (forward-char -1)
1589                (looking-at "[;{]"))     ; After { or ; + spaces
1590              (looking-at "[ \t]*}")     ; Before }
1591              (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
1592          (save-excursion
1593            (and
1594             (eq (car (parse-partial-sexp pos end -1)) -1) 
1595                                         ; Leave the level of parens
1596             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
1597                                         ; Are at end
1598             (progn
1599               (backward-sexp 1)
1600               (setq start (point-marker))
1601               (<= start pos)))))        ; Redundant? Are after the
1602                                         ; start of parens group.
1603         (progn
1604           (skip-chars-backward " \t")
1605           (or (memq (preceding-char) (append ";{" nil))
1606               (insert ";"))
1607           (insert "\n")
1608           (forward-line -1)
1609           (cperl-indent-line)
1610           (goto-char start)
1611           (or (looking-at "{[ \t]*$")   ; If there is a statement
1612                                         ; before, move it to separate line
1613               (progn
1614                 (forward-char 1)
1615                 (insert "\n")
1616                 (cperl-indent-line)))
1617           (forward-line 1)              ; We are on the target line
1618           (cperl-indent-line)
1619           (beginning-of-line)
1620           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
1621                                             ; after, move it to separate line
1622               (progn
1623                 (end-of-line)
1624                 (search-backward "}" beg)
1625                 (skip-chars-backward " \t")
1626                 (or (memq (preceding-char) (append ";{" nil))
1627                     (insert ";"))
1628                 (insert "\n")
1629                 (cperl-indent-line)
1630                 (forward-line -1)))
1631           (forward-line -1)             ; We are on the line before target 
1632           (end-of-line)
1633           (newline-and-indent))
1634       (end-of-line)                     ; else
1635       (cond
1636        ((and (looking-at "\n[ \t]*{$")
1637              (save-excursion
1638                (skip-chars-backward " \t")
1639                (eq (preceding-char) ?\)))) ; Probably if () {} group
1640                                            ; with an extra newline.
1641         (forward-line 2)
1642         (cperl-indent-line))
1643        ((looking-at "\n[ \t]*$")        ; Next line is empty - use it.
1644         (forward-line 1)
1645         (cperl-indent-line))
1646        (t
1647         (newline-and-indent))))))
1648
1649 (defun cperl-electric-semi (arg)
1650   "Insert character and correct line's indentation."
1651   (interactive "P")
1652   (if cperl-auto-newline
1653       (cperl-electric-terminator arg)
1654     (self-insert-command (prefix-numeric-value arg))))
1655
1656 (defun cperl-electric-terminator (arg)
1657   "Insert character and correct line's indentation."
1658   (interactive "P")
1659   (let (insertpos (end (point)) 
1660                   (auto (and cperl-auto-newline
1661                              (or (not (eq last-command-char ?:))
1662                                  cperl-auto-newline-after-colon))))
1663     (if (and ;;(not arg) 
1664              (eolp)
1665              (not (save-excursion
1666                     (beginning-of-line)
1667                     (skip-chars-forward " \t")
1668                     (or
1669                      ;; Ignore in comment lines
1670                      (= (following-char) ?#)
1671                      ;; Colon is special only after a label
1672                      ;; So quickly rule out most other uses of colon
1673                      ;; and do no indentation for them.
1674                      (and (eq last-command-char ?:)
1675                           (save-excursion
1676                             (forward-word 1)
1677                             (skip-chars-forward " \t")
1678                             (and (< (point) end)
1679                                  (progn (goto-char (- end 1))
1680                                         (not (looking-at ":"))))))
1681                      (progn
1682                        (beginning-of-defun)
1683                        (let ((pps (parse-partial-sexp (point) end)))
1684                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
1685         (progn
1686           (insert last-command-char)
1687           ;;(forward-char -1)
1688           (if auto (setq insertpos (point-marker)))
1689           ;;(forward-char 1)
1690           (cperl-indent-line)
1691           (if auto
1692               (progn
1693                 (newline)
1694                 (cperl-indent-line)))
1695 ;;        (save-excursion
1696 ;;          (if insertpos (progn (goto-char (marker-position insertpos))
1697 ;;                               (search-forward (make-string 
1698 ;;                                                1 last-command-char))
1699 ;;                               (setq insertpos (1- (point)))))
1700 ;;          (delete-char -1))))
1701           (save-excursion
1702             (if insertpos (goto-char (1- (marker-position insertpos)))
1703               (forward-char -1))
1704             (delete-char 1))))
1705     (if insertpos
1706         (save-excursion
1707           (goto-char insertpos)
1708           (self-insert-command (prefix-numeric-value arg)))
1709       (self-insert-command (prefix-numeric-value arg)))))
1710
1711 (defun cperl-electric-backspace (arg)
1712   "Backspace-untabify, or remove the whitespace inserted by an electric key."
1713   (interactive "p")
1714   (if (and cperl-auto-newline 
1715            (memq last-command '(cperl-electric-semi 
1716                                 cperl-electric-terminator
1717                                 cperl-electric-lbrace))
1718            (memq (preceding-char) '(?  ?\t ?\n)))
1719       (let (p)
1720         (if (eq last-command 'cperl-electric-lbrace) 
1721             (skip-chars-forward " \t\n"))
1722         (setq p (point))
1723         (skip-chars-backward " \t\n")
1724         (delete-region (point) p))
1725     (backward-delete-char-untabify arg)))
1726
1727 (defun cperl-inside-parens-p ()
1728   (condition-case ()
1729       (save-excursion
1730         (save-restriction
1731           (narrow-to-region (point)
1732                             (progn (beginning-of-defun) (point)))
1733           (goto-char (point-max))
1734           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
1735     (error nil)))
1736 \f
1737 (defun cperl-indent-command (&optional whole-exp)
1738   "Indent current line as Perl code, or in some cases insert a tab character.
1739 If `cperl-tab-always-indent' is non-nil (the default), always indent current line.
1740 Otherwise, indent the current line only if point is at the left margin
1741 or in the line's indentation; otherwise insert a tab.
1742
1743 A numeric argument, regardless of its value,
1744 means indent rigidly all the lines of the expression starting after point
1745 so that this line becomes properly indented.
1746 The relative indentation among the lines of the expression are preserved."
1747   (interactive "P")
1748   (if whole-exp
1749       ;; If arg, always indent this line as Perl
1750       ;; and shift remaining lines of expression the same amount.
1751       (let ((shift-amt (cperl-indent-line))
1752             beg end)
1753         (save-excursion
1754           (if cperl-tab-always-indent
1755               (beginning-of-line))
1756           (setq beg (point))
1757           (forward-sexp 1)
1758           (setq end (point))
1759           (goto-char beg)
1760           (forward-line 1)
1761           (setq beg (point)))
1762         (if (> end beg)
1763             (indent-code-rigidly beg end shift-amt "#")))
1764     (if (and (not cperl-tab-always-indent)
1765              (save-excursion
1766                (skip-chars-backward " \t")
1767                (not (bolp))))
1768         (insert-tab)
1769       (cperl-indent-line))))
1770
1771 (defun cperl-indent-line (&optional symbol)
1772   "Indent current line as Perl code.
1773 Return the amount the indentation changed by."
1774   (let (indent
1775         beg shift-amt
1776         (case-fold-search nil)
1777         (pos (- (point-max) (point))))
1778     (setq indent (cperl-calculate-indent nil symbol))
1779     (beginning-of-line)
1780     (setq beg (point))
1781     (cond ((or (eq indent nil) (eq indent t))
1782            (setq indent (current-indentation)))
1783           ;;((eq indent t)    ; Never?
1784           ;; (setq indent (cperl-calculate-indent-within-comment)))
1785           ;;((looking-at "[ \t]*#")
1786           ;; (setq indent 0))
1787           (t
1788            (skip-chars-forward " \t")
1789            (if (listp indent) (setq indent (car indent)))
1790            (cond ((looking-at "[A-Za-z_][A-Za-z_0-9]*:[^:]")
1791                   (and (> indent 0)
1792                        (setq indent (max cperl-min-label-indent
1793                                          (+ indent cperl-label-offset)))))
1794                  ((= (following-char) ?})
1795                   (setq indent (- indent cperl-indent-level)))
1796                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
1797                   (setq indent (+ indent cperl-close-paren-offset)))
1798                  ((= (following-char) ?{)
1799                   (setq indent (+ indent cperl-brace-offset))))))
1800     (skip-chars-forward " \t")
1801     (setq shift-amt (- indent (current-column)))
1802     (if (zerop shift-amt)
1803         (if (> (- (point-max) pos) (point))
1804             (goto-char (- (point-max) pos)))
1805       (delete-region beg (point))
1806       (indent-to indent)
1807       ;; If initial point was within line's indentation,
1808       ;; position after the indentation.  Else stay at same point in text.
1809       (if (> (- (point-max) pos) (point))
1810           (goto-char (- (point-max) pos))))
1811     shift-amt))
1812
1813 (defun cperl-after-label ()
1814   ;; Returns true if the point is after label. Does not do save-excursion.
1815   (and (eq (preceding-char) ?:)
1816        (memq (char-syntax (char-after (- (point) 2)))
1817              '(?w ?_))
1818        (progn
1819          (backward-sexp)
1820          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))
1821
1822 (defun cperl-get-state (&optional parse-start start-state)
1823   ;; returns list (START STATE DEPTH PRESTART), START is a good place
1824   ;; to start parsing, STATE is what is returned by
1825   ;; `parse-partial-sexp'. DEPTH is true is we are immediately after
1826   ;; end of block which contains START. PRESTART is the position
1827   ;; basing on which START was found.
1828   (save-excursion
1829     (let ((start-point (point)) depth state start prestart)
1830       (if parse-start
1831           (goto-char parse-start)
1832         (beginning-of-defun))
1833       (setq prestart (point))
1834       (if start-state nil
1835         ;; Try to go out, if sub is not on the outermost level
1836         (while (< (point) start-point)
1837           (setq start (point) parse-start start depth nil
1838                 state (parse-partial-sexp start start-point -1))
1839           (if (> (car state) -1) nil
1840             ;; The current line could start like }}}, so the indentation
1841             ;; corresponds to a different level than what we reached
1842             (setq depth t)
1843             (beginning-of-line 2)))     ; Go to the next line.
1844         (if start (goto-char start)))   ; Not at the start of file
1845       (setq start (point))
1846       (if (< start start-point) (setq parse-start start))
1847       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
1848       (list start state depth prestart))))
1849
1850 (defun cperl-block-p ()                 ; Do not C-M-q ! One string contains ";" !
1851   ;; Positions is before ?\{. Checks whether it starts a block.
1852   ;; No save-excursion!
1853   (cperl-backward-to-noncomment (point-min))
1854   ;;(skip-chars-backward " \t\n\f")
1855   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label! \C-@ at bobp
1856                                         ; Label may be mixed up with `$blah :'
1857       (save-excursion (cperl-after-label))
1858       (and (memq (char-syntax (preceding-char)) '(?w ?_))
1859            (progn
1860              (backward-sexp)
1861              ;; Need take into account `bless', `return', `tr',...
1862              (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
1863                       (not (looking-at "\\(bless\\|return\\|qw\\|tr\\|[smy]\\)\\>")))
1864                  (progn
1865                    (skip-chars-backward " \t\n\f")
1866                    (and (memq (char-syntax (preceding-char)) '(?w ?_))
1867                         (progn
1868                           (backward-sexp)
1869                           (looking-at 
1870                            "sub[ \t]+[a-zA-Z0-9_:]+[ \t\n\f]*\\(([^()]*)[ \t\n\f]*\\)?[#{]")))))))))
1871
1872 (defvar cperl-look-for-prop '((pod in-pod) (here-doc-delim here-doc-group)))
1873
1874 (defun cperl-calculate-indent (&optional parse-start symbol)
1875   "Return appropriate indentation for current line as Perl code.
1876 In usual case returns an integer: the column to indent to.
1877 Returns nil if line starts inside a string, t if in a comment."
1878   (save-excursion
1879     (if (or
1880          (memq (get-text-property (point) 'syntax-type) 
1881                '(pod here-doc here-doc-delim format))
1882          ;; before start of POD - whitespace found since do not have 'pod!
1883          (and (looking-at "[ \t]*\n=")
1884               (error "Spaces before pod section!")))
1885         nil
1886      (beginning-of-line)
1887      (let ((indent-point (point))
1888            (char-after (save-excursion
1889                            (skip-chars-forward " \t")
1890                            (following-char)))
1891            (in-pod (get-text-property (point) 'in-pod))
1892            (pre-indent-point (point))
1893            p prop look-prop)
1894       (cond
1895        (in-pod                          
1896         ;; In the verbatim part, probably code example. What to do???
1897         )
1898        (t 
1899         (save-excursion
1900           ;; Not in pod
1901           (cperl-backward-to-noncomment nil)
1902           (setq p (max (point-min) (1- (point)))
1903                 prop (get-text-property p 'syntax-type)
1904                 look-prop (or (nth 1 (assoc prop cperl-look-for-prop))
1905                               'syntax-type))
1906           (if (memq prop '(pod here-doc format here-doc-delim))
1907               (progn
1908                 (goto-char (or (previous-single-property-change p look-prop) 
1909                                (point-min)))
1910                 (beginning-of-line)
1911                 (setq pre-indent-point (point)))))))
1912       (goto-char pre-indent-point)
1913       (let* ((case-fold-search nil)
1914              (s-s (cperl-get-state))
1915              (start (nth 0 s-s))
1916              (state (nth 1 s-s))
1917              (containing-sexp (car (cdr state)))
1918              (start-indent (save-excursion
1919                              (goto-char start)
1920                              (- (current-indentation)
1921                                 (if (nth 2 s-s) cperl-indent-level 0))))
1922              old-indent)
1923         ;;      (or parse-start (null symbol)
1924         ;;        (setq parse-start (symbol-value symbol) 
1925         ;;              start-indent (nth 2 parse-start) 
1926         ;;              parse-start (car parse-start)))
1927         ;;      (if parse-start
1928         ;;        (goto-char parse-start)
1929         ;;      (beginning-of-defun))
1930         ;;      ;; Try to go out
1931         ;;      (while (< (point) indent-point)
1932         ;;      (setq start (point) parse-start start moved nil
1933         ;;            state (parse-partial-sexp start indent-point -1))
1934         ;;      (if (> (car state) -1) nil
1935         ;;        ;; The current line could start like }}}, so the indentation
1936         ;;        ;; corresponds to a different level than what we reached
1937         ;;        (setq moved t)
1938         ;;        (beginning-of-line 2)))       ; Go to the next line.
1939         ;;      (if start                               ; Not at the start of file
1940         ;;        (progn
1941         ;;          (goto-char start)
1942         ;;          (setq start-indent (current-indentation))
1943         ;;          (if moved                   ; Should correct...
1944         ;;              (setq start-indent (- start-indent cperl-indent-level))))
1945         ;;      (setq start-indent 0))
1946         ;;      (if (< (point) indent-point) (setq parse-start (point)))
1947         ;;      (or state (setq state (parse-partial-sexp 
1948         ;;                           (point) indent-point -1 nil start-state)))
1949         ;;      (setq containing-sexp 
1950         ;;          (or (car (cdr state)) 
1951         ;;              (and (>= (nth 6 state) 0) old-containing-sexp))
1952         ;;          old-containing-sexp nil start-state nil)
1953 ;;;;      (while (< (point) indent-point)
1954 ;;;;    (setq parse-start (point))
1955 ;;;;    (setq state (parse-partial-sexp (point) indent-point -1 nil start-state))
1956 ;;;;    (setq containing-sexp 
1957 ;;;;          (or (car (cdr state)) 
1958 ;;;;              (and (>= (nth 6 state) 0) old-containing-sexp))
1959 ;;;;          old-containing-sexp nil start-state nil))
1960         ;;      (if symbol (set symbol (list indent-point state start-indent)))
1961         ;;      (goto-char indent-point)
1962         (cond ((or (nth 3 state) (nth 4 state))
1963                ;; return nil or t if should not change this line
1964                (nth 4 state))
1965               ((null containing-sexp)
1966                ;; Line is at top level.  May be data or function definition,
1967                ;; or may be function argument declaration.
1968                ;; Indent like the previous top level line
1969                ;; unless that ends in a closeparen without semicolon,
1970                ;; in which case this line is the first argument decl.
1971                (skip-chars-forward " \t")
1972                (+ start-indent
1973                   (if (= (following-char) ?{) cperl-continued-brace-offset 0)
1974                   (progn
1975                     (cperl-backward-to-noncomment (or parse-start (point-min)))
1976                     ;;(skip-chars-backward " \t\f\n")
1977                     ;; Look at previous line that's at column 0
1978                     ;; to determine whether we are in top-level decls
1979                     ;; or function's arg decls.  Set basic-indent accordingly.
1980                     ;; Now add a little if this is a continuation line.
1981                     (if (or (bobp)
1982                             (memq (preceding-char) (append " ;}" nil)) ; Was ?\)
1983                             (memq char-after (append ")]}" nil))
1984                             (and (eq (preceding-char) ?\:) ; label
1985                                  (progn
1986                                    (forward-sexp -1)
1987                                    (skip-chars-backward " \t")
1988                                    (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*[ \t]*:")))) 
1989                         0
1990                       cperl-continued-statement-offset))))
1991               ((/= (char-after containing-sexp) ?{)
1992                ;; line is expression, not statement:
1993                ;; indent to just after the surrounding open,
1994                ;; skip blanks if we do not close the expression.
1995                (goto-char (1+ containing-sexp))
1996                (or (memq char-after (append ")]}" nil))
1997                    (looking-at "[ \t]*\\(#\\|$\\)")
1998                    (skip-chars-forward " \t"))
1999                (current-column))
2000               ((progn
2001                  ;; Containing-expr starts with \{. Check whether it is a hash.
2002                  (goto-char containing-sexp)
2003                  (not (cperl-block-p)))
2004                (goto-char (1+ containing-sexp))
2005                (or (eq char-after ?\})
2006                    (looking-at "[ \t]*\\(#\\|$\\)")
2007                    (skip-chars-forward " \t"))
2008                (+ (current-column)      ; Correct indentation of trailing ?\}
2009                   (if (eq char-after ?\}) (+ cperl-indent-level
2010                                              cperl-close-paren-offset) 
2011                     0)))
2012               (t
2013                ;; Statement level.  Is it a continuation or a new statement?
2014                ;; Find previous non-comment character.
2015                (goto-char pre-indent-point)
2016                (cperl-backward-to-noncomment containing-sexp)
2017                ;; Back up over label lines, since they don't
2018                ;; affect whether our line is a continuation.
2019                (while (or (eq (preceding-char) ?\,)
2020                           (and (eq (preceding-char) ?:)
2021                                (or;;(eq (char-after (- (point) 2)) ?\') ; ????
2022                                 (memq (char-syntax (char-after (- (point) 2)))
2023                                       '(?w ?_)))))
2024                  (if (eq (preceding-char) ?\,)
2025                      ;; Will go to beginning of line, essentially.
2026                      ;; Will ignore embedded sexpr XXXX.
2027                      (cperl-backward-to-start-of-continued-exp containing-sexp))
2028                  (beginning-of-line)
2029                  (cperl-backward-to-noncomment containing-sexp))
2030                ;; Now we get the answer.
2031                (if (not (memq (preceding-char) (append ", ;}{" '(nil)))) ; Was ?\,
2032                    ;; This line is continuation of preceding line's statement;
2033                    ;; indent  `cperl-continued-statement-offset'  more than the
2034                    ;; previous line of the statement.
2035                    (progn
2036                      (cperl-backward-to-start-of-continued-exp containing-sexp)
2037                      (+ (if (memq char-after (append "}])" nil))
2038                             0           ; Closing parenth
2039                           cperl-continued-statement-offset)
2040                         (current-column)
2041                         (if (eq char-after ?\{)
2042                             cperl-continued-brace-offset 0)))
2043                  ;; This line starts a new statement.
2044                  ;; Position following last unclosed open.
2045                  (goto-char containing-sexp)
2046                  ;; Is line first statement after an open-brace?
2047                  (or
2048                   ;; If no, find that first statement and indent like
2049                   ;; it.  If the first statement begins with label, do
2050                   ;; not believe when the indentation of the label is too
2051                   ;; small.
2052                   (save-excursion
2053                     (forward-char 1)
2054                     (setq old-indent (current-indentation))
2055                     (let ((colon-line-end 0))
2056                       (while (progn (skip-chars-forward " \t\n")
2057                                     (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]"))
2058                         ;; Skip over comments and labels following openbrace.
2059                         (cond ((= (following-char) ?\#)
2060                                (forward-line 1))
2061                               ;; label:
2062                               (t
2063                                (save-excursion (end-of-line)
2064                                                (setq colon-line-end (point)))
2065                                (search-forward ":"))))
2066                       ;; The first following code counts
2067                       ;; if it is before the line we want to indent.
2068                       (and (< (point) indent-point)
2069                            (if (> colon-line-end (point)) ; After label
2070                                (if (> (current-indentation) 
2071                                       cperl-min-label-indent)
2072                                    (- (current-indentation) cperl-label-offset)
2073                                  ;; Do not believe: `max' is involved
2074                                  (+ old-indent cperl-indent-level))
2075                              (current-column)))))
2076                   ;; If no previous statement,
2077                   ;; indent it relative to line brace is on.
2078                   ;; For open brace in column zero, don't let statement
2079                   ;; start there too.  If cperl-indent-level is zero,
2080                   ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
2081                   ;; For open-braces not the first thing in a line,
2082                   ;; add in cperl-brace-imaginary-offset.
2083
2084                   ;; If first thing on a line:  ?????
2085                   (+ (if (and (bolp) (zerop cperl-indent-level))
2086                          (+ cperl-brace-offset cperl-continued-statement-offset)
2087                        cperl-indent-level)
2088                      ;; Move back over whitespace before the openbrace.
2089                      ;; If openbrace is not first nonwhite thing on the line,
2090                      ;; add the cperl-brace-imaginary-offset.
2091                      (progn (skip-chars-backward " \t")
2092                             (if (bolp) 0 cperl-brace-imaginary-offset))
2093                      ;; If the openbrace is preceded by a parenthesized exp,
2094                      ;; move to the beginning of that;
2095                      ;; possibly a different line
2096                      (progn
2097                        (if (eq (preceding-char) ?\))
2098                            (forward-sexp -1))
2099                        ;; In the case it starts a subroutine, indent with
2100                        ;; respect to `sub', not with respect to the the
2101                        ;; first thing on the line, say in the case of
2102                        ;; anonymous sub in a hash.
2103                        ;;
2104                        (skip-chars-backward " \t")
2105                        (if (and (eq (preceding-char) ?b)
2106                                 (progn
2107                                   (forward-sexp -1)
2108                                   (looking-at "sub\\>"))
2109                                 (setq old-indent 
2110                                       (nth 1 
2111                                            (parse-partial-sexp 
2112                                             (save-excursion (beginning-of-line) (point)) 
2113                                             (point)))))
2114                            (progn (goto-char (1+ old-indent))
2115                                   (skip-chars-forward " \t")
2116                                   (current-column))
2117                          ;; Get initial indentation of the line we are on.
2118                          ;; If line starts with label, calculate label indentation
2119                          (if (save-excursion
2120                                (beginning-of-line)
2121                                (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
2122                              (if (> (current-indentation) cperl-min-label-indent)
2123                                  (- (current-indentation) cperl-label-offset)
2124                                (cperl-calculate-indent 
2125                                 (if (and parse-start (<= parse-start (point)))
2126                                     parse-start)))
2127                            (current-indentation))))))))))))))
2128
2129 (defvar cperl-indent-alist
2130   '((string nil)
2131     (comment nil)
2132     (toplevel 0)
2133     (toplevel-after-parenth 2)
2134     (toplevel-continued 2)
2135     (expression 1))
2136   "Alist of indentation rules for CPerl mode.
2137 The values mean:
2138   nil: do not indent;
2139   number: add this amount of indentation.")
2140
2141 (defun cperl-where-am-i (&optional parse-start start-state)
2142   ;; Unfinished
2143   "Return a list of lists ((TYPE POS)...) of good points before the point.
2144 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'."
2145   (save-excursion
2146     (let* ((start-point (point))
2147            (s-s (cperl-get-state))
2148            (start (nth 0 s-s))
2149            (state (nth 1 s-s))
2150            (prestart (nth 3 s-s))
2151            (containing-sexp (car (cdr state)))
2152            (case-fold-search nil)
2153            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
2154       (cond ((nth 3 state)              ; In string
2155              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
2156             ((nth 4 state)              ; In comment
2157              (setq res (cons '(comment) res)))
2158             ((null containing-sexp)
2159              ;; Line is at top level.  
2160              ;; Indent like the previous top level line
2161              ;; unless that ends in a closeparen without semicolon,
2162              ;; in which case this line is the first argument decl.
2163              (cperl-backward-to-noncomment (or parse-start (point-min)))
2164              ;;(skip-chars-backward " \t\f\n")
2165              (cond
2166               ((or (bobp)
2167                    (memq (preceding-char) (append ";}" nil)))
2168                (setq res (cons (list 'toplevel start) res)))
2169               ((eq (preceding-char) ?\) )
2170                (setq res (cons (list 'toplevel-after-parenth start) res)))
2171               (t 
2172                (setq res (cons (list 'toplevel-continued start) res)))))
2173             ((/= (char-after containing-sexp) ?{)
2174              ;; line is expression, not statement:
2175              ;; indent to just after the surrounding open.
2176              ;; skip blanks if we do not close the expression.
2177              (setq res (cons (list 'expression-blanks
2178                                    (progn
2179                                      (goto-char (1+ containing-sexp))
2180                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
2181                                          (skip-chars-forward " \t"))
2182                                      (point)))
2183                              (cons (list 'expression containing-sexp) res))))
2184             ((progn
2185               ;; Containing-expr starts with \{. Check whether it is a hash.
2186               (goto-char containing-sexp)
2187               (not (cperl-block-p)))
2188              (setq res (cons (list 'expression-blanks
2189                                    (progn
2190                                      (goto-char (1+ containing-sexp))
2191                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
2192                                          (skip-chars-forward " \t"))
2193                                      (point)))
2194                              (cons (list 'expression containing-sexp) res))))
2195             (t
2196              ;; Statement level.
2197              (setq res (cons (list 'in-block containing-sexp) res))
2198              ;; Is it a continuation or a new statement?
2199              ;; Find previous non-comment character.
2200              (cperl-backward-to-noncomment containing-sexp)
2201              ;; Back up over label lines, since they don't
2202              ;; affect whether our line is a continuation.
2203              ;; Back up comma-delimited lines too ?????
2204              (while (or (eq (preceding-char) ?\,)
2205                         (save-excursion (cperl-after-label)))
2206                (if (eq (preceding-char) ?\,)
2207                    ;; Will go to beginning of line, essentially
2208                      ;; Will ignore embedded sexpr XXXX.
2209                    (cperl-backward-to-start-of-continued-exp containing-sexp))
2210                (beginning-of-line)
2211                (cperl-backward-to-noncomment containing-sexp))
2212              ;; Now we get the answer.
2213              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
2214                  ;; This line is continuation of preceding line's statement.
2215                  (list (list 'statement-continued containing-sexp))
2216                ;; This line starts a new statement.
2217                ;; Position following last unclosed open.
2218                (goto-char containing-sexp)
2219                ;; Is line first statement after an open-brace?
2220                (or
2221                 ;; If no, find that first statement and indent like
2222                 ;; it.  If the first statement begins with label, do
2223                 ;; not believe when the indentation of the label is too
2224                 ;; small.
2225                 (save-excursion
2226                   (forward-char 1)
2227                   (let ((colon-line-end 0))
2228                     (while (progn (skip-chars-forward " \t\n" start-point)
2229                                   (and (< (point) start-point)
2230                                        (looking-at
2231                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
2232                       ;; Skip over comments and labels following openbrace.
2233                       (cond ((= (following-char) ?\#)
2234                              ;;(forward-line 1)
2235                              (end-of-line))
2236                             ;; label:
2237                             (t
2238                              (save-excursion (end-of-line)
2239                                              (setq colon-line-end (point)))
2240                              (search-forward ":"))))
2241                     ;; Now at the point, after label, or at start 
2242                     ;; of first statement in the block.
2243                     (and (< (point) start-point)
2244                          (if (> colon-line-end (point)) 
2245                              ;; Before statement after label
2246                              (if (> (current-indentation) 
2247                                     cperl-min-label-indent)
2248                                  (list (list 'label-in-block (point)))
2249                                ;; Do not believe: `max' is involved
2250                                (list
2251                                 (list 'label-in-block-min-indent (point))))
2252                            ;; Before statement
2253                            (list 'statement-in-block (point))))))
2254                 ;; If no previous statement,
2255                 ;; indent it relative to line brace is on.
2256                 ;; For open brace in column zero, don't let statement
2257                 ;; start there too.  If cperl-indent-level is zero,
2258                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
2259                 ;; For open-braces not the first thing in a line,
2260                 ;; add in cperl-brace-imaginary-offset.
2261
2262                 ;; If first thing on a line:  ?????
2263                 (+ (if (and (bolp) (zerop cperl-indent-level))
2264                        (+ cperl-brace-offset cperl-continued-statement-offset)
2265                      cperl-indent-level)
2266                    ;; Move back over whitespace before the openbrace.
2267                    ;; If openbrace is not first nonwhite thing on the line,
2268                    ;; add the cperl-brace-imaginary-offset.
2269                    (progn (skip-chars-backward " \t")
2270                           (if (bolp) 0 cperl-brace-imaginary-offset))
2271                    ;; If the openbrace is preceded by a parenthesized exp,
2272                    ;; move to the beginning of that;
2273                    ;; possibly a different line
2274                    (progn
2275                      (if (eq (preceding-char) ?\))
2276                          (forward-sexp -1))
2277                      ;; Get initial indentation of the line we are on.
2278                      ;; If line starts with label, calculate label indentation
2279                      (if (save-excursion
2280                            (beginning-of-line)
2281                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
2282                          (if (> (current-indentation) cperl-min-label-indent)
2283                              (- (current-indentation) cperl-label-offset)
2284                            (cperl-calculate-indent 
2285                             (if (and parse-start (<= parse-start (point)))
2286                                 parse-start)))
2287                        (current-indentation))))))))
2288       res)))
2289
2290 (defun cperl-calculate-indent-within-comment ()
2291   "Return the indentation amount for line, assuming that
2292 the current line is to be regarded as part of a block comment."
2293   (let (end star-start)
2294     (save-excursion
2295       (beginning-of-line)
2296       (skip-chars-forward " \t")
2297       (setq end (point))
2298       (and (= (following-char) ?#)
2299            (forward-line -1)
2300            (cperl-to-comment-or-eol)
2301            (setq end (point)))
2302       (goto-char end)
2303       (current-column))))
2304
2305
2306 (defun cperl-to-comment-or-eol ()
2307   "Goes to position before comment on the current line, or to end of line.
2308 Returns true if comment is found."
2309   (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
2310       (beginning-of-line)
2311       (if (or 
2312            (eq (get-text-property (point) 'syntax-type) 'pod)
2313            (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t))
2314           (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
2315         ;; Else
2316         (while (not stop-in)
2317           (setq state (parse-partial-sexp (point) lim nil nil nil t))
2318                                         ; stop at comment
2319           ;; If fails (beginning-of-line inside sexp), then contains not-comment
2320           ;; Do simplified processing
2321           ;;(if (re-search-forward "[^$]#" lim 1)
2322           ;;      (progn
2323           ;;    (forward-char -1)
2324           ;;    (skip-chars-backward " \t\n\f" lim))
2325           ;;    (goto-char lim))                ; No `#' at all
2326           ;;)
2327           (if (nth 4 state)             ; After `#';
2328                                         ; (nth 2 state) can be
2329                                         ; beginning of m,s,qq and so
2330                                         ; on
2331               (if (nth 2 state)
2332                   (progn
2333                     (setq cpoint (point))
2334                     (goto-char (nth 2 state))
2335                     (cond
2336                      ((looking-at "\\(s\\|tr\\)\\>")
2337                       (or (re-search-forward
2338                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
2339                            lim 'move)
2340                           (setq stop-in t)))
2341                      ((looking-at "\\(m\\|q\\([qxw]\\)?\\)\\>")
2342                       (or (re-search-forward
2343                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
2344                            lim 'move)
2345                           (setq stop-in t)))
2346                      (t                 ; It was fair comment
2347                       (setq stop-in t)  ; Finish
2348                       (goto-char (1- cpoint)))))
2349                 (setq stop-in t)        ; Finish
2350                 (forward-char -1))
2351             (setq stop-in t))           ; Finish
2352           )
2353         (nth 4 state))))
2354
2355 (defsubst cperl-1- (p)
2356   (max (point-min) (1- p)))
2357
2358 (defsubst cperl-1+ (p)
2359   (min (point-max) (1+ p)))
2360
2361 (defvar cperl-st-cfence '(14))          ; Comment-fence
2362 (defvar cperl-st-sfence '(15))          ; String-fence
2363 (defvar cperl-st-punct '(1))
2364 (defvar cperl-st-word '(2))
2365
2366 (defun cperl-protect-defun-start (s e)
2367   ;; C code looks for "^\\s(" to skip comment backward in "hard" situations
2368   (save-excursion
2369     (goto-char s)
2370     (while (re-search-forward "^\\s(" e 'to-end)
2371       (put-text-property (1- (point)) (point) 'syntax-table cperl-st-punct))))
2372
2373 (defun cperl-commentify (bb e string)
2374   (if cperl-use-syntax-table-text-property 
2375       (progn
2376         ;; We suppose that e is _after_ the end of construction, as after eol.
2377         (setq string (if string cperl-st-sfence cperl-st-cfence))
2378         (put-text-property bb (1+ bb) 'syntax-table string)
2379         (put-text-property bb (1+ bb) 'rear-nonsticky t)
2380         (put-text-property (1- e) e 'syntax-table string)
2381         (put-text-property (1- e) e 'rear-nonsticky t)
2382         (if (and (eq string cperl-st-sfence) (> (- e 2) bb))
2383             (put-text-property (1+ bb) (1- e) 
2384                                'syntax-table cperl-string-syntax-table))
2385         (cperl-protect-defun-start bb e))))
2386
2387 (defun cperl-find-pods-heres (&optional min max)
2388   "Scans the buffer for POD sections and here-documents.
2389 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify 
2390 the sections using `cperl-pod-head-face', `cperl-pod-face', 
2391 `cperl-here-face'."
2392   (interactive)
2393   (or min (setq min (point-min)))
2394   (or max (setq max (point-max)))
2395   (let (face head-face here-face b e bb tag qtag err b1 e1 argument st i c
2396              (cperl-pod-here-fontify (eval cperl-pod-here-fontify))
2397              (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
2398              (modified (buffer-modified-p))
2399              (after-change-functions nil)
2400              (state-point (point-min)) state
2401              (search
2402               (concat
2403                "\\(\\`\n?\\|\n\n\\)=" 
2404                "\\|"
2405                ;; One extra () before this:
2406                "<<" 
2407                  "\\(" 
2408                  ;; First variant "BLAH" or just ``.
2409                     "\\([\"'`]\\)"
2410                     "\\([^\"'`\n]*\\)"
2411                     "\\3"
2412                  "\\|"
2413                  ;; Second variant: Identifier or empty
2414                    "\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)"
2415                    ;; Check that we do not have <<= or << 30 or << $blah.
2416                    "\\([^= \t$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)"
2417                  "\\)"
2418                "\\|"
2419                ;; 1+6 extra () before this:
2420                "^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
2421                (if cperl-use-syntax-table-text-property
2422                    (concat
2423                     "\\|"
2424                     ;; 1+6+2=9 extra () before this:
2425                     "\\<\\(q[wxq]?\\|[msy]\\|tr\\)\\>"
2426                     "\\|"
2427                     ;; 1+6+2+1=10 extra () before this:
2428                     "\\([?/]\\)"        ; /blah/ or ?blah?
2429                     "\\|"
2430                     ;; 1+6+2+1+1=11 extra () before this:
2431                     "\\<sub\\>[ \t]*\\([a-zA-Z_:'0-9]+[ \t]*\\)?\\(([^()]*)\\)"
2432                     "\\|"
2433                     ;; 1+6+2+1+1+2=13 extra () before this:
2434                     "\\$\\(['{]\\)"
2435                     "\\|"
2436                     ;; 1+6+2+1+1+2+1=14 extra () before this:
2437                     "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'")
2438                  ""))))
2439     (unwind-protect
2440         (progn
2441           (save-excursion
2442             (message "Scanning for pods, formats and here-docs...")
2443             (if cperl-pod-here-fontify
2444                 ;; We had evals here, do not know why...
2445                 (setq face cperl-pod-face
2446                       head-face cperl-pod-head-face
2447                       here-face cperl-here-face))
2448             (remove-text-properties min max 
2449                                     '(syntax-type t in-pod t syntax-table t))
2450             ;; Need to remove face as well...
2451             (goto-char min)
2452             (while (re-search-forward search max t)
2453               (cond 
2454                ((match-beginning 1)     ; POD section
2455                 ;;  "\\(\\`\n?\\|\n\n\\)=" 
2456                 (if (looking-at "\n*cut\\>")
2457                     (progn
2458                       (message "=cut is not preceded by a pod section")
2459                       (or err (setq err (point))))
2460                   (beginning-of-line)
2461                 
2462                   (setq b (point) bb b)
2463                   (or (re-search-forward "\n\n=cut\\>" max 'toend)
2464                       (progn
2465                         (message "Cannot find the end of a pod section")
2466                         (or err (setq err b))))
2467                   (beginning-of-line 2) ; An empty line after =cut is not POD!
2468                   (setq e (point))
2469                   (put-text-property b e 'in-pod t)
2470                   (goto-char b)
2471                   (while (re-search-forward "\n\n[ \t]" e t)
2472                     ;; We start 'pod 1 char earlier to include the preceding line
2473                     (beginning-of-line)
2474                     (put-text-property (cperl-1- b) (point) 'syntax-type 'pod)
2475                     (cperl-put-do-not-fontify b (point))
2476                     ;;(put-text-property (max (point-min) (1- b))
2477                     ;;               (point) cperl-do-not-fontify t)
2478                     (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
2479                     (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
2480                     (beginning-of-line)
2481                     (setq b (point)))
2482                   (put-text-property (cperl-1- (point)) e 'syntax-type 'pod)
2483                   (cperl-put-do-not-fontify (point) e)
2484                   ;;(put-text-property (max (point-min) (1- (point)))
2485                   ;;               e cperl-do-not-fontify t)
2486                   (if cperl-pod-here-fontify 
2487                       (progn (put-text-property (point) e 'face face)
2488                              (goto-char bb)
2489                              (if (looking-at 
2490                                   "=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
2491                                  (put-text-property 
2492                                   (match-beginning 1) (match-end 1)
2493                                   'face head-face))
2494                              (while (re-search-forward
2495                                      ;; One paragraph
2496                                      "\n\n=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
2497                                      e 'toend)
2498                                (put-text-property 
2499                                 (match-beginning 1) (match-end 1)
2500                                 'face head-face))))
2501                   (cperl-commentify bb e nil)
2502                   (goto-char e)))
2503                ;; Here document
2504                ;; We do only one here-per-line
2505                ;; 1 () ahead
2506                ;; "<<\\(\\([\"'`]\\)\\([^\"'`\n]*\\)\\3\\|\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)\\)"
2507                ((match-beginning 2)     ; 1 + 1
2508                 ;; Abort in comment:
2509                 (setq b (point))
2510                 (setq state (parse-partial-sexp state-point b nil nil state)
2511                       state-point b)
2512                 (if ;;(save-excursion
2513                     ;;  (beginning-of-line)
2514                     ;;  (search-forward "#" b t))
2515                     (or (nth 3 state) (nth 4 state))
2516                     (goto-char (match-end 2))
2517                   (if (match-beginning 5) ;4 + 1
2518                       (setq b1 (match-beginning 5) ; 4 + 1
2519                             e1 (match-end 5)) ; 4 + 1
2520                     (setq b1 (match-beginning 4) ; 3 + 1
2521                           e1 (match-end 4))) ; 3 + 1
2522                   (setq tag (buffer-substring b1 e1)
2523                         qtag (regexp-quote tag))
2524                   (cond (cperl-pod-here-fontify 
2525                          (put-text-property b1 e1 'face font-lock-reference-face)
2526                          (cperl-put-do-not-fontify b1 e1)))
2527                   (forward-line)
2528                   (setq b (point))
2529                   (cond ((re-search-forward (concat "^" qtag "$") max 'toend)
2530                          (if cperl-pod-here-fontify 
2531                              (progn
2532                                (put-text-property (match-beginning 0) (match-end 0) 
2533                                                   'face font-lock-reference-face)
2534                                (cperl-put-do-not-fontify b (match-end 0))
2535                                ;;(put-text-property (max (point-min) (1- b))
2536                                ;;                     (min (point-max)
2537                                ;;                          (1+ (match-end 0)))
2538                                ;;                     cperl-do-not-fontify t)
2539                                (put-text-property b (match-beginning 0) 
2540                                                   'face here-face)))
2541                          (setq e1 (cperl-1+ (match-end 0)))
2542                          (put-text-property b (match-beginning 0) 
2543                                             'syntax-type 'here-doc)
2544                          (put-text-property (match-beginning 0) e1
2545                                             'syntax-type 'here-doc-delim)
2546                          (put-text-property b e1
2547                                             'here-doc-group t)
2548                          (cperl-commentify b e1 nil)
2549                          (cperl-put-do-not-fontify b (match-end 0)))
2550                         (t (message "End of here-document `%s' not found." tag)
2551                            (or err (setq err b))))))
2552                ;; format
2553                ((match-beginning 8)
2554                 ;; 1+6=7 extra () before this:
2555                 ;;"^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
2556                 (setq b (point)
2557                       name (if (match-beginning 8) ; 7 + 1
2558                                (buffer-substring (match-beginning 8) ; 7 + 1
2559                                                  (match-end 8)) ; 7 + 1
2560                              ""))
2561                 (setq argument nil)
2562                 (if cperl-pod-here-fontify 
2563                     (while (and (eq (forward-line) 0)
2564                                 (not (looking-at "^[.;]$")))
2565                       (cond
2566                        ((looking-at "^#")) ; Skip comments
2567                        ((and argument   ; Skip argument multi-lines
2568                              (looking-at "^[ \t]*{")) 
2569                         (forward-sexp 1)
2570                         (setq argument nil))
2571                        (argument        ; Skip argument lines
2572                         (setq argument nil))
2573                        (t               ; Format line
2574                         (setq b1 (point))
2575                         (setq argument (looking-at "^[^\n]*[@^]"))
2576                         (end-of-line)
2577                         (put-text-property b1 (point) 
2578                                            'face font-lock-string-face)
2579                         (cperl-commentify b1 (point) nil)
2580                         (cperl-put-do-not-fontify b1 (point)))))
2581                   (re-search-forward (concat "^[.;]$") max 'toend))
2582                 (beginning-of-line)
2583                 (if (looking-at "^[.;]$")
2584                     (progn
2585                       (put-text-property (point) (+ (point) 2)
2586                                          'face font-lock-string-face)
2587                       (cperl-commentify (point) (+ (point) 2) nil)
2588                       (cperl-put-do-not-fontify (point) (+ (point) 2)))
2589                   (message "End of format `%s' not found." name)
2590                   (or err (setq err b)))
2591                 (forward-line)
2592                 (put-text-property b (point) 'syntax-type 'format)
2593 ;;;            (cond ((re-search-forward (concat "^[.;]$") max 'toend)
2594 ;;;                   (if cperl-pod-here-fontify 
2595 ;;;                       (progn
2596 ;;;                         (put-text-property b (match-end 0)
2597 ;;;                                            'face font-lock-string-face)
2598 ;;;                         (cperl-put-do-not-fontify b (match-end 0))))
2599 ;;;                   (put-text-property b (match-end 0) 
2600 ;;;                                      'syntax-type 'format)
2601 ;;;                   (cperl-put-do-not-fontify b (match-beginning 0)))
2602 ;;;                  (t (message "End of format `%s' not found." name)))
2603                 )
2604                ;; Regexp:
2605                ((or (match-beginning 10) (match-beginning 11))
2606                 ;; 1+6+2=9 extra () before this:
2607                 ;; "\\<\\(qx?\\|[my]\\)\\>"
2608                 (setq b1 (if (match-beginning 10) 10 11)
2609                       argument (buffer-substring
2610                                 (match-beginning b1) (match-end b1))
2611                       b (point)
2612                       i b
2613                       c (char-after (match-beginning b1))
2614                       bb (or
2615                           (memq (char-after (1- (match-beginning b1)))
2616                                 '(?\$ ?\@ ?\% ?\& ?\*))
2617                           (and
2618                            (eq (char-after (1- (match-beginning b1))) ?-)
2619                            (eq (char-after (match-beginning b1)) ?s))))
2620                 (or bb
2621                     (if (eq b1 11)      ; bare /blah/ or ?blah?
2622                         (setq argument ""
2623                              bb 
2624                              (progn
2625                                (goto-char (match-beginning b1))
2626                                (cperl-backward-to-noncomment (point-min))
2627                                (not (or (memq (preceding-char)
2628                                               (append (if (eq c ?\?)
2629                                                           ;; $a++ ? 1 : 2
2630                                                           "~{(=|&*!,;"
2631                                                         "~{(=|&+-*!,;") nil))
2632                                         (and (eq (preceding-char) ?\})
2633                                              (cperl-after-block-p (point-min)))
2634                                         (and (eq (char-syntax (preceding-char)) ?w)
2635                                              (progn
2636                                                (forward-sexp -1)
2637                                                (looking-at 
2638                                                 "\\(while\\|if\\|unless\\|until\\|and\\|or\\|not\\|xor\\|split\\|grep\\|map\\)\\>")))
2639                                         (and (eq (preceding-char) ?.)
2640                                              (eq (char-after (- (point) 2)) ?.))
2641                                         (bobp))))
2642                              b (1- b))))
2643                 (or bb (setq state (parse-partial-sexp 
2644                                     state-point b nil nil state)
2645                              state-point b))
2646                 (goto-char b)
2647                 (if (or bb (nth 3 state) (nth 4 state))
2648                     (goto-char i)
2649                   (skip-chars-forward " \t")
2650                   ;; qtag means two-argument matcher, may be reset to
2651                   ;; 2 or 3 later if some special quoting is needed.
2652                   (setq b (point) 
2653                         tag (char-after b)
2654                         qtag (if (string-match "^\\([sy]\\|tr\\)$" argument) t)
2655                         e1 (cdr (assoc tag '(( ?\( . ?\) )
2656                                              ( ?\[ . ?\] )
2657                                              ( ?\{ . ?\} )
2658                                              ( ?\< . ?\> )
2659                                              ))))
2660                   ;; What if tag == ?\\  ????
2661                   (or st 
2662                       (progn
2663                         (setq st (make-syntax-table) i 0)
2664                         (while (< i 256)
2665                           (modify-syntax-entry i "." st)
2666                           (setq i (1+ i)))
2667                         (modify-syntax-entry ?\\ "\\" st)))
2668                   ;; Whether we have an intermediate point
2669                   (setq i nil)
2670                   ;; Prepare the syntax table:
2671                   (cond
2672                    ;; $ has TeXish matching rules, so $$ equiv $...
2673                    ((and qtag 
2674                          (not e1) 
2675                          (eq tag (char-after (cperl-1+ b)))
2676                          (eq tag (char-after (+ 2 b))))
2677                     (setq qtag 3))      ; s///
2678                    ((and qtag
2679                          (not e1) 
2680                          (eq tag (char-after (cperl-1+ b))))
2681                     (setq qtag nil))    ; s//blah/, will work anyway
2682                    ((and (not e1) 
2683                          (eq tag (char-after (cperl-1+ b))))
2684                     (setq qtag 2))      ; m//
2685                    ((not e1)
2686                     (modify-syntax-entry tag "$" st)) ; m/blah/, s/x//, s/x/y/
2687                    (t                   ; s{}(), m[]
2688                     (modify-syntax-entry tag (concat "(" (list e1)) st)
2689                     (modify-syntax-entry e1  (concat ")" (list tag)) st)))
2690                   (if (numberp qtag)
2691                       (forward-char qtag)
2692                     (condition-case bb
2693                         (progn
2694                           (set-syntax-table st)
2695                           (forward-sexp 1) ; Wrong if m// - taken care of...
2696                           (if qtag
2697                               (if e1 
2698                                   (progn
2699                                     (setq i (point))
2700                                     (set-syntax-table cperl-mode-syntax-table)
2701                                     (forward-sexp 1)) ; Should be smarter?
2702                                 ;; "$" has funny matching rules
2703                                 (if (/= (char-after (- (point) 2)) 
2704                                         (preceding-char))
2705                                     (progn
2706                                       ;; Commenting \\ is dangerous, what about ( ?
2707                                       (if (eq (following-char) ?\\) nil
2708                                         (setq i (point)))
2709                                       (forward-char -1)
2710                                       (forward-sexp 1)))
2711                                 )))
2712                       (error (goto-char (point-max))
2713                              (message
2714                               "End of `%s%c ... %c' string not found: %s"
2715                               argument tag (or e1 tag) bb)
2716                              (or err (setq err b)))))
2717                   (set-syntax-table cperl-mode-syntax-table)
2718                   (if (null i)
2719                       (cperl-commentify b (point) t)
2720                     (cperl-commentify b i t)
2721                     (if (looking-at "\\sw*e") nil ; s///e
2722                       (cperl-commentify i (point) t)))
2723                   (if (eq (char-syntax (following-char)) ?w)
2724                       (forward-word 1)) ; skip modifiers s///s
2725                   (modify-syntax-entry tag "." st)
2726                   (if e1 (modify-syntax-entry e1 "." st))))
2727                ((match-beginning 13)    ; sub with prototypes
2728                 (setq b (match-beginning 0))
2729                 (if (memq (char-after (1- b))
2730                           '(?\$ ?\@ ?\% ?\& ?\*))
2731                     nil
2732                   (setq state (parse-partial-sexp 
2733                                state-point (1- b) nil nil state)
2734                         state-point (1- b))
2735                   (if (or (nth 3 state) (nth 4 state))
2736                       nil
2737                     ;; Mark as string
2738                     (cperl-commentify (match-beginning 13) (match-end 13) t))
2739                   (goto-char (match-end 0))))
2740                ((and (match-beginning 14)
2741                  (eq (preceding-char) ?\')) ; $'
2742                 (setq b (1- (point))
2743                       state (parse-partial-sexp 
2744                              state-point (1- b) nil nil state)
2745                       state-point (1- b))
2746                 (if (nth 3 state)       ; in string
2747                     (progn
2748                       (put-text-property (1- b) b 'syntax-table cperl-st-punct)
2749                       (put-text-property (1- b) b 'rear-nonsticky t)))
2750                 (goto-char (1+ b)))
2751                ((match-beginning 14)    ; ${
2752                 (setq bb (match-beginning 0))
2753                 (put-text-property bb (1+ bb) 'syntax-table cperl-st-punct)
2754                 (put-text-property bb (1+ bb) 'rear-nonsticky t))
2755                (t                       ; old $abc'efg syntax
2756                 (setq bb (match-end 0))
2757                 (put-text-property (1- bb) bb 'syntax-table cperl-st-word))))
2758 ;;;         (while (re-search-forward "\\(\\`\n?\\|\n\n\\)=" max t)
2759 ;;;           (if (looking-at "\n*cut\\>")
2760 ;;;               (progn
2761 ;;;                 (message "=cut is not preceded by a pod section")
2762 ;;;                 (setq err (point)))
2763 ;;;             (beginning-of-line)
2764                 
2765 ;;;             (setq b (point) bb b)
2766 ;;;             (or (re-search-forward "\n\n=cut\\>" max 'toend)
2767 ;;;                 (message "Cannot find the end of a pod section"))
2768 ;;;             (beginning-of-line 3)
2769 ;;;             (setq e (point))
2770 ;;;             (put-text-property b e 'in-pod t)
2771 ;;;             (goto-char b)
2772 ;;;             (while (re-search-forward "\n\n[ \t]" e t)
2773 ;;;               (beginning-of-line)
2774 ;;;               (put-text-property b (point) 'syntax-type 'pod)
2775 ;;;               (cperl-put-do-not-fontify b (point))
2776 ;;;               ;;(put-text-property (max (point-min) (1- b))
2777 ;;;               ;;                 (point) cperl-do-not-fontify t)
2778 ;;;               (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
2779 ;;;               (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
2780 ;;;               (beginning-of-line)
2781 ;;;               (setq b (point)))
2782 ;;;             (put-text-property (point) e 'syntax-type 'pod)
2783 ;;;             (cperl-put-do-not-fontify (point) e)
2784 ;;;             ;;(put-text-property (max (point-min) (1- (point)))
2785 ;;;             ;;                 e cperl-do-not-fontify t)
2786 ;;;             (if cperl-pod-here-fontify 
2787 ;;;                 (progn (put-text-property (point) e 'face face)
2788 ;;;                        (goto-char bb)
2789 ;;;                        (if (looking-at 
2790 ;;;                         "=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
2791 ;;;                            (put-text-property 
2792 ;;;                             (match-beginning 1) (match-end 1)
2793 ;;;                             'face head-face))
2794 ;;;                        (while (re-search-forward
2795 ;;;                                ;; One paragraph
2796 ;;;                                "\n\n=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
2797 ;;;                                e 'toend)
2798 ;;;                          (put-text-property 
2799 ;;;                           (match-beginning 1) (match-end 1)
2800 ;;;                           'face head-face))))
2801 ;;;             (goto-char e)))
2802 ;;;         (goto-char min)
2803 ;;;         (while (re-search-forward 
2804 ;;;                 ;; We exclude \n to avoid misrecognition inside quotes.
2805 ;;;                 "<<\\(\\([\"'`]\\)\\([^\"'`\n]*\\)\\2\\|\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)\\)"
2806 ;;;                 max t)
2807 ;;;           (if (match-beginning 4)
2808 ;;;               (setq b1 (match-beginning 4)
2809 ;;;                     e1 (match-end 4))
2810 ;;;             (setq b1 (match-beginning 3)
2811 ;;;                   e1 (match-end 3)))
2812 ;;;           (setq tag (buffer-substring b1 e1)
2813 ;;;                 qtag (regexp-quote tag))
2814 ;;;           (cond (cperl-pod-here-fontify 
2815 ;;;                  (put-text-property b1 e1 'face font-lock-reference-face)
2816 ;;;                  (cperl-put-do-not-fontify b1 e1)))
2817 ;;;           (forward-line)
2818 ;;;           (setq b (point))
2819 ;;;           (cond ((re-search-forward (concat "^" qtag "$") max 'toend)
2820 ;;;                  (if cperl-pod-here-fontify 
2821 ;;;                      (progn
2822 ;;;                        (put-text-property (match-beginning 0) (match-end 0) 
2823 ;;;                                           'face font-lock-reference-face)
2824 ;;;                        (cperl-put-do-not-fontify b (match-end 0))
2825 ;;;                        ;;(put-text-property (max (point-min) (1- b))
2826 ;;;                        ;;                 (min (point-max)
2827 ;;;                        ;;                      (1+ (match-end 0)))
2828 ;;;                        ;;                 cperl-do-not-fontify t)
2829 ;;;                        (put-text-property b (match-beginning 0) 
2830 ;;;                                           'face here-face)))
2831 ;;;                  (put-text-property b (match-beginning 0) 
2832 ;;;                                     'syntax-type 'here-doc)
2833 ;;;                  (cperl-put-do-not-fontify b (match-beginning 0)))
2834 ;;;                 (t (message "End of here-document `%s' not found." tag))))
2835 ;;;         (goto-char min)
2836 ;;;         (while (re-search-forward 
2837 ;;;                 "^[ \t]*format[ \t]*\\(\\([a-zA-Z0-9_]+[ \t]*\\)?\\)=[ \t]*$"
2838 ;;;                 max t)
2839 ;;;           (setq b (point)
2840 ;;;                 name (buffer-substring (match-beginning 1)
2841 ;;;                                        (match-end 1)))
2842 ;;;           (cond ((re-search-forward (concat "^[.;]$") max 'toend)
2843 ;;;                  (if cperl-pod-here-fontify 
2844 ;;;                      (progn
2845 ;;;                        (put-text-property b (match-end 0)
2846 ;;;                                           'face font-lock-string-face)
2847 ;;;                        (cperl-put-do-not-fontify b (match-end 0))))
2848 ;;;                  (put-text-property b (match-end 0) 
2849 ;;;                                     'syntax-type 'format)
2850 ;;;                  (cperl-put-do-not-fontify b (match-beginning 0)))
2851 ;;;                 (t (message "End of format `%s' not found." name))))
2852 )
2853           (if err (goto-char err)
2854             (message "Scan for pods, formats and here-docs completed.")))
2855       (and (buffer-modified-p)
2856            (not modified)
2857            (set-buffer-modified-p nil))
2858       (set-syntax-table cperl-mode-syntax-table))))
2859
2860 (defun cperl-backward-to-noncomment (lim)
2861   ;; Stops at lim or after non-whitespace that is not in comment
2862   (let (stop p)
2863     (while (and (not stop) (> (point) (or lim 1)))
2864       (skip-chars-backward " \t\n\f" lim)
2865       (setq p (point))
2866       (beginning-of-line)
2867       (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
2868         ;; Else
2869         (cperl-to-comment-or-eol) 
2870         (skip-chars-backward " \t")
2871         (if (< p (point)) (goto-char p))
2872         (setq stop t)))))
2873
2874 (defun cperl-after-block-p (lim)
2875   ;; We suppose that the preceding char is }.
2876   (save-excursion
2877     (condition-case nil
2878         (progn
2879           (forward-sexp -1)
2880           (cperl-backward-to-noncomment lim)
2881           (or (eq (preceding-char) ?\) ) ; if () {}
2882               (and (eq (char-syntax (preceding-char)) ?w) ; else {}
2883                    (progn
2884                      (forward-sexp -1)
2885                      (looking-at "\\(else\\|grep\\|map\\)\\>")))
2886               (cperl-after-expr-p lim)))
2887       (error nil))))
2888
2889 (defun cperl-after-expr-p (&optional lim chars test)
2890   "Returns true if the position is good for start of expression.
2891 TEST is the expression to evaluate at the found position. If absent,
2892 CHARS is a string that contains good characters to have before us (however,
2893 `}' is treated \"smartly\" if it is not in the list)."
2894   (let (stop p 
2895              (lim (or lim (point-min))))
2896     (save-excursion
2897       (while (and (not stop) (> (point) lim))
2898         (skip-chars-backward " \t\n\f" lim)
2899         (setq p (point))
2900         (beginning-of-line)
2901         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
2902           ;; Else: last iteration (What to do with labels?)
2903           (cperl-to-comment-or-eol) 
2904           (skip-chars-backward " \t")
2905           (if (< p (point)) (goto-char p))
2906           (setq stop t)))
2907       (or (bobp)
2908           (progn
2909             (if test (eval test)
2910               (or (memq (preceding-char) (append (or chars "{;") nil))
2911                   (and (eq (preceding-char) ?\})
2912                        (cperl-after-block-p lim)))))))))
2913
2914 (defun cperl-backward-to-start-of-continued-exp (lim)
2915   (if (memq (preceding-char) (append ")]}\"'`" nil))
2916       (forward-sexp -1))
2917   (beginning-of-line)
2918   (if (<= (point) lim)
2919       (goto-char (1+ lim)))
2920   (skip-chars-forward " \t"))
2921
2922 \f
2923 (defvar innerloop-done nil)
2924 (defvar last-depth nil)
2925
2926 (defun cperl-indent-exp ()
2927   "Simple variant of indentation of continued-sexp.
2928 Should be slow. Will not indent comment if it starts at `comment-indent'
2929 or looks like continuation of the comment on the previous line."
2930   (interactive)
2931   (save-excursion
2932     (let ((tmp-end (progn (end-of-line) (point))) top done)
2933       (save-excursion
2934         (while (null done)
2935           (beginning-of-line)
2936           (setq top (point))
2937           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
2938                                                -1)) -1)
2939             (setq top (point)))         ; Get the outermost parenths in line
2940           (goto-char top)
2941           (while (< (point) tmp-end)
2942             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
2943             (or (eolp) (forward-sexp 1)))
2944           (if (> (point) tmp-end) (progn (end-of-line) (setq tmp-end (point)))
2945             (setq done t)))
2946         (goto-char tmp-end)
2947         (setq tmp-end (point-marker)))
2948       (cperl-indent-region (point) tmp-end))))
2949
2950 (defun cperl-indent-region (start end)
2951   "Simple variant of indentation of region in CPerl mode.
2952 Should be slow. Will not indent comment if it starts at `comment-indent' 
2953 or looks like continuation of the comment on the previous line.
2954 Indents all the lines whose first character is between START and END 
2955 inclusive."
2956   (interactive "r")
2957   (save-excursion
2958     (let (st comm indent-info old-comm-indent new-comm-indent 
2959              (pm 0) (imenu-scanning-message "Indenting... (%3d%%)"))
2960       (goto-char start)
2961       (setq old-comm-indent (and (cperl-to-comment-or-eol)
2962                                  (current-column))
2963             new-comm-indent old-comm-indent)
2964       (goto-char start)
2965       (or (bolp) (beginning-of-line 2))
2966       (or (fboundp 'imenu-progress-message)
2967           (message "Indenting... For feedback load `imenu'..."))
2968       (while (and (<= (point) end) (not (eobp))) ; bol to check start
2969         (and (fboundp 'imenu-progress-message)
2970              (imenu-progress-message 
2971               pm (/ (* 100 (- (point) start)) (- end start -1))))
2972         (setq st (point) 
2973               indent-info nil
2974               ) ; Believe indentation of the current
2975         (if (and (setq comm (looking-at "[ \t]*#"))
2976                  (or (eq (current-indentation) (or old-comm-indent 
2977                                                    comment-column))
2978                      (setq old-comm-indent nil)))
2979             (if (and old-comm-indent
2980                      (= (current-indentation) old-comm-indent)
2981                      (not (eq (get-text-property (point) 'syntax-type) 'pod)))
2982                 (let ((comment-column new-comm-indent))
2983                   (indent-for-comment)))
2984           (progn 
2985             (cperl-indent-line 'indent-info)
2986             (or comm
2987                 (progn
2988                   (if (setq old-comm-indent (and (cperl-to-comment-or-eol)
2989                                                  (not (eq (get-text-property (point) 'syntax-type) 'pod))
2990                                                  (current-column)))
2991                       (progn (indent-for-comment)
2992                              (skip-chars-backward " \t")
2993                              (skip-chars-backward "#")
2994                              (setq new-comm-indent (current-column))))))))
2995         (beginning-of-line 2))
2996         (if (fboundp 'imenu-progress-message)
2997              (imenu-progress-message pm 100)
2998           (message nil)))))
2999
3000 ;;(defun cperl-slash-is-regexp (&optional pos)
3001 ;;  (save-excursion
3002 ;;    (goto-char (if pos pos (1- (point))))
3003 ;;    (and
3004 ;;     (not (memq (get-text-property (point) 'face)
3005 ;;              '(font-lock-string-face font-lock-comment-face)))
3006 ;;     (cperl-after-expr-p nil nil '
3007 ;;                     (or (looking-at "[^]a-zA-Z0-9_)}]")
3008 ;;                         (eq (get-text-property (point) 'face)
3009 ;;                             'font-lock-keyword-face))))))
3010
3011 ;; Stolen from lisp-mode with a lot of improvements
3012
3013 (defun cperl-fill-paragraph (&optional justify iteration)
3014   "Like \\[fill-paragraph], but handle CPerl comments.
3015 If any of the current line is a comment, fill the comment or the
3016 block of it that point is in, preserving the comment's initial
3017 indentation and initial hashes. Behaves usually outside of comment."
3018   (interactive "P")
3019   (let (
3020         ;; Non-nil if the current line contains a comment.
3021         has-comment
3022
3023         ;; If has-comment, the appropriate fill-prefix for the comment.
3024         comment-fill-prefix
3025         ;; Line that contains code and comment (or nil)
3026         start
3027         c spaces len dc (comment-column comment-column))
3028     ;; Figure out what kind of comment we are looking at.
3029     (save-excursion
3030       (beginning-of-line)
3031       (cond
3032
3033        ;; A line with nothing but a comment on it?
3034        ((looking-at "[ \t]*#[# \t]*")
3035         (setq has-comment t
3036               comment-fill-prefix (buffer-substring (match-beginning 0)
3037                                                     (match-end 0))))
3038
3039        ;; A line with some code, followed by a comment?  Remember that the
3040        ;; semi which starts the comment shouldn't be part of a string or
3041        ;; character.
3042        ((cperl-to-comment-or-eol)
3043         (setq has-comment t)
3044         (looking-at "#+[ \t]*")
3045         (setq start (point) c (current-column) 
3046               comment-fill-prefix
3047               (concat (make-string (current-column) ?\ )
3048                       (buffer-substring (match-beginning 0) (match-end 0)))
3049               spaces (progn (skip-chars-backward " \t") 
3050                             (buffer-substring (point) start))
3051               dc (- c (current-column)) len (- start (point)) 
3052               start (point-marker))
3053         (delete-char len)
3054         (insert (make-string dc ?-)))))
3055     (if (not has-comment)
3056         (fill-paragraph justify)        ; Do the usual thing outside of comment
3057       ;; Narrow to include only the comment, and then fill the region.
3058       (save-restriction
3059         (narrow-to-region
3060          ;; Find the first line we should include in the region to fill.
3061          (if start (progn (beginning-of-line) (point))
3062            (save-excursion
3063              (while (and (zerop (forward-line -1))
3064                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
3065              ;; We may have gone to far.  Go forward again.
3066              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
3067                  (forward-line 1))
3068              (point)))
3069          ;; Find the beginning of the first line past the region to fill.
3070          (save-excursion
3071            (while (progn (forward-line 1)
3072                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
3073            (point)))
3074         ;; Remove existing hashes
3075         (goto-char (point-min))
3076         (while (progn (forward-line 1) (< (point) (point-max)))
3077           (skip-chars-forward " \t")
3078           (and (looking-at "#+") 
3079                (delete-char (- (match-end 0) (match-beginning 0)))))
3080
3081         ;; Lines with only hashes on them can be paragraph boundaries.
3082         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
3083               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
3084               (fill-prefix comment-fill-prefix))
3085           (fill-paragraph justify)))
3086       (if (and start)
3087           (progn 
3088             (goto-char start)
3089             (if (> dc 0)
3090               (progn (delete-char dc) (insert spaces)))
3091             (if (or (= (current-column) c) iteration) nil
3092               (setq comment-column c)
3093               (indent-for-comment)
3094               ;; Repeat once more, flagging as iteration
3095               (cperl-fill-paragraph justify t)))))))
3096
3097 (defun cperl-do-auto-fill ()
3098   ;; Break out if the line is short enough
3099   (if (> (save-excursion
3100            (end-of-line)
3101            (current-column))
3102          fill-column)
3103   (let ((c (save-excursion (beginning-of-line)
3104                            (cperl-to-comment-or-eol) (point)))
3105         (s (memq (following-char) '(?\ ?\t))) marker)
3106     (if (>= c (point)) nil
3107       (setq marker (point-marker))
3108       (cperl-fill-paragraph)
3109       (goto-char marker)
3110       ;; Is not enough, sometimes marker is a start of line
3111       (if (bolp) (progn (re-search-forward "#+[ \t]*") 
3112                         (goto-char (match-end 0))))
3113       ;; Following space could have gone:
3114       (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
3115         (insert " ")
3116         (backward-char 1))
3117       ;; Previous space could have gone:
3118       (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
3119
3120 (defvar imenu-example--function-name-regexp-perl
3121   (concat 
3122    "^\\("
3123        "[ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*\\(([^()]*)[ \t]*\\)?"
3124      "\\|"
3125        "=head\\([12]\\)[ \t]+\\([^\n]+\\)$"
3126    "\\)"))
3127
3128 (defun cperl-imenu-addback (lst &optional isback name)
3129   ;; We suppose that the lst is a DAG, unless the first element only
3130   ;; loops back, and ISBACK is set. Thus this function cannot be
3131   ;; applied twice without ISBACK set.
3132   (cond ((not cperl-imenu-addback) lst)
3133         (t
3134          (or name 
3135              (setq name "+++BACK+++"))
3136          (mapcar (function (lambda (elt)
3137                              (if (and (listp elt) (listp (cdr elt)))
3138                                  (progn
3139                                    ;; In the other order it goes up
3140                                    ;; one level only ;-(
3141                                    (setcdr elt (cons (cons name lst)
3142                                                      (cdr elt)))
3143                                    (cperl-imenu-addback (cdr elt) t name)
3144                                    ))))
3145                  (if isback (cdr lst) lst))
3146          lst)))
3147
3148 (defun imenu-example--create-perl-index (&optional regexp)
3149   (require 'cl)
3150   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '()) 
3151         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
3152         (index-meth-alist '()) meth
3153         packages ends-ranges p
3154         (prev-pos 0) char fchar index index1 name (end-range 0) package)
3155     (goto-char (point-min))
3156     (imenu-progress-message prev-pos 0)
3157     ;; Search for the function
3158     (progn ;;save-match-data
3159       (while (re-search-forward
3160               (or regexp imenu-example--function-name-regexp-perl)
3161               nil t)
3162         (imenu-progress-message prev-pos)
3163         ;;(backward-up-list 1)
3164         (cond
3165          ((and
3166            (match-beginning 2)          ; package or sub
3167            ;; Skip if quoted (will not skip multi-line ''-comments :-():
3168            (null (get-text-property (match-beginning 1) 'syntax-table))
3169            (null (get-text-property (match-beginning 1) 'syntax-type))
3170            (null (get-text-property (match-beginning 1) 'in-pod)))
3171           (save-excursion
3172             (goto-char (match-beginning 2))
3173             (setq fchar (following-char))
3174             )
3175           ;; (if (looking-at "([^()]*)[ \t\n\f]*")
3176           ;;    (goto-char (match-end 0)))      ; Messes what follows
3177           (setq char (following-char) 
3178                 meth nil
3179                 p (point))
3180           (while (and ends-ranges (>= p (car ends-ranges)))
3181             ;; delete obsolete entries
3182             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
3183           (setq package (or (car packages) "")
3184                 end-range (or (car ends-ranges) 0))
3185           (if (eq fchar ?p)
3186               (setq name (buffer-substring (match-beginning 3) (match-end 3))
3187                     name (progn
3188                            (set-text-properties 0 (length name) nil name)
3189                            name)
3190                     package (concat name "::") 
3191                     name (concat "package " name)
3192                     end-range 
3193                     (save-excursion
3194                       (parse-partial-sexp (point) (point-max) -1) (point))
3195                     ends-ranges (cons end-range ends-ranges)
3196                     packages (cons package packages)))
3197           ;;   )
3198           ;; Skip this function name if it is a prototype declaration.
3199           (if (and (eq fchar ?s) (eq char ?\;)) nil
3200             (setq index (imenu-example--name-and-position))
3201             (if (eq fchar ?p) nil
3202               (setq name (buffer-substring (match-beginning 3) (match-end 3)))
3203               (set-text-properties 0 (length name) nil name)
3204               (cond ((string-match "[:']" name)
3205                      (setq meth t))
3206                     ((> p end-range) nil)
3207                     (t 
3208                      (setq name (concat package name) meth t))))
3209             (setcar index name)
3210             (if (eq fchar ?p) 
3211                 (push index index-pack-alist)
3212               (push index index-alist))
3213             (if meth (push index index-meth-alist))
3214             (push index index-unsorted-alist)))
3215          ((match-beginning 5)           ; Pod section
3216           ;; (beginning-of-line)
3217           (setq index (imenu-example--name-and-position)
3218                 name (buffer-substring (match-beginning 6) (match-end 6)))
3219           (set-text-properties 0 (length name) nil name)
3220           (if (eq (char-after (match-beginning 5)) ?2)
3221               (setq name (concat "   " name)))
3222           (setcar index name)
3223           (setq index1 (cons (concat "=" name) (cdr index)))
3224           (push index index-pod-alist)
3225           (push index1 index-unsorted-alist)))))
3226     (imenu-progress-message prev-pos 100)
3227     (setq index-alist 
3228           (if (default-value 'imenu-sort-function)
3229               (sort index-alist (default-value 'imenu-sort-function))
3230               (nreverse index-alist)))
3231     (and index-pod-alist
3232          (push (cons "+POD headers+..."
3233                      (nreverse index-pod-alist))
3234                index-alist))
3235     (and (or index-pack-alist index-meth-alist)
3236          (let ((lst index-pack-alist) hier-list pack elt group name)
3237            ;; Remove "package ", reverse and uniquify.
3238            (while lst
3239              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
3240              (if (assoc name hier-list) nil
3241                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
3242            (setq lst index-meth-alist)
3243            (while lst
3244              (setq elt (car lst) lst (cdr lst))
3245              (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
3246                     (setq pack (substring (car elt) 0 (match-beginning 0)))
3247                     (if (setq group (assoc pack hier-list)) 
3248                         (if (listp (cdr group))
3249                             ;; Have some functions already
3250                             (setcdr group 
3251                                     (cons (cons (substring 
3252                                                  (car elt)
3253                                                  (+ 2 (match-beginning 0)))
3254                                                 (cdr elt))
3255                                           (cdr group)))
3256                           (setcdr group (list (cons (substring 
3257                                                      (car elt)
3258                                                      (+ 2 (match-beginning 0)))
3259                                                     (cdr elt)))))
3260                       (setq hier-list 
3261                             (cons (cons pack 
3262                                         (list (cons (substring 
3263                                                      (car elt)
3264                                                      (+ 2 (match-beginning 0)))
3265                                                     (cdr elt))))
3266                                   hier-list))))))
3267            (push (cons "+Hierarchy+..."
3268                        hier-list)
3269                  index-alist)))
3270     (and index-pack-alist
3271          (push (cons "+Packages+..."
3272                      (nreverse index-pack-alist))
3273                index-alist))
3274     (and (or index-pack-alist index-pod-alist 
3275              (default-value 'imenu-sort-function))
3276          index-unsorted-alist
3277          (push (cons "+Unsorted List+..."
3278                      (nreverse index-unsorted-alist))
3279                index-alist))
3280     (cperl-imenu-addback index-alist)))
3281
3282 (defvar cperl-compilation-error-regexp-alist 
3283   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
3284   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
3285      2 3))
3286   "Alist that specifies how to match errors in perl output.")
3287
3288 (if (fboundp 'eval-after-load)
3289     (eval-after-load
3290      "mode-compile"
3291      '(setq perl-compilation-error-regexp-alist
3292            cperl-compilation-error-regexp-alist)))
3293
3294
3295 (defvar cperl-faces-init nil)
3296
3297 (defun cperl-windowed-init ()
3298   "Initialization under windowed version."
3299   (add-hook 'font-lock-mode-hook
3300             (function
3301              (lambda ()
3302                (if (or
3303                     (eq major-mode 'perl-mode)
3304                     (eq major-mode 'cperl-mode))
3305                    (progn
3306                      (or cperl-faces-init (cperl-init-faces))))))))
3307
3308 (defvar perl-font-lock-keywords-1 nil
3309   "Additional expressions to highlight in Perl mode. Minimal set.")
3310 (defvar perl-font-lock-keywords nil
3311   "Additional expressions to highlight in Perl mode. Default set.")
3312 (defvar perl-font-lock-keywords-2 nil
3313   "Additional expressions to highlight in Perl mode. Maximal set")
3314
3315 (defun cperl-init-faces ()
3316   (condition-case nil
3317       (progn
3318         (require 'font-lock)
3319         (and (fboundp 'font-lock-fontify-anchored-keywords)
3320              (featurep 'font-lock-extra)
3321              (message "You have an obsolete package `font-lock-extra'. Install `choose-color'."))
3322         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
3323           ;;(defvar cperl-font-lock-enhanced nil
3324           ;;  "Set to be non-nil if font-lock allows active highlights.")
3325           (if (fboundp 'font-lock-fontify-anchored-keywords)
3326               (setq font-lock-anchored t))
3327           (setq 
3328            t-font-lock-keywords
3329            (list
3330             (cons
3331              (concat
3332               "\\(^\\|[^$@%&\\]\\)\\<\\("
3333               (mapconcat
3334                'identity
3335                '("if" "until" "while" "elsif" "else" "unless" "for"
3336                  "foreach" "continue" "exit" "die" "last" "goto" "next"
3337                  "redo" "return" "local" "exec" "sub" "do" "dump" "use"
3338                  "require" "package" "eval" "my" "BEGIN" "END")
3339                "\\|")                   ; Flow control
3340               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
3341                                         ; In what follows we use `type' style
3342                                         ; for overwritable builtins
3343             (list
3344              (concat
3345               "\\(^\\|[^$@%&\\]\\)\\<\\("
3346               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm"
3347               ;; "and" "atan2" "bind" "binmode" "bless" "caller"
3348               ;; "chdir" "chmod" "chown" "chr" "chroot" "close"
3349               ;; "closedir" "cmp" "connect" "continue" "cos" "crypt"
3350               ;; "dbmclose" "dbmopen" "die" "dump" "endgrent"
3351               ;; "endhostent" "endnetent" "endprotoent" "endpwent"
3352               ;; "endservent" "eof" "eq" "exec" "exit" "exp" "fcntl"
3353               ;; "fileno" "flock" "fork" "formline" "ge" "getc"
3354               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr"
3355               ;; "gethostbyname" "gethostent" "getlogin"
3356               ;; "getnetbyaddr" "getnetbyname" "getnetent"
3357               ;; "getpeername" "getpgrp" "getppid" "getpriority"
3358               ;; "getprotobyname" "getprotobynumber" "getprotoent"
3359               ;; "getpwent" "getpwnam" "getpwuid" "getservbyname"
3360               ;; "getservbyport" "getservent" "getsockname"
3361               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int"
3362               ;; "ioctl" "join" "kill" "lc" "lcfirst" "le" "length"
3363               ;; "link" "listen" "localtime" "log" "lstat" "lt"
3364               ;; "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd" "ne"
3365               ;; "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
3366               ;; "quotemeta" "rand" "read" "readdir" "readline"
3367               ;; "readlink" "readpipe" "recv" "ref" "rename" "require"
3368               ;; "reset" "reverse" "rewinddir" "rindex" "rmdir" "seek"
3369               ;; "seekdir" "select" "semctl" "semget" "semop" "send"
3370               ;; "setgrent" "sethostent" "setnetent" "setpgrp"
3371               ;; "setpriority" "setprotoent" "setpwent" "setservent"
3372               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite"
3373               ;; "shutdown" "sin" "sleep" "socket" "socketpair"
3374               ;; "sprintf" "sqrt" "srand" "stat" "substr" "symlink"
3375               ;; "syscall" "sysread" "system" "syswrite" "tell"
3376               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst"
3377               ;; "umask" "unlink" "unpack" "utime" "values" "vec"
3378               ;; "wait" "waitpid" "wantarray" "warn" "write" "x" "xor"
3379               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|" 
3380               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
3381               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
3382               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
3383               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
3384               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
3385               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
3386               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
3387               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
3388               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
3389               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
3390               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
3391               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
3392               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
3393               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
3394               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
3395               "\\(\\|ngth\\)\\|o\\(caltime\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
3396               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
3397               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
3398               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
3399               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
3400               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
3401               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
3402               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
3403               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
3404               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|tem\\|write\\)\\|"
3405               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
3406               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
3407               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
3408               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
3409               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\|PACKAGE__\\)"
3410               "\\)\\>") 2 'font-lock-type-face)
3411             ;; In what follows we use `other' style
3412             ;; for nonoverwritable builtins
3413             ;; Somehow 's', 'm' are not auto-generated???
3414             (list
3415              (concat
3416               "\\(^\\|[^$@%&\\]\\)\\<\\("
3417               ;; "AUTOLOAD" "BEGIN" "DESTROY" "END" "__END__" "chomp"
3418               ;; "chop" "defined" "delete" "do" "each" "else" "elsif"
3419               ;; "eval" "exists" "for" "foreach" "format" "goto"
3420               ;; "grep" "if" "keys" "last" "local" "map" "my" "next"
3421               ;; "no" "package" "pop" "pos" "print" "printf" "push"
3422               ;; "q" "qq" "qw" "qx" "redo" "return" "scalar" "shift"
3423               ;; "sort" "splice" "split" "study" "sub" "tie" "tr"
3424               ;; "undef" "unless" "unshift" "untie" "until" "use"
3425               ;; "while" "y"
3426               "AUTOLOAD\\|BEGIN\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
3427               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
3428               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|if\\|keys\\|"
3429               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|"
3430               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
3431               "q\\(\\|q\\|w\\|x\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
3432               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
3433               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
3434               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
3435               "\\|[sm]"                 ; Added manually
3436               "\\)\\>") 2 'font-lock-other-type-face)
3437             ;;          (mapconcat 'identity
3438             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
3439             ;;                       "#include" "#define" "#undef")
3440             ;;                     "\\|")
3441             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
3442               font-lock-function-name-face keep) ; Not very good, triggers at "[a-z]"
3443             '("\\<sub[ \t]+\\([^ \t{;]+\\)[ \t]*\\(([^()]*)[ \t]*\\)?[#{\n]" 1
3444               font-lock-function-name-face)
3445             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
3446               2 font-lock-function-name-face)
3447             '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
3448               1 font-lock-function-name-face)
3449             (cond ((featurep 'font-lock-extra)
3450                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}" 
3451                      (2 font-lock-string-face t)
3452                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
3453                   (font-lock-anchored
3454                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
3455                      (2 font-lock-string-face t)
3456                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
3457                       nil nil
3458                       (1 font-lock-string-face t))))
3459                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
3460                        2 font-lock-string-face t)))
3461             '("[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
3462               font-lock-string-face t)
3463             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1 
3464               font-lock-reference-face) ; labels
3465             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
3466               2 font-lock-reference-face)
3467             (cond ((featurep 'font-lock-extra)
3468                    '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
3469                      (3 font-lock-variable-name-face)
3470                      (4 '(another 4 nil
3471                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
3472                                    (1 font-lock-variable-name-face)
3473                                    (2 '(restart 2 nil) nil t))) 
3474                         nil t)))        ; local variables, multiple
3475                   (font-lock-anchored
3476                    '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
3477                      (3 font-lock-variable-name-face)
3478                      ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)"
3479                       nil nil
3480                       (1 font-lock-variable-name-face))))
3481                   (t '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
3482                        3 font-lock-variable-name-face)))
3483             '("\\<for\\(each\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
3484               2 font-lock-variable-name-face)))
3485           (setq 
3486            t-font-lock-keywords-1
3487            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
3488                 (not cperl-xemacs-p) ; not yet as of XEmacs 19.12
3489                 '(
3490                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
3491                    (if (eq (char-after (match-beginning 2)) ?%)
3492                        font-lock-other-emphasized-face
3493                      font-lock-emphasized-face)
3494                    t)                   ; arrays and hashes
3495                   ("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
3496                    1
3497                    (if (= (- (match-end 2) (match-beginning 2)) 1) 
3498                        (if (eq (char-after (match-beginning 3)) ?{)
3499                            font-lock-other-emphasized-face
3500                          font-lock-emphasized-face) ; arrays and hashes
3501                      font-lock-variable-name-face) ; Just to put something
3502                    t)
3503                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
3504                        ;;; Too much noise from \s* @s[ and friends
3505                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)" 
3506                   ;;(3 font-lock-function-name-face t t)
3507                   ;;(4
3508                   ;; (if (cperl-slash-is-regexp)
3509                   ;;    font-lock-function-name-face 'default) nil t))
3510                   )))
3511           (setq perl-font-lock-keywords-1 t-font-lock-keywords
3512                 perl-font-lock-keywords perl-font-lock-keywords-1
3513                 perl-font-lock-keywords-2 (append
3514                                            t-font-lock-keywords
3515                                            t-font-lock-keywords-1)))
3516         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
3517         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
3518             (font-lock-require-faces
3519              (list
3520               ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
3521               (list 'font-lock-comment-face
3522                     ["Firebrick"        "OrangeRed"     "DimGray"       "Gray80"]
3523                     nil
3524                     [nil                nil             t               t       t]
3525                     [nil                nil             t               t       t]
3526                     nil)
3527               (list 'font-lock-string-face
3528                     ["RosyBrown"        "LightSalmon"   "Gray50"        "LightGray"]
3529                     nil
3530                     nil
3531                     [nil                nil             t               t       t]
3532                     nil)
3533               (list 'font-lock-keyword-face
3534                     ["Purple"           "LightSteelBlue" "DimGray"      "Gray90"]
3535                     nil
3536                     [nil                nil             t               t       t]
3537                     nil
3538                     nil)
3539               (list 'font-lock-function-name-face
3540                     (vector
3541                      "Blue"             "LightSkyBlue"  "Gray50"        "LightGray"
3542                      (cdr (assq 'background-color ; if mono
3543                                 (frame-parameters))))
3544                     (vector
3545                      nil                nil             nil             nil
3546                      (cdr (assq 'foreground-color ; if mono
3547                                 (frame-parameters))))
3548                     [nil                nil             t               t       t]
3549                     nil
3550                     nil)
3551               (list 'font-lock-variable-name-face
3552                     ["DarkGoldenrod"    "LightGoldenrod" "DimGray"      "Gray90"]
3553                     nil
3554                     [nil                nil             t               t       t]
3555                     [nil                nil             t               t       t]
3556                     nil)
3557               (list 'font-lock-type-face
3558                     ["DarkOliveGreen"   "PaleGreen"     "DimGray"       "Gray80"]
3559                     nil
3560                     [nil                nil             t               t       t]
3561                     nil
3562                     [nil                nil             t               t       t]
3563                     )
3564               (list 'font-lock-reference-face
3565                     ["CadetBlue"        "Aquamarine"    "Gray50"        "LightGray"]
3566                     nil
3567                     [nil                nil             t               t       t]
3568                     nil
3569                     [nil                nil             t               t       t]
3570                     )
3571               (list 'font-lock-other-type-face
3572                     ["chartreuse3"      ("orchid1" "orange")
3573                      nil                "Gray80"]
3574                     [nil                nil             "gray90"]
3575                     [nil                nil             nil             t       t]
3576                     [nil                nil             t               t]
3577                     [nil                nil             t               t       t]
3578                     )
3579               (list 'font-lock-emphasized-face
3580                     ["blue"             "yellow"        nil             "Gray80"]
3581                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
3582                      "gray90"]
3583                     t
3584                     nil
3585                     nil)
3586               (list 'font-lock-other-emphasized-face
3587                     ["red"              "red"           nil             "Gray80"]
3588                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
3589                      "gray90"]
3590                     t
3591                     t
3592                     nil)))
3593           (defvar cperl-guessed-background nil
3594             "Display characteristics as guessed by cperl.")
3595           (or (fboundp 'x-color-defined-p)
3596               (defalias 'x-color-defined-p 
3597                 (cond ((fboundp 'color-defined-p) 'color-defined-p)
3598                       ;; XEmacs >= 19.12
3599                       ((fboundp 'valid-color-name-p) 'valid-color-name-p)
3600                       ;; XEmacs 19.11
3601                       (t 'x-valid-color-name-p))))
3602           (defvar font-lock-reference-face 'font-lock-reference-face)
3603           (defvar font-lock-variable-name-face 'font-lock-variable-name-face)
3604           (or (boundp 'font-lock-type-face)
3605               (defconst font-lock-type-face
3606                 'font-lock-type-face
3607                 "Face to use for data types.")
3608               )
3609           (or (boundp 'font-lock-other-type-face)
3610               (defconst font-lock-other-type-face
3611                 'font-lock-other-type-face
3612                 "Face to use for data types from another group.")
3613               )
3614           (if (not cperl-xemacs-p) nil
3615             (or (boundp 'font-lock-comment-face)
3616                 (defconst font-lock-comment-face
3617                   'font-lock-comment-face
3618                   "Face to use for comments.")
3619                 )
3620             (or (boundp 'font-lock-keyword-face)
3621                 (defconst font-lock-keyword-face
3622                   'font-lock-keyword-face
3623                   "Face to use for keywords.")
3624                 )
3625             (or (boundp 'font-lock-function-name-face)
3626                 (defconst font-lock-function-name-face
3627                   'font-lock-function-name-face
3628                   "Face to use for function names.")
3629                 )
3630             )
3631           ;;(if (featurep 'font-lock)
3632           (if (face-equal font-lock-type-face font-lock-comment-face)
3633               (defconst font-lock-type-face
3634                 'font-lock-type-face
3635                 "Face to use for basic data types.")
3636             )
3637 ;;;       (if (fboundp 'eval-after-load)
3638 ;;;           (eval-after-load "font-lock"
3639 ;;;                            '(if (face-equal font-lock-type-face
3640 ;;;                                             font-lock-comment-face)
3641 ;;;                                 (defconst font-lock-type-face
3642 ;;;                                   'font-lock-type-face
3643 ;;;                                   "Face to use for basic data types.")
3644 ;;;                               )))   ; This does not work :-( Why?!
3645 ;;;                                     ; Workaround: added to font-lock-m-h
3646 ;;;       )
3647           (or (boundp 'font-lock-other-emphasized-face)
3648               (defconst font-lock-other-emphasized-face
3649                 'font-lock-other-emphasized-face
3650                 "Face to use for another type of emphasizing.")
3651               )
3652           (or (boundp 'font-lock-emphasized-face)
3653               (defconst font-lock-emphasized-face
3654                 'font-lock-emphasized-face
3655                 "Face to use for emphasizing.")
3656               )
3657           ;; Here we try to guess background
3658           (let ((background
3659                  (if (boundp 'font-lock-background-mode)
3660                      font-lock-background-mode
3661                    'light)) 
3662                 (face-list (and (fboundp 'face-list) (face-list)))
3663                 is-face)
3664             (fset 'is-face
3665                   (cond ((fboundp 'find-face)
3666                          (symbol-function 'find-face))
3667                         (face-list
3668                          (function (lambda (face) (member face face-list))))
3669                         (t
3670                          (function (lambda (face) (boundp face))))))
3671             (defvar cperl-guessed-background
3672               (if (and (boundp 'font-lock-display-type)
3673                        (eq font-lock-display-type 'grayscale))
3674                   'gray
3675                 background)
3676               "Background as guessed by CPerl mode")
3677             (if (is-face 'font-lock-type-face) nil
3678               (copy-face 'default 'font-lock-type-face)
3679               (cond
3680                ((eq background 'light)
3681                 (set-face-foreground 'font-lock-type-face
3682                                      (if (x-color-defined-p "seagreen")
3683                                          "seagreen"
3684                                        "sea green")))
3685                ((eq background 'dark)
3686                 (set-face-foreground 'font-lock-type-face
3687                                      (if (x-color-defined-p "os2pink")
3688                                          "os2pink"
3689                                        "pink")))
3690                (t
3691                 (set-face-background 'font-lock-type-face "gray90"))))
3692             (if (is-face 'font-lock-other-type-face)
3693                 nil
3694               (copy-face 'font-lock-type-face 'font-lock-other-type-face)
3695               (cond
3696                ((eq background 'light)
3697                 (set-face-foreground 'font-lock-other-type-face
3698                                      (if (x-color-defined-p "chartreuse3")
3699                                          "chartreuse3"
3700                                        "chartreuse")))
3701                ((eq background 'dark)
3702                 (set-face-foreground 'font-lock-other-type-face
3703                                      (if (x-color-defined-p "orchid1")
3704                                          "orchid1"
3705                                        "orange")))))
3706             (if (is-face 'font-lock-other-emphasized-face) nil
3707               (copy-face 'bold-italic 'font-lock-other-emphasized-face)
3708               (cond
3709                ((eq background 'light)
3710                 (set-face-background 'font-lock-other-emphasized-face
3711                                      (if (x-color-defined-p "lightyellow2")
3712                                          "lightyellow2"
3713                                        (if (x-color-defined-p "lightyellow")
3714                                            "lightyellow"
3715                                          "light yellow"))))
3716                ((eq background 'dark)
3717                 (set-face-background 'font-lock-other-emphasized-face
3718                                      (if (x-color-defined-p "navy")
3719                                          "navy"
3720                                        (if (x-color-defined-p "darkgreen")
3721                                            "darkgreen"
3722                                          "dark green"))))
3723                (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
3724             (if (is-face 'font-lock-emphasized-face) nil
3725               (copy-face 'bold 'font-lock-emphasized-face)
3726               (cond
3727                ((eq background 'light)
3728                 (set-face-background 'font-lock-emphasized-face
3729                                      (if (x-color-defined-p "lightyellow2")
3730                                          "lightyellow2"
3731                                        "lightyellow")))
3732                ((eq background 'dark)
3733                 (set-face-background 'font-lock-emphasized-face
3734                                      (if (x-color-defined-p "navy")
3735                                          "navy"
3736                                        (if (x-color-defined-p "darkgreen")
3737                                            "darkgreen"
3738                                          "dark green"))))
3739                (t (set-face-background 'font-lock-emphasized-face "gray90"))))
3740             (if (is-face 'font-lock-variable-name-face) nil
3741               (copy-face 'italic 'font-lock-variable-name-face))
3742             (if (is-face 'font-lock-reference-face) nil
3743               (copy-face 'italic 'font-lock-reference-face))))
3744         (setq cperl-faces-init t))
3745     (error nil)))
3746
3747
3748 (defun cperl-ps-print-init ()
3749   "Initialization of `ps-print' components for faces used in CPerl."
3750   ;; Guard against old versions
3751   (defvar ps-underlined-faces nil)
3752   (defvar ps-bold-faces nil)
3753   (defvar ps-italic-faces nil)
3754   (setq ps-bold-faces
3755         (append '(font-lock-emphasized-face
3756                   font-lock-keyword-face 
3757                   font-lock-variable-name-face 
3758                   font-lock-reference-face 
3759                   font-lock-other-emphasized-face) 
3760                 ps-bold-faces))
3761   (setq ps-italic-faces
3762         (append '(font-lock-other-type-face
3763                   font-lock-reference-face 
3764                   font-lock-other-emphasized-face)
3765                 ps-italic-faces))
3766   (setq ps-underlined-faces
3767         (append '(font-lock-emphasized-face
3768                   font-lock-other-emphasized-face 
3769                   font-lock-other-type-face font-lock-type-face)
3770                 ps-underlined-faces))
3771   (cons 'font-lock-type-face ps-underlined-faces))
3772
3773
3774 (if (cperl-enable-font-lock) (cperl-windowed-init))
3775
3776 (defun cperl-set-style (style)
3777   "Set CPerl-mode variables to use one of several different indentation styles.
3778 The arguments are a string representing the desired style.
3779 Available styles are GNU, K&R, BSD and Whitesmith."
3780   (interactive 
3781    (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
3782                        c-style-alist)))
3783      (list (completing-read "Enter style: " list nil 'insist))))
3784   (let ((style (cdr (assoc style c-style-alist))) setting str sym)
3785     (while style
3786       (setq setting (car style) style (cdr style))
3787       (setq str (symbol-name (car setting)))
3788       (and (string-match "^c-" str)
3789            (setq str (concat "cperl-" (substring str 2)))
3790            (setq sym (intern-soft str))
3791            (boundp sym)
3792            (set sym (cdr setting))))))
3793
3794 (defun cperl-check-syntax ()
3795   (interactive)
3796   (require 'mode-compile)
3797   (let ((perl-dbg-flags "-wc"))
3798     (mode-compile)))
3799
3800 (defun cperl-info-buffer (type)
3801   ;; Returns buffer with documentation. Creates if missing.
3802   ;; If TYPE, this vars buffer.
3803   ;; Special care is taken to not stomp over an existing info buffer
3804   (let* ((bname (if type "*info-perl-var*" "*info-perl*"))
3805          (info (get-buffer bname))
3806          (oldbuf (get-buffer "*info*")))
3807     (if info info
3808       (save-window-excursion
3809         ;; Get Info running
3810         (require 'info)
3811         (cond (oldbuf
3812                (set-buffer oldbuf)
3813                (rename-buffer "*info-perl-tmp*")))
3814         (save-window-excursion
3815           (info))
3816         (Info-find-node cperl-info-page (if type "perlvar" "perlfunc"))
3817         (set-buffer "*info*")
3818         (rename-buffer bname)
3819         (cond (oldbuf
3820                (set-buffer "*info-perl-tmp*")
3821                (rename-buffer "*info*")
3822                (set-buffer bname)))
3823         (make-variable-buffer-local 'window-min-height)
3824         (setq window-min-height 2)
3825         (current-buffer)))))
3826
3827 (defun cperl-word-at-point (&optional p)
3828   ;; Returns the word at point or at P.
3829   (save-excursion
3830     (if p (goto-char p))
3831     (or (cperl-word-at-point-hard)
3832         (progn
3833           (require 'etags)
3834           (funcall (or (and (boundp 'find-tag-default-function)
3835                             find-tag-default-function)
3836                        (get major-mode 'find-tag-default-function)
3837                        ;; XEmacs 19.12 has `find-tag-default-hook'; it is
3838                        ;; automatically used within `find-tag-default':
3839                        'find-tag-default))))))
3840
3841 (defun cperl-info-on-command (command)
3842   "Shows documentation for Perl command in other window.
3843 If perl-info buffer is shown in some frame, uses this frame.
3844 Customized by setting variables `cperl-shrink-wrap-info-frame',
3845 `cperl-max-help-size'."
3846   (interactive 
3847    (let* ((default (cperl-word-at-point))
3848           (read (read-string 
3849                      (format "Find doc for Perl function (default %s): " 
3850                              default))))
3851      (list (if (equal read "") 
3852                    default 
3853                  read))))
3854
3855   (let ((buffer (current-buffer))
3856         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
3857         pos isvar height iniheight frheight buf win fr1 fr2 iniwin not-loner
3858         max-height char-height buf-list)
3859     (if (string-match "^-[a-zA-Z]$" command)
3860         (setq cmd-desc "^-X[ \t\n]"))
3861     (setq isvar (string-match "^[$@%]" command)
3862           buf (cperl-info-buffer isvar)
3863           iniwin (selected-window)
3864           fr1 (window-frame iniwin))
3865     (set-buffer buf)
3866     (beginning-of-buffer)
3867     (or isvar 
3868         (progn (re-search-forward "^-X[ \t\n]")
3869                (forward-line -1)))
3870     (if (re-search-forward cmd-desc nil t)
3871         (progn
3872           ;; Go back to beginning of the group (ex, for qq)
3873           (if (re-search-backward "^[ \t\n\f]")
3874               (forward-line 1))
3875           (beginning-of-line)
3876           ;; Get some of 
3877           (setq pos (point)
3878                 buf-list (list buf "*info-perl-var*" "*info-perl*"))
3879           (while (and (not win) buf-list)
3880             (setq win (get-buffer-window (car buf-list) t))
3881             (setq buf-list (cdr buf-list)))
3882           (or (not win)
3883               (eq (window-buffer win) buf)
3884               (set-window-buffer win buf))
3885           (and win (setq fr2 (window-frame win)))
3886           (if (or (not fr2) (eq fr1 fr2))
3887               (pop-to-buffer buf)
3888             (special-display-popup-frame buf) ; Make it visible
3889             (select-window win))
3890           (goto-char pos)               ; Needed (?!).
3891           ;; Resize
3892           (setq iniheight (window-height)
3893                 frheight (frame-height)
3894                 not-loner (< iniheight (1- frheight))) ; Are not alone
3895           (cond ((if not-loner cperl-max-help-size 
3896                    cperl-shrink-wrap-info-frame)
3897                  (setq height 
3898                        (+ 2 
3899                           (count-lines 
3900                            pos 
3901                            (save-excursion
3902                              (if (re-search-forward
3903                                   "^[ \t][^\n]*\n+\\([^ \t\n\f]\\|\\'\\)" nil t)
3904                                  (match-beginning 0) (point-max)))))
3905                        max-height 
3906                        (if not-loner
3907                            (/ (* (- frheight 3) cperl-max-help-size) 100)
3908                          (setq char-height (frame-char-height))
3909                          ;; Non-functioning under OS/2:
3910                          (if (eq char-height 1) (setq char-height 18))
3911                          ;; Title, menubar, + 2 for slack
3912                          (- (/ (x-display-pixel-height) char-height) 4)
3913                          ))
3914                  (if (> height max-height) (setq height max-height))
3915                  ;;(message "was %s doing %s" iniheight height)
3916                  (if not-loner
3917                      (enlarge-window (- height iniheight))
3918                    (set-frame-height (window-frame win) (1+ height)))))
3919           (set-window-start (selected-window) pos))
3920       (message "No entry for %s found." command))
3921     ;;(pop-to-buffer buffer)
3922     (select-window iniwin)))
3923
3924 (defun cperl-info-on-current-command ()
3925   "Shows documentation for Perl command at point in other window."
3926   (interactive)
3927   (cperl-info-on-command (cperl-word-at-point)))
3928
3929 (defun cperl-imenu-info-imenu-search ()
3930   (if (looking-at "^-X[ \t\n]") nil
3931     (re-search-backward
3932      "^\n\\([-a-zA-Z_]+\\)[ \t\n]")
3933     (forward-line 1)))
3934
3935 (defun cperl-imenu-info-imenu-name ()  
3936   (buffer-substring
3937    (match-beginning 1) (match-end 1)))
3938
3939 (defun cperl-imenu-on-info ()
3940   (interactive)
3941   (let* ((buffer (current-buffer))
3942          imenu-create-index-function
3943          imenu-prev-index-position-function 
3944          imenu-extract-index-name-function 
3945          (index-item (save-restriction
3946                        (save-window-excursion
3947                          (set-buffer (cperl-info-buffer nil))
3948                          (setq imenu-create-index-function 
3949                                'imenu-default-create-index-function
3950                                imenu-prev-index-position-function
3951                                'cperl-imenu-info-imenu-search
3952                                imenu-extract-index-name-function
3953                                'cperl-imenu-info-imenu-name)
3954                          (imenu-choose-buffer-index)))))
3955     (and index-item
3956          (progn
3957            (push-mark)
3958            (pop-to-buffer "*info-perl*")
3959            (cond
3960             ((markerp (cdr index-item))
3961              (goto-char (marker-position (cdr index-item))))
3962             (t
3963              (goto-char (cdr index-item))))
3964            (set-window-start (selected-window) (point))
3965            (pop-to-buffer buffer)))))
3966
3967 (defun cperl-lineup (beg end &optional step minshift)
3968   "Lineup construction in a region.
3969 Beginning of region should be at the start of a construction.
3970 All first occurrences of this construction in the lines that are
3971 partially contained in the region are lined up at the same column.
3972
3973 MINSHIFT is the minimal amount of space to insert before the construction.
3974 STEP is the tabwidth to position constructions.
3975 If STEP is `nil', `cperl-lineup-step' will be used 
3976 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
3977 Will not move the position at the start to the left."
3978   (interactive "r")
3979   (let (search col tcol seen b e)
3980     (save-excursion
3981       (goto-char end)
3982       (end-of-line)
3983       (setq end (point-marker))
3984       (goto-char beg)
3985       (skip-chars-forward " \t\f")
3986       (setq beg (point-marker))
3987       (indent-region beg end nil)
3988       (goto-char beg)
3989       (setq col (current-column))
3990       (if (looking-at "[a-zA-Z0-9_]")
3991           (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
3992               (setq search
3993                     (concat "\\<" 
3994                             (regexp-quote 
3995                              (buffer-substring (match-beginning 0)
3996                                                (match-end 0))) "\\>"))
3997             (error "Cannot line up in a middle of the word"))
3998         (if (looking-at "$")
3999             (error "Cannot line up end of line"))
4000         (setq search (regexp-quote (char-to-string (following-char)))))
4001       (setq step (or step cperl-lineup-step cperl-indent-level))
4002       (or minshift (setq minshift 1))
4003       (while (progn
4004                (beginning-of-line 2)
4005                (and (< (point) end) 
4006                     (re-search-forward search end t)
4007                     (goto-char (match-beginning 0))))
4008         (setq tcol (current-column) seen t)
4009         (if (> tcol col) (setq col tcol)))
4010       (or seen
4011           (error "The construction to line up occurred only once"))
4012       (goto-char beg)
4013       (setq col (+ col minshift))
4014       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
4015       (while 
4016           (progn
4017             (setq e (point))
4018             (skip-chars-backward " \t")
4019             (delete-region (point) e)
4020             (indent-to-column col); (make-string (- col (current-column)) ?\ ))
4021             (beginning-of-line 2) 
4022             (and (< (point) end) 
4023                  (re-search-forward search end t)
4024                  (goto-char (match-beginning 0)))))))) ; No body
4025
4026 (defun cperl-etags (&optional add all files)
4027   "Run etags with appropriate options for Perl files.
4028 If optional argument ALL is `recursive', will process Perl files
4029 in subdirectories too."
4030   (interactive)
4031   (let ((cmd "etags")
4032         (args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\(([^()]*)[ \t]*\\)?\\([{#]\\|$\\)\\)/\\4/"))
4033         res)
4034     (if add (setq args (cons "-a" args)))
4035     (or files (setq files (list buffer-file-name)))
4036     (cond
4037      ((eq all 'recursive)
4038       ;;(error "Not implemented: recursive")
4039       (setq args (append (list "-e" 
4040                                "sub wanted {push @ARGV, $File::Find::name if /\\.[Pp][Llm]$/}
4041                                 use File::Find;
4042                                 find(\\&wanted, '.');
4043                                 exec @ARGV;" 
4044                                cmd) args)
4045             cmd "perl"))
4046      (all 
4047       ;;(error "Not implemented: all")
4048       (setq args (append (list "-e" 
4049                                "push @ARGV, <*.PL *.pl *.pm>;
4050                                 exec @ARGV;" 
4051                                cmd) args)
4052             cmd "perl"))
4053      (t
4054       (setq args (append args files))))
4055     (setq res (apply 'call-process cmd nil nil nil args))
4056     (or (eq res 0)
4057         (message "etags returned \"%s\"" res))))
4058
4059 (defun cperl-toggle-auto-newline ()
4060   "Toggle the state of `cperl-auto-newline'."
4061   (interactive)
4062   (setq cperl-auto-newline (not cperl-auto-newline))
4063   (message "Newlines will %sbe auto-inserted now." 
4064            (if cperl-auto-newline "" "not ")))
4065
4066 (defun cperl-toggle-abbrev ()
4067   "Toggle the state of automatic keyword expansion in CPerl mode."
4068   (interactive)
4069   (abbrev-mode (if abbrev-mode 0 1))
4070   (message "Perl control structure will %sbe auto-inserted now." 
4071            (if abbrev-mode "" "not ")))
4072
4073
4074 (defun cperl-toggle-electric ()
4075   "Toggle the state of parentheses doubling in CPerl mode."
4076   (interactive)
4077   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
4078   (message "Parentheses will %sbe auto-doubled now." 
4079            (if (cperl-val 'cperl-electric-parens) "" "not ")))
4080
4081 ;;;; Tags file creation.
4082
4083 (defvar cperl-tmp-buffer " *cperl-tmp*")
4084
4085 (defun cperl-setup-tmp-buf ()
4086   (set-buffer (get-buffer-create cperl-tmp-buffer))
4087   (set-syntax-table cperl-mode-syntax-table)
4088   (buffer-disable-undo)
4089   (auto-fill-mode 0))
4090
4091 (defun cperl-xsub-scan ()
4092   (require 'cl)
4093   (require 'imenu)
4094   (let ((index-alist '()) 
4095         (prev-pos 0) index index1 name package prefix)
4096     (goto-char (point-min))
4097     (imenu-progress-message prev-pos 0)
4098     ;; Search for the function
4099     (progn ;;save-match-data
4100       (while (re-search-forward
4101               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
4102               nil t)
4103         (imenu-progress-message prev-pos)
4104         (cond
4105          ((match-beginning 2)   ; SECTION
4106           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
4107           (goto-char (match-beginning 0))
4108           (skip-chars-forward " \t")
4109           (forward-char 1)
4110           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
4111               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
4112             (setq prefix nil)))
4113          ((not package) nil)            ; C language section
4114          ((match-beginning 3)           ; XSUB
4115           (goto-char (1+ (match-beginning 3)))
4116           (setq index (imenu-example--name-and-position))
4117           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
4118           (if (and prefix (string-match (concat "^" prefix) name))
4119               (setq name (substring name (length prefix))))
4120           (cond ((string-match "::" name) nil)
4121                 (t
4122                  (setq index1 (cons (concat package "::" name) (cdr index)))
4123                  (push index1 index-alist)))
4124           (setcar index name)
4125           (push index index-alist))
4126          (t                             ; BOOT: section
4127           ;; (beginning-of-line)
4128           (setq index (imenu-example--name-and-position))
4129           (setcar index (concat package "::BOOT:"))
4130           (push index index-alist)))))
4131     (imenu-progress-message prev-pos 100)
4132     ;;(setq index-alist 
4133     ;;      (if (default-value 'imenu-sort-function)
4134     ;;          (sort index-alist (default-value 'imenu-sort-function))
4135     ;;          (nreverse index-alist)))
4136     index-alist))
4137
4138 (defun cperl-find-tags (file xs)
4139   (let (ind (b (get-buffer cperl-tmp-buffer)) lst elt pos ret)
4140     (save-excursion
4141       (if b (set-buffer b)
4142           (cperl-setup-tmp-buf))
4143       (erase-buffer)
4144       (setq file (car (insert-file-contents file)))
4145       (message "Scanning file %s..." file)
4146       (if xs
4147           (setq lst (cperl-xsub-scan))
4148         (setq ind (imenu-example--create-perl-index))
4149         (setq lst (cdr (assoc "+Unsorted List+..." ind))))
4150       (setq lst 
4151             (mapcar 
4152              (function 
4153               (lambda (elt)
4154                 (cond ((string-match "^[_a-zA-Z]" (car elt))
4155                        (goto-char (cdr elt))
4156                        (list (car elt) 
4157                              (point) (count-lines 1 (point))
4158                              (buffer-substring (progn
4159                                                  (skip-chars-forward 
4160                                                   ":_a-zA-Z0-9")
4161                                                  (or (eolp) (forward-char 1))
4162                                                  (point))
4163                                                (progn
4164                                                  (beginning-of-line)
4165                                                  (point))))))))
4166                     lst))
4167       (erase-buffer)
4168       (while lst
4169         (setq elt (car lst) lst (cdr lst))
4170         (if elt
4171             (progn
4172               (insert (elt elt 3) 
4173                       127
4174                       (if (string-match "^package " (car elt))
4175                           (substring (car elt) 8)
4176                         (car elt) )
4177                       1
4178                       (number-to-string (elt elt 1))
4179                       ","
4180                       (number-to-string (elt elt 2))
4181                       "\n")
4182               (if (and (string-match "^[_a-zA-Z]+::" (car elt))
4183                        (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
4184                                      (elt elt 3)))
4185                   ;; Need to insert the name without package as well
4186                   (setq lst (cons (cons (substring (elt elt 3) 
4187                                                    (match-beginning 1)
4188                                                    (match-end 1))
4189                                         (cdr elt))
4190                                   lst))))))
4191       (setq pos (point))
4192       (goto-char 1)
4193       (insert "\f\n" file "," (number-to-string (1- pos)) "\n")
4194       (setq ret (buffer-substring 1 (point-max)))
4195       (erase-buffer)
4196       (message "Scanning file %s finished" file)
4197       ret)))
4198
4199 (defun cperl-write-tags (&optional file erase recurse dir inbuffer)
4200   ;; If INBUFFER, do not select buffer, and do not save
4201   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
4202   (require 'etags)
4203   (if file nil
4204     (setq file (if dir default-directory (buffer-file-name)))
4205     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
4206   (let ((tags-file-name "TAGS")
4207         (case-fold-search (eq system-type 'emx))
4208         xs)
4209     (save-excursion
4210       (cond (inbuffer nil)              ; Already there
4211             ((file-exists-p tags-file-name)
4212              (visit-tags-table-buffer tags-file-name))
4213             (t (set-buffer (find-file-noselect tags-file-name))))
4214       (cond
4215        (dir
4216         (cond ((eq erase 'ignore))
4217               (erase
4218                (erase-buffer)
4219                (setq erase 'ignore)))
4220         (let ((files 
4221                (directory-files file t 
4222                                 (if recurse nil cperl-scan-files-regexp)
4223                                 t)))
4224           (mapcar (function (lambda (file)
4225                               (cond
4226                                ((string-match cperl-noscan-files-regexp file)
4227                                 nil)
4228                                ((not (file-directory-p file))
4229                                 (if (string-match cperl-scan-files-regexp file)
4230                                     (cperl-write-tags file erase recurse nil t)))
4231                                ((not recurse) nil)
4232                                (t (cperl-write-tags file erase recurse t t)))))
4233                   files))
4234         )
4235        (t
4236         (setq xs (string-match "\\.xs$" file))
4237         (cond ((eq erase 'ignore) (goto-char (point-max)))
4238               (erase (erase-buffer))
4239               (t
4240                (goto-char 1)
4241                (if (search-forward (concat "\f\n" file ",") nil t)
4242                    (progn
4243                      (search-backward "\f\n")
4244                      (delete-region (point)
4245                                     (progn 
4246                                       (forward-char 1)
4247                                       (search-forward "\f\n" nil 'toend)
4248                                       (point))))
4249                  (goto-char (point-max)))))
4250         (insert (cperl-find-tags file xs))))
4251       (if inbuffer nil          ; Delegate to the caller
4252         (save-buffer 0)         ; No backup
4253         (if (fboundp 'initialize-new-tags-table) ; Do we need something special in XEmacs?
4254             (initialize-new-tags-table))))))
4255
4256 (defvar cperl-tags-hier-regexp-list
4257   (concat 
4258    "^\\("
4259       "\\(package\\)\\>"
4260      "\\|"
4261       "sub\\>[^\n]+::"
4262      "\\|"
4263       "[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::" ; XSUB?
4264      "\\|"
4265       "[ \t]*BOOT:\C-?[^\n]+::"         ; BOOT section
4266    "\\)"))
4267
4268 (defvar cperl-hierarchy '(() ())
4269   "Global hierarchy of classes")
4270
4271 (defun cperl-tags-hier-fill ()
4272   ;; Suppose we are in a tag table cooked by cperl.
4273   (goto-char 1)
4274   (let (type pack name pos line chunk ord cons1 file str info fileind)
4275     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
4276       (setq pos (match-beginning 0) 
4277             pack (match-beginning 2))
4278       (beginning-of-line)
4279       (if (looking-at (concat
4280                        "\\([^\n]+\\)"
4281                        "\C-?"
4282                        "\\([^\n]+\\)"
4283                        "\C-a"
4284                        "\\([0-9]+\\)"
4285                        ","
4286                        "\\([0-9]+\\)"))
4287           (progn
4288             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
4289                   name (buffer-substring (match-beginning 2) (match-end 2))
4290                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
4291                   line (buffer-substring (match-beginning 4) (match-end 4))
4292                   ord (if pack 1 0)
4293                   info (etags-snarf-tag) ; Moves to beginning of the next line
4294                   file (file-of-tag)
4295                   fileind (format "%s:%s" file line))
4296             ;; Move back
4297             (forward-char -1)
4298             ;; Make new member of hierarchy name ==> file ==> pos if needed
4299             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
4300                 ;; Name known
4301                 (setcdr cons1 (cons (cons fileind (vector file info))
4302                                     (cdr cons1)))
4303               ;; First occurrence of the name, start alist
4304               (setq cons1 (cons name (list (cons fileind (vector file info)))))
4305               (if pack 
4306                   (setcar (cdr cperl-hierarchy)
4307                           (cons cons1 (nth 1 cperl-hierarchy)))
4308                 (setcar cperl-hierarchy
4309                         (cons cons1 (car cperl-hierarchy)))))))
4310       (end-of-line))))
4311
4312 (defun cperl-tags-hier-init (&optional update)
4313   "Show hierarchical menu of classes and methods.
4314 Finds info about classes by a scan of loaded TAGS files.
4315 Supposes that the TAGS files contain fully qualified function names.
4316 One may build such TAGS files from CPerl mode menu."
4317   (interactive)
4318   (require 'etags)
4319   (require 'imenu)
4320   (if (or update (null (nth 2 cperl-hierarchy)))
4321       (let (pack name cons1 to l1 l2 l3 l4
4322                  (remover (function (lambda (elt) ; (name (file1...) (file2..))
4323                                       (or (nthcdr 2 elt)
4324                                           ;; Only in one file
4325                                           (setcdr elt (cdr (nth 1 elt))))))))
4326         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
4327         (setq cperl-hierarchy (list l1 l2 l3))
4328         (or tags-table-list
4329             (call-interactively 'visit-tags-table))
4330         (message "Updating list of classes...")
4331         (mapcar 
4332          (function
4333           (lambda (tagsfile)
4334             (set-buffer (get-file-buffer tagsfile))
4335             (cperl-tags-hier-fill)))
4336          tags-table-list)
4337         (mapcar remover (car cperl-hierarchy))
4338         (mapcar remover (nth 1 cperl-hierarchy))
4339         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
4340                        (cons "Methods: " (car cperl-hierarchy))))
4341         (cperl-tags-treeify to 1)
4342         (setcar (nthcdr 2 cperl-hierarchy)
4343                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
4344         (message "Updating list of classes: done, requesting display...")
4345         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
4346         ))
4347   (or (nth 2 cperl-hierarchy)
4348       (error "No items found"))
4349   (setq update
4350 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
4351         (if window-system
4352             (x-popup-menu t (nth 2 cperl-hierarchy))
4353           (require 'tmm)
4354           (tmm-prompt (nth 2 cperl-hierarchy))))
4355   (if (and update (listp update))
4356       (progn (while (cdr update) (setq update (cdr update)))
4357              (setq update (car update)))) ; Get the last from the list
4358   (if (vectorp update) 
4359       (progn
4360         (find-file (elt update 0))
4361         (etags-goto-tag-location (elt update 1))))
4362   (if (eq update -999) (cperl-tags-hier-init t)))
4363
4364 (defun cperl-tags-treeify (to level)
4365   ;; cadr of to is read-write. On start it is a cons
4366   (let* ((regexp (concat "^\\(" (mapconcat 
4367                                  'identity
4368                                  (make-list level "[_a-zA-Z0-9]+")
4369                                  "::")
4370                          "\\)\\(::\\)?"))
4371          (packages (cdr (nth 1 to)))
4372          (methods (cdr (nth 2 to)))
4373          l1 head tail cons1 cons2 ord writeto packs recurse
4374          root-packages root-functions ms many_ms same_name ps
4375          (move-deeper
4376           (function 
4377            (lambda (elt)
4378              (cond ((and (string-match regexp (car elt))
4379                          (or (eq ord 1) (match-end 2)))
4380                     (setq head (substring (car elt) 0 (match-end 1))
4381                           tail (if (match-end 2) (substring (car elt) 
4382                                                             (match-end 2)))
4383                           recurse t)
4384                     (if (setq cons1 (assoc head writeto)) nil
4385                       ;; Need to init new head
4386                       (setcdr writeto (cons (list head (list "Packages: ")
4387                                                   (list "Methods: "))
4388                                             (cdr writeto)))
4389                       (setq cons1 (nth 1 writeto)))
4390                     (setq cons2 (nth ord cons1)) ; Either packs or meths
4391                     (setcdr cons2 (cons elt (cdr cons2))))
4392                    ((eq ord 2)
4393                     (setq root-functions (cons elt root-functions)))
4394                    (t
4395                     (setq root-packages (cons elt root-packages))))))))
4396     (setcdr to l1)                      ; Init to dynamic space
4397     (setq writeto to)
4398     (setq ord 1)
4399     (mapcar move-deeper packages)
4400     (setq ord 2)
4401     (mapcar move-deeper methods)
4402     (if recurse
4403         (mapcar (function (lambda (elt)
4404                           (cperl-tags-treeify elt (1+ level))))
4405                 (cdr to)))
4406     ;; Now add back functions removed from display
4407     (mapcar (function (lambda (elt)
4408                         (setcdr to (cons elt (cdr to)))))
4409             root-functions)
4410     ;; Now add back packages removed from display
4411     (mapcar (function (lambda (elt)
4412                         (setcdr to (cons (cons (concat "package " (car elt)) 
4413                                                (cdr elt)) 
4414                                          (cdr to)))))
4415             root-packages)
4416     ;;Now clean up leaders with one child only
4417     (mapcar (function (lambda (elt)
4418                         (if (not (and (listp (cdr elt)) 
4419                                       (eq (length elt) 2))) nil
4420                             (setcar elt (car (nth 1 elt)))
4421                             (setcdr elt (cdr (nth 1 elt))))))
4422             (cdr to))
4423     ))
4424
4425 ;;;(x-popup-menu t
4426 ;;;   '(keymap "Name1" 
4427 ;;;         ("Ret1" "aa")
4428 ;;;         ("Head1" "ab"  
4429 ;;;          keymap "Name2" 
4430 ;;;          ("Tail1" "x") ("Tail2" "y"))))
4431
4432 (defun cperl-list-fold (list name limit)
4433   (let (list1 list2 elt1 (num 0))
4434     (if (<= (length list) limit) list
4435       (setq list1 nil list2 nil)
4436       (while list
4437         (setq num (1+ num) 
4438               elt1 (car list)
4439               list (cdr list))
4440         (if (<= num imenu-max-items)
4441             (setq list2 (cons elt1 list2))
4442           (setq list1 (cons (cons name
4443                                   (nreverse list2))
4444                             list1)
4445                 list2 (list elt1)
4446                 num 1)))
4447       (nreverse (cons (cons name
4448                             (nreverse list2))
4449                       list1)))))
4450
4451 (defun cperl-menu-to-keymap (menu &optional name)
4452   (let (list)
4453     (cons 'keymap 
4454           (mapcar 
4455            (function 
4456             (lambda (elt)
4457               (cond ((listp (cdr elt))
4458                      (setq list (cperl-list-fold
4459                                  (cdr elt) (car elt) imenu-max-items))
4460                      (cons nil
4461                            (cons (car elt)
4462                                  (cperl-menu-to-keymap list))))
4463                     (t
4464                      (list (cdr elt) (car elt) t))))) ; t is needed in 19.34
4465            (cperl-list-fold menu "Root" imenu-max-items)))))
4466
4467 \f
4468 (defvar cperl-bad-style-regexp
4469   (mapconcat 'identity
4470    '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
4471      "[-<>=+^&|]+[^- \t\n=+<>~]"        ; sign+ char
4472      )
4473    "\\|")
4474   "Finds places such that insertion of a whitespace may help a lot.")
4475
4476 (defvar cperl-not-bad-style-regexp 
4477   (mapconcat 'identity
4478    '("[^-\t <>=+]\\(--\\|\\+\\+\\)"     ; var-- var++
4479      "[a-zA-Z0-9_][|&][a-zA-Z0-9_$]"    ; abc|def abc&def are often used.
4480      "&[(a-zA-Z0-9_$]"                  ; &subroutine &(var->field)
4481      "<\\$?\\sw+\\(\\.\\sw+\\)?>"       ; <IN> <stdin.h>
4482      "-[a-zA-Z][ \t]+[_$\"'`]"          ; -f file
4483      "-[0-9]"                           ; -5
4484      "\\+\\+"                           ; ++var
4485      "--"                               ; --var
4486      ".->"                              ; a->b
4487      "->"                               ; a SPACE ->b
4488      "\\[-"                             ; a[-1]
4489      "^="                               ; =head
4490      "||"
4491      "&&"
4492      "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
4493      "-[a-zA-Z_0-9]+[ \t]*=>"                   ; -option => value
4494      ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
4495      ;;"[*/+-|&<.]+="
4496      )
4497    "\\|")
4498   "If matches at the start of match found by `my-bad-c-style-regexp',
4499 insertion of a whitespace will not help.")
4500
4501 (defvar found-bad)
4502
4503 (defun cperl-find-bad-style ()
4504   "Find places in the buffer where insertion of a whitespace may help.
4505 Prompts user for insertion of spaces.
4506 Currently it is tuned to C and Perl syntax."
4507   (interactive)
4508   (let (found-bad (p (point)))
4509     (setq last-nonmenu-event 13)        ; To disable popup
4510     (beginning-of-buffer)
4511     (map-y-or-n-p "Insert space here? "
4512                   (function (lambda (arg) (insert " ")))
4513                   'cperl-next-bad-style
4514                   '("location" "locations" "insert a space into") 
4515                   '((?\C-r (lambda (arg)
4516                              (let ((buffer-quit-function
4517                                     'exit-recursive-edit))
4518                                (message "Exit with Esc Esc")
4519                                (recursive-edit)
4520                                t))      ; Consider acted upon
4521                            "edit, exit with Esc Esc") 
4522                     (?e (lambda (arg)
4523                           (let ((buffer-quit-function
4524                                  'exit-recursive-edit))
4525                             (message "Exit with Esc Esc")
4526                             (recursive-edit)
4527                             t))         ; Consider acted upon
4528                         "edit, exit with Esc Esc"))
4529                   t)
4530     (if found-bad (goto-char found-bad)
4531       (goto-char p)
4532       (message "No appropriate place found"))))
4533
4534 (defun cperl-next-bad-style ()
4535   (let (p (not-found t) (point (point)) found)
4536     (while (and not-found
4537                 (re-search-forward cperl-bad-style-regexp nil 'to-end))
4538       (setq p (point))
4539       (goto-char (match-beginning 0))
4540       (if (or
4541            (looking-at cperl-not-bad-style-regexp)
4542            ;; Check for a < -b and friends
4543            (and (eq (following-char) ?\-)
4544                 (save-excursion
4545                   (skip-chars-backward " \t\n")
4546                   (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\(, ?\[, ?\{))))
4547            ;; Now check for syntax type
4548            (save-match-data
4549              (setq found (point))
4550              (beginning-of-defun)
4551              (let ((pps (parse-partial-sexp (point) found)))
4552                (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
4553           (goto-char (match-end 0))
4554         (goto-char (1- p))
4555         (setq not-found nil
4556               found-bad found)))
4557     (not not-found)))
4558
4559 \ 6
4560 ;;; Getting help
4561 (defvar cperl-have-help-regexp 
4562   ;;(concat "\\("
4563   (mapconcat
4564    'identity
4565    '("[$@%*&][0-9a-zA-Z_:]+\\([ \t]*[[{]\\)?"           ; Usual variable
4566      "[$@]\\^[a-zA-Z]"                  ; Special variable
4567      "[$@][^ \n\t]"                     ; Special variable
4568      "-[a-zA-Z]"                        ; File test
4569      "\\\\[a-zA-Z0]"                    ; Special chars
4570      "^=[a-z][a-zA-Z0-9_]*"             ; Pod sections
4571      "[-!&*+,-./<=>?\\\\^|~]+"          ; Operator
4572      "[a-zA-Z_0-9:]+"                   ; symbol or number
4573      "x="
4574      "#!"
4575      )
4576    ;;"\\)\\|\\("
4577    "\\|"
4578    )
4579           ;;"\\)"
4580           ;;)
4581   "Matches places in the buffer we can find help for.")
4582
4583 (defvar cperl-message-on-help-error t)
4584 (defvar cperl-help-from-timer nil)
4585
4586 (defun cperl-word-at-point-hard ()
4587   ;; Does not save-excursion
4588   ;; Get to the something meaningful
4589   (or (eobp) (eolp) (forward-char 1))
4590   (re-search-backward "[-a-zA-Z0-9_:!&*+,-./<=>?\\\\^|~$%@]" 
4591                       (save-excursion (beginning-of-line) (point))
4592                       'to-beg)
4593   ;;  (cond
4594   ;;   ((or (eobp) (looking-at "[][ \t\n{}();,]")) ; Not at a symbol
4595   ;;    (skip-chars-backward " \n\t\r({[]});,")
4596   ;;    (or (bobp) (backward-char 1))))
4597   ;; Try to backtrace
4598   (cond
4599    ((looking-at "[a-zA-Z0-9_:]")        ; symbol
4600     (skip-chars-backward "a-zA-Z0-9_:")
4601     (cond 
4602      ((and (eq (preceding-char) ?^)     ; $^I
4603            (eq (char-after (- (point) 2)) ?\$))
4604       (forward-char -2))
4605      ((memq (preceding-char) (append "*$@%&\\" nil)) ; *glob
4606       (forward-char -1))
4607      ((and (eq (preceding-char) ?\=)
4608            (eq (current-column) 1))
4609       (forward-char -1)))               ; =head1
4610     (if (and (eq (preceding-char) ?\<)
4611              (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <FH>
4612         (forward-char -1)))
4613    ((and (looking-at "=") (eq (preceding-char) ?x)) ; x=
4614     (forward-char -1))
4615    ((and (looking-at "\\^") (eq (preceding-char) ?\$)) ; $^I
4616     (forward-char -1))
4617    ((looking-at "[-!&*+,-./<=>?\\\\^|~]")
4618     (skip-chars-backward "-!&*+,-./<=>?\\\\^|~")
4619     (cond
4620      ((and (eq (preceding-char) ?\$)
4621            (not (eq (char-after (- (point) 2)) ?\$))) ; $-
4622       (forward-char -1))
4623      ((and (eq (following-char) ?\>)
4624            (string-match "[a-zA-Z0-9_]" (char-to-string (preceding-char)))
4625            (save-excursion
4626              (forward-sexp -1)
4627              (and (eq (preceding-char) ?\<)
4628                   (looking-at "\\$?[a-zA-Z0-9_:]+>")))) ; <FH>
4629       (search-backward "<"))))
4630    ((and (eq (following-char) ?\$)
4631          (eq (preceding-char) ?\<)
4632          (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <$fh>
4633     (forward-char -1)))
4634   (if (looking-at cperl-have-help-regexp)
4635       (buffer-substring (match-beginning 0) (match-end 0))))
4636
4637 (defun cperl-get-help ()
4638   "Get one-line docs on the symbol at the point.
4639 The data for these docs is a little bit obsolete and may be in fact longer
4640 than a line. Your contribution to update/shorten it is appreciated."
4641   (interactive)
4642   (save-match-data                      ; May be called "inside" query-replace
4643     (save-excursion
4644       (let ((word (cperl-word-at-point-hard)))
4645         (if word
4646             (if (and cperl-help-from-timer ; Bail out if not in mainland
4647                      (not (string-match "^#!\\|\\\\\\|^=" word)) ; Show help even in comments/strings.
4648                      (or (memq (get-text-property (point) 'face)
4649                                '(font-lock-comment-face font-lock-string-face))
4650                          (memq (get-text-property (point) 'syntax-type)
4651                                '(pod here-doc format))))
4652                 nil
4653               (cperl-describe-perl-symbol word))
4654           (if cperl-message-on-help-error
4655               (message "Nothing found for %s..." 
4656                        (buffer-substring (point) (min (+ 5 (point)) (point-max))))))))))
4657
4658 ;;; Stolen from perl-descr.el by Johan Vromans:
4659
4660 (defvar cperl-doc-buffer " *perl-doc*"
4661   "Where the documentation can be found.")
4662
4663 (defun cperl-describe-perl-symbol (val)
4664   "Display the documentation of symbol at point, a Perl operator."
4665   (let ((enable-recursive-minibuffers t)
4666         args-file regexp)
4667     (cond
4668         ((string-match "^[&*][a-zA-Z_]" val)
4669          (setq val (concat (substring val 0 1) "NAME")))
4670         ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*\\[" val)
4671          (setq val (concat "@" (substring val 1 (match-end 1)))))
4672         ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*{" val)
4673          (setq val (concat "%" (substring val 1 (match-end 1)))))
4674         ((and (string= val "x") (string-match "^x=" val))
4675          (setq val "x="))
4676         ((string-match "^\\$[\C-a-\C-z]" val)
4677          (setq val (concat "$^" (char-to-string (+ ?A -1 (aref val 1))))))
4678         ((string-match "^CORE::" val)
4679          (setq val "CORE::"))
4680         ((string-match "^SUPER::" val)
4681          (setq val "SUPER::"))
4682         ((and (string= "<" val) (string-match "^<\\$?[a-zA-Z0-9_:]+>" val))
4683          (setq val "<NAME>")))
4684     (setq regexp (concat "^" 
4685                          "\\([^a-zA-Z0-9_:]+[ \t]+\\)?"
4686                          (regexp-quote val) 
4687                          "\\([ \t([/]\\|$\\)"))
4688
4689     ;; get the buffer with the documentation text
4690     (cperl-switch-to-doc-buffer)
4691
4692     ;; lookup in the doc
4693     (goto-char (point-min))
4694     (let ((case-fold-search nil))
4695       (list 
4696        (if (re-search-forward regexp (point-max) t)
4697            (save-excursion
4698              (beginning-of-line 1)
4699              (let ((lnstart (point)))
4700                (end-of-line)
4701                (message "%s" (buffer-substring lnstart (point)))))
4702          (if cperl-message-on-help-error
4703              (message "No definition for %s" val)))))))
4704
4705 (defvar cperl-short-docs "Ignore my value"
4706   ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl)
4707   "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5]
4708 ! ...   Logical negation.       
4709 ... != ...      Numeric inequality.
4710 ... !~ ...      Search pattern, substitution, or translation (negated).
4711 $!      In numeric context: errno. In a string context: error string.
4712 $\"     The separator which joins elements of arrays interpolated in strings.
4713 $#      The output format for printed numbers. Initial value is %.20g.
4714 $$      Process number of this script. Changes in the fork()ed child process.
4715 $%      The current page number of the currently selected output channel.
4716
4717         The following variables are always local to the current block:
4718
4719 $1      Match of the 1st set of parentheses in the last match (auto-local).
4720 $2      Match of the 2nd set of parentheses in the last match (auto-local).
4721 $3      Match of the 3rd set of parentheses in the last match (auto-local).
4722 $4      Match of the 4th set of parentheses in the last match (auto-local).
4723 $5      Match of the 5th set of parentheses in the last match (auto-local).
4724 $6      Match of the 6th set of parentheses in the last match (auto-local).
4725 $7      Match of the 7th set of parentheses in the last match (auto-local).
4726 $8      Match of the 8th set of parentheses in the last match (auto-local).
4727 $9      Match of the 9th set of parentheses in the last match (auto-local).
4728 $&      The string matched by the last pattern match (auto-local).
4729 $'      The string after what was matched by the last match (auto-local).
4730 $`      The string before what was matched by the last match (auto-local).
4731
4732 $(      The real gid of this process.
4733 $)      The effective gid of this process.
4734 $*      Deprecated: Set to 1 to do multiline matching within a string.
4735 $+      The last bracket matched by the last search pattern.
4736 $,      The output field separator for the print operator.
4737 $-      The number of lines left on the page.
4738 $.      The current input line number of the last filehandle that was read.
4739 $/      The input record separator, newline by default.
4740 $0      Name of the file containing the perl script being executed. May be set.
4741 $:     String may be broken after these characters to fill ^-lines in a format.
4742 $;      Subscript separator for multi-dim array emulation. Default \"\\034\".
4743 $<      The real uid of this process.
4744 $=      The page length of the current output channel. Default is 60 lines.
4745 $>      The effective uid of this process.
4746 $?      The status returned by the last ``, pipe close or `system'.
4747 $@      The perl error message from the last eval or do @var{EXPR} command.
4748 $ARGV   The name of the current file used with <> .
4749 $[      Deprecated: The index of the first element/char in an array/string.
4750 $\\     The output record separator for the print operator.
4751 $]      The perl version string as displayed with perl -v.
4752 $^      The name of the current top-of-page format.
4753 $^A     The current value of the write() accumulator for format() lines.
4754 $^D     The value of the perl debug (-D) flags.
4755 $^E     Information about the last system error other than that provided by $!.
4756 $^F     The highest system file descriptor, ordinarily 2.
4757 $^H     The current set of syntax checks enabled by `use strict'.
4758 $^I     The value of the in-place edit extension (perl -i option).
4759 $^L     What formats output to perform a formfeed. Default is \f.
4760 $^O     The operating system name under which this copy of Perl was built.
4761 $^P     Internal debugging flag.
4762 $^T     The time the script was started. Used by -A/-M/-C file tests.
4763 $^W     True if warnings are requested (perl -w flag).
4764 $^X     The name under which perl was invoked (argv[0] in C-speech).
4765 $_      The default input and pattern-searching space.
4766 $|      Auto-flush after write/print on the current output channel? Default 0. 
4767 $~      The name of the current report format.
4768 ... % ...       Modulo division.
4769 ... %= ...      Modulo division assignment.
4770 %ENV    Contains the current environment.
4771 %INC    List of files that have been require-d or do-ne.
4772 %SIG    Used to set signal handlers for various signals.
4773 ... & ...       Bitwise and.
4774 ... && ...      Logical and.
4775 ... &&= ...     Logical and assignment.
4776 ... &= ...      Bitwise and assignment.
4777 ... * ...       Multiplication.
4778 ... ** ...      Exponentiation.
4779 *NAME   Glob: all objects refered by NAME. *NAM1 = *NAM2 aliases NAM1 to NAM2.
4780 &NAME(arg0, ...)        Subroutine call. Arguments go to @_.
4781 ... + ...       Addition.               +EXPR   Makes EXPR into scalar context.
4782 ++      Auto-increment (magical on strings).    ++EXPR  EXPR++
4783 ... += ...      Addition assignment.
4784 ,       Comma operator.
4785 ... - ...       Subtraction.
4786 --      Auto-decrement (NOT magical on strings).        --EXPR  EXPR--
4787 ... -= ...      Subtraction assignment.
4788 -A      Access time in days since script started.
4789 -B      File is a non-text (binary) file.
4790 -C      Inode change time in days since script started.
4791 -M      Age in days since script started.
4792 -O      File is owned by real uid.
4793 -R      File is readable by real uid.
4794 -S      File is a socket .
4795 -T      File is a text file.
4796 -W      File is writable by real uid.
4797 -X      File is executable by real uid.
4798 -b      File is a block special file.
4799 -c      File is a character special file.
4800 -d      File is a directory.
4801 -e      File exists .
4802 -f      File is a plain file.
4803 -g      File has setgid bit set.
4804 -k      File has sticky bit set.
4805 -l      File is a symbolic link.
4806 -o      File is owned by effective uid.
4807 -p      File is a named pipe (FIFO).
4808 -r      File is readable by effective uid.
4809 -s      File has non-zero size.
4810 -t      Tests if filehandle (STDIN by default) is opened to a tty.
4811 -u      File has setuid bit set.
4812 -w      File is writable by effective uid.
4813 -x      File is executable by effective uid.
4814 -z      File has zero size.
4815 .       Concatenate strings.
4816 ..      Alternation, also range operator.
4817 .=      Concatenate assignment strings
4818 ... / ...       Division.       /PATTERN/ioxsmg Pattern match
4819 ... /= ...      Division assignment.
4820 /PATTERN/ioxsmg Pattern match.
4821 ... < ...       Numeric less than.      <pattern>       Glob.   See <NAME>, <> as well.
4822 <NAME>  Reads line from filehandle NAME. NAME must be bareword/dollar-bareword.
4823 <pattern>       Glob. (Unless pattern is bareword/dollar-bareword - see <NAME>)
4824 <>      Reads line from union of files in @ARGV (= command line) and STDIN.
4825 ... << ...      Bitwise shift left.     <<      start of HERE-DOCUMENT.
4826 ... <= ...      Numeric less than or equal to.
4827 ... <=> ...     Numeric compare.
4828 ... = ...       Assignment.
4829 ... == ...      Numeric equality.
4830 ... =~ ...      Search pattern, substitution, or translation
4831 ... > ...       Numeric greater than.
4832 ... >= ...      Numeric greater than or equal to.
4833 ... >> ...      Bitwise shift right.
4834 ... >>= ...     Bitwise shift right assignment.
4835 ... ? ... : ... Condition=if-then-else operator.   ?PAT? One-time pattern match.
4836 ?PATTERN?       One-time pattern match.
4837 @ARGV   Command line arguments (not including the command name - see $0).
4838 @INC    List of places to look for perl scripts during do/include/use.
4839 @_      Parameter array for subroutines. Also used by split unless in array context.
4840 \\  Creates reference to what follows, like \$var, or quotes non-\w in strings.
4841 \\0     Octal char, e.g. \\033.
4842 \\E     Case modification terminator. See \\Q, \\L, and \\U.
4843 \\L     Lowercase until \\E . See also \l, lc.
4844 \\U     Upcase until \\E . See also \u, uc.
4845 \\Q     Quote metacharacters until \\E . See also quotemeta.
4846 \\a     Alarm character (octal 007).
4847 \\b     Backspace character (octal 010).
4848 \\c     Control character, e.g. \\c[ .
4849 \\e     Escape character (octal 033).
4850 \\f     Formfeed character (octal 014).
4851 \\l     Lowercase the next character. See also \\L and \\u, lcfirst.
4852 \\n     Newline character (octal 012 on most systems).
4853 \\r     Return character (octal 015 on most systems).
4854 \\t     Tab character (octal 011).
4855 \\u     Upcase the next character. See also \\U and \\l, ucfirst.
4856 \\x     Hex character, e.g. \\x1b.
4857 ... ^ ...       Bitwise exclusive or.
4858 __END__ Ends program source.
4859 __DATA__        Ends program source.
4860 __FILE__        Current (source) filename.
4861 __LINE__        Current line in current source.
4862 __PACKAGE__     Current package.
4863 ARGV    Default multi-file input filehandle. <ARGV> is a synonym for <>.
4864 ARGVOUT Output filehandle with -i flag.
4865 BEGIN { ... }   Immediately executed (during compilation) piece of code.
4866 END { ... }     Pseudo-subroutine executed after the script finishes.
4867 DATA    Input filehandle for what follows after __END__ or __DATA__.
4868 accept(NEWSOCKET,GENERICSOCKET)
4869 alarm(SECONDS)
4870 atan2(X,Y)
4871 bind(SOCKET,NAME)
4872 binmode(FILEHANDLE)
4873 caller[(LEVEL)]
4874 chdir(EXPR)
4875 chmod(LIST)
4876 chop[(LIST|VAR)]
4877 chown(LIST)
4878 chroot(FILENAME)
4879 close(FILEHANDLE)
4880 closedir(DIRHANDLE)
4881 ... cmp ...     String compare.
4882 connect(SOCKET,NAME)
4883 continue of { block } continue { block }. Is executed after `next' or at end.
4884 cos(EXPR)
4885 crypt(PLAINTEXT,SALT)
4886 dbmclose(%HASH)
4887 dbmopen(%HASH,DBNAME,MODE)
4888 defined(EXPR)
4889 delete($HASH{KEY})
4890 die(LIST)
4891 do { ... }|SUBR while|until EXPR        executes at least once
4892 do(EXPR|SUBR([LIST]))   (with while|until executes at least once)
4893 dump LABEL
4894 each(%HASH)
4895 endgrent
4896 endhostent
4897 endnetent
4898 endprotoent
4899 endpwent
4900 endservent
4901 eof[([FILEHANDLE])]
4902 ... eq ...      String equality.
4903 eval(EXPR) or eval { BLOCK }
4904 exec(LIST)
4905 exit(EXPR)
4906 exp(EXPR)
4907 fcntl(FILEHANDLE,FUNCTION,SCALAR)
4908 fileno(FILEHANDLE)
4909 flock(FILEHANDLE,OPERATION)
4910 for (EXPR;EXPR;EXPR) { ... }
4911 foreach [VAR] (@ARRAY) { ... }
4912 fork
4913 ... ge ...      String greater than or equal.
4914 getc[(FILEHANDLE)]
4915 getgrent
4916 getgrgid(GID)
4917 getgrnam(NAME)
4918 gethostbyaddr(ADDR,ADDRTYPE)
4919 gethostbyname(NAME)
4920 gethostent
4921 getlogin
4922 getnetbyaddr(ADDR,ADDRTYPE)
4923 getnetbyname(NAME)
4924 getnetent
4925 getpeername(SOCKET)
4926 getpgrp(PID)
4927 getppid
4928 getpriority(WHICH,WHO)
4929 getprotobyname(NAME)
4930 getprotobynumber(NUMBER)
4931 getprotoent
4932 getpwent
4933 getpwnam(NAME)
4934 getpwuid(UID)
4935 getservbyname(NAME,PROTO)
4936 getservbyport(PORT,PROTO)
4937 getservent
4938 getsockname(SOCKET)
4939 getsockopt(SOCKET,LEVEL,OPTNAME)
4940 gmtime(EXPR)
4941 goto LABEL
4942 grep(EXPR,LIST)
4943 ... gt ...      String greater than.
4944 hex(EXPR)
4945 if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXPR if EXPR
4946 index(STR,SUBSTR[,OFFSET])
4947 int(EXPR)
4948 ioctl(FILEHANDLE,FUNCTION,SCALAR)
4949 join(EXPR,LIST)
4950 keys(%HASH)
4951 kill(LIST)
4952 last [LABEL]
4953 ... le ...      String less than or equal.
4954 length(EXPR)
4955 link(OLDFILE,NEWFILE)
4956 listen(SOCKET,QUEUESIZE)
4957 local(LIST)
4958 localtime(EXPR)
4959 log(EXPR)
4960 lstat(EXPR|FILEHANDLE|VAR)
4961 ... lt ...      String less than.
4962 m/PATTERN/iogsmx
4963 mkdir(FILENAME,MODE)
4964 msgctl(ID,CMD,ARG)
4965 msgget(KEY,FLAGS)
4966 msgrcv(ID,VAR,SIZE,TYPE.FLAGS)
4967 msgsnd(ID,MSG,FLAGS)
4968 my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, or %HASH).
4969 ... ne ...      String inequality.
4970 next [LABEL]
4971 oct(EXPR)
4972 open(FILEHANDLE[,EXPR])
4973 opendir(DIRHANDLE,EXPR)
4974 ord(EXPR)       ASCII value of the first char of the string.
4975 pack(TEMPLATE,LIST)
4976 package NAME    Introduces package context.
4977 pipe(READHANDLE,WRITEHANDLE)    Create a pair of filehandles on ends of a pipe.
4978 pop(ARRAY)
4979 print [FILEHANDLE] [(LIST)]
4980 printf [FILEHANDLE] (FORMAT,LIST)
4981 push(ARRAY,LIST)
4982 q/STRING/       Synonym for 'STRING'
4983 qq/STRING/      Synonym for \"STRING\"
4984 qx/STRING/      Synonym for `STRING`
4985 rand[(EXPR)]
4986 read(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
4987 readdir(DIRHANDLE)
4988 readlink(EXPR)
4989 recv(SOCKET,SCALAR,LEN,FLAGS)
4990 redo [LABEL]
4991 rename(OLDNAME,NEWNAME)
4992 require [FILENAME | PERL_VERSION]
4993 reset[(EXPR)]
4994 return(LIST)
4995 reverse(LIST)
4996 rewinddir(DIRHANDLE)
4997 rindex(STR,SUBSTR[,OFFSET])
4998 rmdir(FILENAME)
4999 s/PATTERN/REPLACEMENT/gieoxsm
5000 scalar(EXPR)
5001 seek(FILEHANDLE,POSITION,WHENCE)
5002 seekdir(DIRHANDLE,POS)
5003 select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT)
5004 semctl(ID,SEMNUM,CMD,ARG)
5005 semget(KEY,NSEMS,SIZE,FLAGS)
5006 semop(KEY,...)
5007 send(SOCKET,MSG,FLAGS[,TO])
5008 setgrent
5009 sethostent(STAYOPEN)
5010 setnetent(STAYOPEN)
5011 setpgrp(PID,PGRP)
5012 setpriority(WHICH,WHO,PRIORITY)
5013 setprotoent(STAYOPEN)
5014 setpwent
5015 setservent(STAYOPEN)
5016 setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
5017 shift[(ARRAY)]
5018 shmctl(ID,CMD,ARG)
5019 shmget(KEY,SIZE,FLAGS)
5020 shmread(ID,VAR,POS,SIZE)
5021 shmwrite(ID,STRING,POS,SIZE)
5022 shutdown(SOCKET,HOW)
5023 sin(EXPR)
5024 sleep[(EXPR)]
5025 socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
5026 socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
5027 sort [SUBROUTINE] (LIST)
5028 splice(ARRAY,OFFSET[,LENGTH[,LIST]])
5029 split[(/PATTERN/[,EXPR[,LIMIT]])]
5030 sprintf(FORMAT,LIST)
5031 sqrt(EXPR)
5032 srand(EXPR)
5033 stat(EXPR|FILEHANDLE|VAR)
5034 study[(SCALAR)]
5035 sub [NAME [(format)]] { BODY }  sub NAME [(format)];    sub [(format)] {...}
5036 substr(EXPR,OFFSET[,LEN])
5037 symlink(OLDFILE,NEWFILE)
5038 syscall(LIST)
5039 sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
5040 system(LIST)
5041 syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
5042 tell[(FILEHANDLE)]
5043 telldir(DIRHANDLE)
5044 time
5045 times
5046 tr/SEARCHLIST/REPLACEMENTLIST/cds
5047 truncate(FILE|EXPR,LENGTH)
5048 umask[(EXPR)]
5049 undef[(EXPR)]
5050 unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR
5051 unlink(LIST)
5052 unpack(TEMPLATE,EXPR)
5053 unshift(ARRAY,LIST)
5054 until (EXPR) { ... }                                    EXPR until EXPR
5055 utime(LIST)
5056 values(%HASH)
5057 vec(EXPR,OFFSET,BITS)
5058 wait
5059 waitpid(PID,FLAGS)
5060 wantarray       Returns true if the sub/eval is called in list context.
5061 warn(LIST)
5062 while  (EXPR) { ... }                                   EXPR while EXPR
5063 write[(EXPR|FILEHANDLE)]
5064 ... x ...       Repeat string or array.
5065 x= ...  Repetition assignment.
5066 y/SEARCHLIST/REPLACEMENTLIST/
5067 ... | ...       Bitwise or.
5068 ... || ...      Logical or.
5069 ~ ...           Unary bitwise complement.
5070 #!      OS interpreter indicator. If contains `perl', used for options, and -x.
5071 AUTOLOAD {...}  Shorthand for `sub AUTOLOAD {...}'.
5072 CORE::          Prefix to access builtin function if imported sub obscures it.
5073 SUPER::         Prefix to lookup for a method in @ISA classes.
5074 DESTROY         Shorthand for `sub DESTROY {...}'.
5075 ... EQ ...      Obsolete synonym of `eq'.
5076 ... GE ...      Obsolete synonym of `ge'.
5077 ... GT ...      Obsolete synonym of `gt'.
5078 ... LE ...      Obsolete synonym of `le'.
5079 ... LT ...      Obsolete synonym of `lt'.
5080 ... NE ...      Obsolete synonym of `ne'.
5081 abs [ EXPR ]    absolute value
5082 ... and ...             Low-precedence synonym for &&.
5083 bless REFERENCE [, PACKAGE]     Makes reference into an object of a package.
5084 chomp [LIST]    Strips $/ off LIST/$_. Returns count. Special if $/ eq ''!
5085 chr             Converts a number to char with the same ordinal.
5086 else            Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
5087 elsif           Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
5088 exists  $HASH{KEY}      True if the key exists.
5089 format [NAME] =  Start of output format. Ended by a single dot (.) on a line.
5090 formline PICTURE, LIST  Backdoor into \"format\" processing.
5091 glob EXPR       Synonym of <EXPR>.
5092 lc [ EXPR ]     Returns lowercased EXPR.
5093 lcfirst [ EXPR ]        Returns EXPR with lower-cased first letter.
5094 map EXPR, LIST  or map {BLOCK} LIST     Applies EXPR/BLOCK to elts of LIST.
5095 no PACKAGE [SYMBOL1, ...]  Partial reverse for `use'. Runs `unimport' method.
5096 not ...         Low-precedence synonym for ! - negation.
5097 ... or ...              Low-precedence synonym for ||.
5098 pos STRING    Set/Get end-position of the last match over this string, see \\G.
5099 quotemeta [ EXPR ]      Quote regexp metacharacters.
5100 qw/WORD1 .../           Synonym of split('', 'WORD1 ...')
5101 readline FH     Synonym of <FH>.
5102 readpipe CMD    Synonym of `CMD`.
5103 ref [ EXPR ]    Type of EXPR when dereferenced.
5104 sysopen FH, FILENAME, MODE [, PERM]     (MODE is numeric, see Fcntl.)
5105 tie VAR, PACKAGE, LIST  Hide an object behind a simple Perl variable.
5106 tied            Returns internal object for a tied data.
5107 uc [ EXPR ]     Returns upcased EXPR.
5108 ucfirst [ EXPR ]        Returns EXPR with upcased first letter.
5109 untie VAR       Unlink an object from a simple Perl variable.
5110 use PACKAGE [SYMBOL1, ...]  Compile-time `require' with consequent `import'.
5111 ... xor ...             Low-precedence synonym for exclusive or.
5112 prototype \&SUB Returns prototype of the function given a reference.
5113 =head1          Top-level heading.
5114 =head2          Second-level heading.
5115 =head3          Third-level heading (is there such?).
5116 =over [ NUMBER ]        Start list.
5117 =item [ TITLE ]         Start new item in the list.
5118 =back           End list.
5119 =cut            Switch from POD to Perl.
5120 =pod            Switch from Perl to POD.
5121 ")
5122
5123 (defun cperl-switch-to-doc-buffer ()
5124   "Go to the perl documentation buffer and insert the documentation."
5125   (interactive)
5126   (let ((buf (get-buffer-create cperl-doc-buffer)))
5127     (if (interactive-p)
5128         (switch-to-buffer-other-window buf)
5129       (set-buffer buf))
5130     (if (= (buffer-size) 0)
5131         (progn
5132           (insert (documentation-property 'cperl-short-docs
5133                                           'variable-documentation))
5134           (setq buffer-read-only t)))))
5135
5136 (defun cperl-beautify-regexp-piece (b e embed)
5137   ;; b is before the starting delimiter, e before the ending
5138   ;; e should be a marker, may be changed, but remains "correct".
5139   (let (s c tmp (m (make-marker)) (m1 (make-marker)) c1 spaces inline)
5140     (if (not embed)
5141         (goto-char (1+ b))
5142       (goto-char b)
5143       (cond ((looking-at "(\\?\\\\#")   ; badly commented (?#)
5144              (forward-char 2)
5145              (delete-char 1)
5146              (forward-char 1))
5147             ((looking-at "(\\?[^a-zA-Z]")
5148              (forward-char 3))
5149             ((looking-at "(\\?")        ; (?i)
5150              (forward-char 2))
5151             (t
5152              (forward-char 1))))
5153     (setq c (1- (current-column))
5154           c1 (+ c (or cperl-regexp-indent-step cperl-indent-level)))
5155     (or (looking-at "[ \t]*[\n#]")
5156         (progn
5157           (insert "\n")))
5158     (goto-char e)
5159     (beginning-of-line)
5160     (if (re-search-forward "[^ \t]" e t)
5161         (progn
5162           (goto-char e)
5163           (insert "\n")
5164           (indent-to-column c)
5165           (set-marker e (point))))
5166     (goto-char b)
5167     (end-of-line 2)
5168     (while (< (point) (marker-position e))
5169       (beginning-of-line)
5170       (setq s (point)
5171             inline t)
5172       (skip-chars-forward " \t")
5173       (delete-region s (point))
5174       (indent-to-column c1)
5175       (while (and
5176               inline
5177               (looking-at 
5178                (concat "\\([a-zA-Z0-9]+[^*+{?]\\)" ; 1
5179                        "\\|"
5180                        "\\$\\([a-zA-Z0-9_]+\\([[{]\\)?\\|[^\n \t)|]\\)" ; 2 3
5181                        "\\|"
5182                        "[$^]"
5183                        "\\|"
5184                        "\\(\\\\.\\|[^][()#|*+?\n]\\)\\([*+{?]\\??\\)?" ; 4 5
5185                        "\\|"
5186                        "\\(\\[\\)"      ; 6
5187                        "\\|"
5188                        "\\((\\(\\?\\)?\\)" ; 7 8
5189                        "\\|"
5190                        "\\(|\\)"        ; 9
5191                        )))
5192         (goto-char (match-end 0))
5193         (setq spaces t)
5194         (cond ((match-beginning 1)      ; Alphanum word + junk
5195                (forward-char -1))
5196               ((or (match-beginning 3)  ; $ab[12]
5197                    (and (match-beginning 5) ; X* X+ X{2,3}
5198                         (eq (preceding-char) ?\{)))
5199                (forward-char -1)
5200                (forward-sexp 1))
5201               ((match-beginning 6)      ; []
5202                (setq tmp (point))
5203                (if (looking-at "\\^?\\]")
5204                    (goto-char (match-end 0)))
5205                (or (re-search-forward "\\]\\([*+{?]\\)?" e t)
5206                    (progn
5207                      (goto-char (1- tmp))
5208                      (error "[]-group not terminated")))
5209                (if (not (eq (preceding-char) ?\{)) nil
5210                  (forward-char -1)
5211                  (forward-sexp 1)))
5212               ((match-beginning 7)      ; ()
5213                (goto-char (match-beginning 0))
5214                (or (eq (current-column) c1)
5215                    (progn
5216                      (insert "\n")
5217                      (indent-to-column c1)))
5218                (setq tmp (point))
5219                (forward-sexp 1)
5220                ;;              (or (forward-sexp 1)
5221                ;;                  (progn
5222                ;;                    (goto-char tmp)
5223                ;;                    (error "()-group not terminated")))
5224                (set-marker m (1- (point)))
5225                (set-marker m1 (point))
5226                (cperl-beautify-regexp-piece tmp m t)
5227                (goto-char m1)
5228                (cond ((looking-at "[*+?]\\??")
5229                       (goto-char (match-end 0)))
5230                      ((eq (following-char) ?\{)
5231                       (forward-sexp 1)
5232                       (if (eq (following-char) ?\?)
5233                           (forward-char))))
5234                (skip-chars-forward " \t")
5235                (setq spaces nil)
5236                (if (looking-at "[#\n]")
5237                    (beginning-of-line 2)
5238                  (insert "\n"))
5239                (end-of-line)
5240                (setq inline nil))
5241               ((match-beginning 9)      ; |
5242                (forward-char -1)
5243                (setq tmp (point))
5244                (beginning-of-line)
5245                (if (re-search-forward "[^ \t]" tmp t)
5246                    (progn
5247                      (goto-char tmp)
5248                      (insert "\n"))
5249                  ;; first at line
5250                  (delete-region (point) tmp))
5251                (indent-to-column c)
5252                (forward-char 1)
5253                (skip-chars-forward " \t")
5254                (setq spaces nil)
5255                (if (looking-at "[#\n]")
5256                    (beginning-of-line 2)
5257                  (insert "\n"))
5258                (end-of-line)
5259                (setq inline nil)))
5260         (or (looking-at "[ \t\n]")
5261             (not spaces)
5262             (insert " "))
5263         (skip-chars-forward " \t"))
5264         (or (looking-at "[#\n]")
5265             (error "unknown code in a regexp"))
5266         (and inline (end-of-line 2)))
5267   ))
5268
5269 (defun cperl-beautify-regexp ()
5270   "do it. (Experimental, may change semantics, recheck afterwards.)
5271 We suppose that the regexp is scanned already."
5272   (interactive)
5273   (or cperl-use-syntax-table-text-property
5274       (error "I need to have regex marked!"))
5275   ;; Find the start
5276   (re-search-backward "\\s|")           ; Assume it is scanned already.
5277   ;;(forward-char 1)
5278   (let ((b (point)) (e (make-marker)) have-x delim (c (current-column))
5279         (sub-p (eq (preceding-char) ?s)) s)
5280     (forward-sexp 1)
5281     (set-marker e (1- (point)))
5282     (setq delim (preceding-char))
5283     (if (and sub-p (eq delim (char-after (- (point) 2))))
5284         (error "Possible s/blah// - do not know how to deal with"))
5285     (if sub-p (forward-sexp 1))
5286     (if (looking-at "\\sw*x") 
5287         (setq have-x t)
5288       (insert "x"))
5289     ;; Protect fragile " ", "#"
5290     (if have-x nil
5291         (goto-char (1+ b))
5292         (while (re-search-forward "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*[ \t\n#]" e t) ; Need to include (?#) too?
5293           (forward-char -1)
5294           (insert "\\")
5295           (forward-char 1)))
5296     (cperl-beautify-regexp-piece b e nil)))
5297
5298 (if (fboundp 'run-with-idle-timer)
5299     (progn
5300       (defvar cperl-help-shown nil
5301         "Non-nil means that the help was already shown now.")
5302
5303       (defvar cperl-lazy-installed nil
5304         "Non-nil means that the lazy-help handlers are installed now.")
5305
5306       (defun cperl-lazy-install ()
5307         (interactive)
5308         (make-variable-buffer-local 'cperl-help-shown)
5309         (if (and (cperl-val 'cperl-lazy-help-time)
5310                  (not cperl-lazy-installed))
5311             (progn
5312               (add-hook 'post-command-hook 'cperl-lazy-hook)
5313               (run-with-idle-timer 
5314                (cperl-val 'cperl-lazy-help-time 1000000 5) 
5315                t 
5316                'cperl-get-help-defer)
5317               (setq cperl-lazy-installed t))))
5318
5319       (defun cperl-lazy-unstall ()
5320         (interactive)
5321         (remove-hook 'post-command-hook 'cperl-lazy-hook)
5322         (cancel-function-timers 'cperl-get-help-defer)
5323         (setq cperl-lazy-installed nil))
5324
5325       (defun cperl-lazy-hook ()
5326         (setq cperl-help-shown nil))
5327
5328       (defun cperl-get-help-defer ()
5329         (if (not (eq major-mode 'perl-mode)) nil
5330           (let ((cperl-message-on-help-error nil) (cperl-help-from-timer t))
5331             (cperl-get-help)
5332             (setq cperl-help-shown t))))
5333       (cperl-lazy-install)))
5334
5335 (provide 'cperl-mode)