applied patch, with tweak suggested by Michael Parker
[p5sagit/p5-mst-13.2.git] / emacs / cperl-mode.el
1 ;;; cperl-mode.el --- Perl code editing commands for Emacs
2
3 ;;;; The following message is relative to GNU version of the module:
4
5 ;; Copyright (C) 1985, 86, 87, 91, 92, 93, 94, 95, 96, 1997
6 ;;     Free Software Foundation, Inc.
7
8 ;; Author: Ilya Zakharevich and Bob Olson
9 ;; Maintainer: Ilya Zakharevich <ilya@math.ohio-state.edu>
10 ;; Keywords: languages, Perl
11
12 ;; This file is part of GNU Emacs.
13
14 ;;; This code started from the following message of long time ago
15 ;;; (IZ), but Bob does not maintain this mode any more:
16
17 ;;; From: olson@mcs.anl.gov (Bob Olson)
18 ;;; Newsgroups: comp.lang.perl
19 ;;; Subject: cperl-mode: Another perl mode for Gnuemacs
20 ;;; Date: 14 Aug 91 15:20:01 GMT
21
22 ;; Copyright (C) Ilya Zakharevich and Bob Olson
23
24 ;; This file may be distributed
25 ;; either under the same terms as GNU Emacs, or under the same terms
26 ;; as Perl. You should have received a copy of Perl Artistic license
27 ;; along with the Perl distribution.
28
29 ;; GNU Emacs is free software; you can redistribute it and/or modify
30 ;; it under the terms of the GNU General Public License as published by
31 ;; the Free Software Foundation; either version 2, or (at your option)
32 ;; any later version.
33
34 ;; GNU Emacs is distributed in the hope that it will be useful,
35 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
36 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37 ;; GNU General Public License for more details.
38
39 ;; You should have received a copy of the GNU General Public License
40 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
41 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
42 ;; Boston, MA 02111-1307, USA.
43
44 ;;; Corrections made by Ilya Zakharevich ilya@math.mps.ohio-state.edu
45 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
46
47 ;;; Commentary:
48
49 ;; $Id: cperl-mode.el 3.14 1998/07/03 00:32:02 vera Exp vera $
50
51 ;;; Before (future?) RMS Emacs 20.3: To use this mode put the following into
52 ;;; your .emacs file:
53
54 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
55
56 ;;; You can either fine-tune the bells and whistles of this mode or
57 ;;; bulk enable them by putting
58
59 ;; (setq cperl-hairy t)
60
61 ;;; in your .emacs file.  (Emacs rulers do not consider it politically
62 ;;; correct to make whistles enabled by default.)
63
64 ;;; DO NOT FORGET to read micro-docs (available from `Perl' menu)   <<<<<<
65 ;;; or as help on variables `cperl-tips', `cperl-problems',         <<<<<<
66 ;;; `cperl-non-problems', `cperl-praise', `cperl-speed'.            <<<<<<
67
68 ;;; Additional useful commands to put into your .emacs file (before
69 ;;; (future?) RMS Emacs 20.3):
70
71 ;; (setq auto-mode-alist
72 ;;      (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
73 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
74 ;;                                      '(("miniperl" . perl-mode))))
75
76 ;;; The mode information (on C-h m) provides some customization help.
77 ;;; If you use font-lock feature of this mode, it is advisable to use
78 ;;; either lazy-lock-mode or fast-lock-mode.  I prefer lazy-lock.
79
80 ;;; Faces used now: three faces for first-class and second-class keywords
81 ;;; and control flow words, one for each: comments, string, labels,
82 ;;; functions definitions and packages, arrays, hashes, and variable
83 ;;; definitions.  If you do not see all these faces, your font-lock does
84 ;;; not define them, so you need to define them manually.  Maybe you have 
85 ;;; an obsolete font-lock from 19.28 or earlier.  Upgrade.
86
87 ;;; If you have a grayscale monitor, and do not have the variable
88 ;;; font-lock-display-type bound to 'grayscale, insert 
89
90 ;;; (setq font-lock-display-type 'grayscale)
91
92 ;;; into your .emacs file (this is relevant before RMS Emacs 20).
93
94 ;;;; This mode supports font-lock, imenu and mode-compile.  In the
95 ;;;; hairy version font-lock is on, but you should activate imenu
96 ;;;; yourself (note that mode-compile is not standard yet).  Well, you
97 ;;;; can use imenu from keyboard anyway (M-x imenu), but it is better
98 ;;;; to bind it like that:
99
100 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
101
102 ;;; In fact the version of font-lock that this version supports can be
103 ;;; much newer than the version you actually have. This means that a
104 ;;; lot of faces can be set up, but are not visible on your screen
105 ;;; since the coloring rules for this faces are not defined.
106
107 ;;; Updates: ========================================
108
109 ;;; Made less hairy by default: parentheses not electric, 
110 ;;; linefeed not magic. Bug with abbrev-mode corrected.
111
112 ;;;; After 1.4:
113 ;;;  Better indentation:
114 ;;;  subs inside braces should work now, 
115 ;;;  Toplevel braces obey customization.
116 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
117 ;;;  moves cursor to a correct place.
118 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-( 
119 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
120 ;;;  Minor documentation fixes.
121 ;;;  Imenu understands packages as prefixes (including nested).
122 ;;;  Hairy options can be switched off one-by-one by setting to null.
123 ;;;  Names of functions and variables changed to conform to `cperl-' style.
124
125 ;;;; After 1.5:
126 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
127 ;;;  `cperl-indent-region' done (slow :-()).
128 ;;;  `cperl-fill-paragraph' done.
129 ;;;  Better package support for `imenu'.
130 ;;;  Progress indicator for indentation (with `imenu' loaded).
131 ;;;  `Cperl-set' was busted, now setting the individual hairy option 
132 ;;;     should be better.
133
134 ;;;; After 1.6:
135 ;;; `cperl-set-style' done.
136 ;;; `cperl-check-syntax' done.
137 ;;; Menu done.
138 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
139 ;;; Bugs with `cperl-auto-newline' corrected.
140 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation 
141 ;;; like $hash{.
142
143 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
144 ;;; - use `next-command-event', if `next-command-events' does not exist
145 ;;; - use `find-face' as def. of `is-face'
146 ;;; - corrected def. of `x-color-defined-p'
147 ;;; - added const defs for font-lock-comment-face,
148 ;;;   font-lock-keyword-face and font-lock-function-name-face
149 ;;; - added def. of font-lock-variable-name-face
150 ;;; - added (require 'easymenu) inside an `eval-when-compile'
151 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
152 ;;;   `define-key's
153 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
154 ;;; Todo (at least):
155 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
156 ;;;   for portable code?
157 ;;; - should `cperl-mode' do a 
158 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
159 ;;;   or should this be left to the user's `cperl-mode-hook'?
160
161 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
162 ;;; Some bugs under XEmacs introduced by the correction corrected.
163
164 ;;; Some more can remain since there are two many different variants. 
165 ;;; Please feedback!
166
167 ;;; We do not support fontification of arrays and hashes under 
168 ;;; obsolete font-lock any more. Upgrade.
169
170 ;;;; after 1.8 Minor bug with parentheses.
171 ;;;; after 1.9 Improvements from Joe Marzot.
172 ;;;; after 1.10
173 ;;;  Does not need easymenu to compile under XEmacs.
174 ;;;  `vc-insert-headers' should work better.
175 ;;;  Should work with 19.29 and 19.12.
176 ;;;  Small improvements to fontification.
177 ;;;  Expansion of keywords does not depend on C-? being backspace.
178
179 ;;; after 1.10+
180 ;;; 19.29 and 19.12 supported.
181 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
182 ;;; Support for font-lock-extra.el.
183
184 ;;;; After 1.11:
185 ;;; Tools submenu.
186 ;;; Support for perl5-info.
187 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
188 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
189 ;;; Fontifies `require a if b;', __DATA__.
190 ;;; Arglist for auto-fill-mode was incorrect.
191
192 ;;;; After 1.12:
193 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions 
194 ;;; vertically.
195 ;;; `cperl-do-auto-fill' updated for 19.29 style.
196 ;;; `cperl-info-on-command' now has a default.
197 ;;; Workaround for broken C-h on XEmacs.
198 ;;; VC strings escaped.
199 ;;; C-h f now may prompt for function name instead of going on,
200 ;;; controlled by `cperl-info-on-command-no-prompt'.
201
202 ;;;; After 1.13:
203 ;;; Msb buffer list includes perl files
204 ;;; Indent-for-comment uses indent-to
205 ;;; Can write tag files using etags.
206
207 ;;;; After 1.14:
208 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
209 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
210 ;;; Bug with auto-filling comments started with "##" corrected.
211
212 ;;;; Very slow now: on DB::DB 0.91, 486/66:
213
214 ;;;Function Name                             Call Count  Elapsed Time  Average Time
215 ;;;========================================  ==========  ============  ============
216 ;;;cperl-block-p                             469         3.7799999999  0.0080597014
217 ;;;cperl-get-state                           505         163.39000000  0.3235445544
218 ;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
219 ;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
220 ;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
221 ;;;cperl-indent-line                         505         172.88000000  0.3423366336
222 ;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
223 ;;;cperl-indent-exp                          1           177.97000000  177.97000000
224 ;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
225 ;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
226 ;;;cperl-indent-region                       1           177.94000000  177.94000000
227
228 ;;;; After 1.15:
229 ;;; Takes into account white space after opening parentheses during indent.
230 ;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
231 ;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
232 ;;; for indentation so far.
233 ;;; Fontification updated to 19.30 style. 
234 ;;; The change 19.29->30 did not add all the required functionality,
235 ;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
236 ;;;       ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
237
238 ;;;; After 1.16:
239 ;;;       else # comment
240 ;;;    recognized as a start of a block.
241 ;;;  Two different font-lock-levels provided.
242 ;;;  `cperl-pod-head-face' introduced. Used for highlighting.
243 ;;;  `imenu' marks pods, +Packages moved to the head. 
244
245 ;;;; After 1.17:
246 ;;;  Scan for pods highlights here-docs too.
247 ;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
248 ;;;  Only one here-doc-tag per line is supported, and one in comment
249 ;;;  or a string may break fontification.
250 ;;;  POD headers were supposed to fill one line only.
251
252 ;;;; After 1.18:
253 ;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme 
254 ;;;    may  break under XEmacs.
255 ;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
256 ;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
257 ;;;    compatibility with older lazy-lock.el) (older one overfontifies
258 ;;;    something nevertheless :-().
259 ;;;  Will not indent something inside pod and here-documents.
260 ;;;  Fontifies the package name after import/no/bootstrap.
261 ;;;  Added new entry to menu with meta-info about the mode.
262
263 ;;;; After 1.19:
264 ;;;  Prefontification works much better with 19.29. Should be checked
265 ;;;   with 19.30 as well.
266 ;;;  Some misprints in docs corrected.
267 ;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
268 ;;;  Now the pod search is much stricter, so it can help you to find
269 ;;;    pod sections which are broken because of whitespace before =blah
270 ;;;    - just observe the fontification.
271
272 ;;;; After 1.20
273 ;;;  Anonymous subs are indented with respect to the level of
274 ;;;    indentation of `sub' now.
275 ;;;  {} is recognized as hash after `bless' and `return'.
276 ;;;  Anonymous subs are split by `cperl-linefeed' as well.
277 ;;;  Electric parens embrace a region if present.
278 ;;;  To make `cperl-auto-newline' useful,
279 ;;;    `cperl-auto-newline-after-colon' is introduced.
280 ;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
281 ;;;  `cperl-electric-parens-string'.
282 ;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
283 ;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
284 ;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
285 ;;;  Beginning-of-defun-regexp was not anchored.
286
287 ;;;; After 1.21
288 ;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
289 ;;;    after ")".
290 ;;;  {} is recognized as expression after `tr' and friends.
291
292 ;;;; After 1.22
293 ;;;  Entry Hierarchy added to imenu. Very primitive so far.
294 ;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
295 ;;;  Writes its own TAGS files.
296 ;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
297 ;;;  19.31: Problems with scan for PODs corrected.
298 ;;;  First POD header correctly fontified.
299 ;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
300 ;;;  Apparently it makes a lot of hierarchy code obsolete...
301
302 ;;;; After 1.23
303 ;;;  Tags filler now scans *.xs as well.
304 ;;;  The info from *.xs scan is used by the hierarchy viewer.
305 ;;;  Hierarchy viewer documented.
306 ;;;  Bug in 19.31 imenu documented.
307
308 ;;;; After 1.24
309 ;;;  New location for info-files mentioned,
310 ;;;  Electric-; should work better.
311 ;;;  Minor bugs with POD marking.
312
313 ;;;; After 1.25 (probably not...)
314 ;;;  `cperl-info-page' introduced.  
315 ;;;  To make `uncomment-region' working, `comment-region' would
316 ;;;  not insert extra space.
317 ;;;  Here documents delimiters better recognized 
318 ;;;  (empty one, and non-alphanums in quotes handled). May be wrong with 1<<14?
319 ;;;  `cperl-db' added, used in menu.
320 ;;;  imenu scan removes text-properties, for better debugging
321 ;;;    - but the bug is in 19.31 imenu.
322 ;;;  formats highlighted by font-lock and prescan, embedded comments
323 ;;;  are not treated.
324 ;;;  POD/friends scan merged in one pass.
325 ;;;  Syntax class is not used for analyzing the code, only char-syntax
326 ;;;  may be checked against _ or'ed with w.
327 ;;;  Syntax class of `:' changed to be _.
328 ;;;  `cperl-find-bad-style' added.
329
330 ;;;; After 1.25
331 ;;;  When search for here-documents, we ignore commented << in simplest cases.
332 ;;;  `cperl-get-help' added, available on C-h v and from menu.
333 ;;;  Auto-help added. Default with `cperl-hairy', switchable on/off
334 ;;;   with startup variable `cperl-lazy-help-time' and from
335 ;;;   menu. Requires `run-with-idle-timer'.
336 ;;;  Highlighting of @abc{@efg} was wrong - interchanged two regexps.
337
338 ;;;; After 1.27
339 ;;;  Indentation: At toplevel after a label - fixed.
340 ;;;  1.27 was put to archives in binary mode ===> DOSish :-(
341
342 ;;;; After 1.28
343 ;;;  Thanks to Martin Buchholz <mrb@Eng.Sun.COM>: misprints in
344 ;;;  comments and docstrings corrected, XEmacs support cleaned up.
345 ;;;  The closing parenths would enclose the region into matching
346 ;;;  parens under the same conditions as the opening ones.
347 ;;;  Minor updates to `cperl-short-docs'.
348 ;;;  Will not consider <<= as start of here-doc.
349
350 ;;;; After 1.29
351 ;;;  Added an extra advice to look into Micro-docs. ;-).
352 ;;;  Enclosing of region when you press a closing parenth is regulated by
353 ;;;  `cperl-electric-parens-string'.
354 ;;;  Minor updates to `cperl-short-docs'.
355 ;;;  `initialize-new-tags-table' called only if present (Does this help
356 ;;;     with generation of tags under XEmacs?).
357 ;;;  When creating/updating tag files, new info is written at the old place,
358 ;;;     or at the end (is this a wanted behaviour? I need this in perl build directory).
359
360 ;;;; After 1.30
361 ;;;  All the keywords from keywords.pl included (maybe with dummy explanation).
362 ;;;  No auto-help inside strings, comment, here-docs, formats, and pods.
363 ;;;  Shrinkwrapping of info, regulated by `cperl-max-help-size',
364 ;;;  `cperl-shrink-wrap-info-frame'.
365 ;;;  Info on variables as well.
366 ;;;  Recognision of HERE-DOCS improved yet more.
367 ;;;  Autonewline works on `}' without warnings.
368 ;;;  Autohelp works again on $_[0].
369
370 ;;;; After 1.31
371 ;;;  perl-descr.el found its author - hi, Johan!
372 ;;;  Some support for correct indent after here-docs and friends (may
373 ;;;  be superseeded by eminent change to Emacs internals).
374 ;;;  Should work with older Emaxen as well ( `-style stuff removed).
375
376 ;;;; After 1.32
377
378 ;;;  Started to add support for `syntax-table' property (should work
379 ;;;  with patched Emaxen), controlled by
380 ;;;  `cperl-use-syntax-table-text-property'. Currently recognized:
381 ;;;    All quote-like operators: m, s, y, tr, qq, qw, qx, q,
382 ;;;    // in most frequent context: 
383 ;;;          after block or
384 ;;;                    ~ { ( = | & + - * ! , ;
385 ;;;          or 
386 ;;;                    while if unless until and or not xor split grep map
387 ;;;    Here-documents, formats, PODs, 
388 ;;;    ${...}
389 ;;;    'abc$'
390 ;;;    sub a ($); sub a ($) {}
391 ;;;  (provide 'cperl-mode) was missing!
392 ;;;  `cperl-after-expr-p' is now much smarter after `}'.
393 ;;;  `cperl-praise' added to mini-docs.
394 ;;;  Utilities try to support subs-with-prototypes.
395
396 ;;;; After 1.32.1
397 ;;;  `cperl-after-expr-p' is now much smarter after "() {}" and "word {}":
398 ;;;     if word is "else, map, grep".
399 ;;;  Updated for new values of syntax-table constants.
400 ;;;  Uses `help-char' (at last!) (disabled, does not work?!)
401 ;;;  A couple of regexps where missing _ in character classes.
402 ;;;  -s could be considered as start of regexp, 1../blah/ was not,
403 ;;;  as was not /blah/ at start of file.
404
405 ;;;; After 1.32.2
406 ;;;  "\C-hv" was wrongly "\C-hf"
407 ;;;  C-hv was not working on `[index()]' because of [] in skip-chars-*.
408 ;;;  `__PACKAGE__' supported.
409 ;;;  Thanks for Greg Badros: `cperl-lazy-unstall' is more complete,
410 ;;;  `cperl-get-help' is made compatible with `query-replace'.
411
412 ;;;; As of Apr 15, development version of 19.34 supports
413 ;;;; `syntax-table' text properties. Try setting
414 ;;;; `cperl-use-syntax-table-text-property'.
415
416 ;;;; After 1.32.3
417 ;;;  We scan for s{}[] as well (in simplest situations).
418 ;;;  We scan for $blah'foo as well.
419 ;;;  The default is to use `syntax-table' text property if Emacs is good enough.
420 ;;;  `cperl-lineup' is put on C-M-| (=C-M-S-\\).
421 ;;;  Start of `cperl-beautify-regexp'.
422
423 ;;;; After 1.32.4
424 ;;; `cperl-tags-hier-init' did not work in text-mode.
425 ;;; `cperl-noscan-files-regexp' had a misprint.
426 ;;; Generation of Class Hierarchy was broken due to a bug in `x-popup-menu'
427 ;;;  in 19.34.
428
429 ;;;; After 1.33:
430 ;;; my,local highlight vars after {} too.
431 ;;; TAGS could not be created before imenu was loaded.
432 ;;; `cperl-indent-left-aligned-comments' created.
433 ;;; Logic of `cperl-indent-exp' changed a little bit, should be more
434 ;;;  robust w.r.t. multiline strings.
435 ;;; Recognition of blah'foo takes into account strings.
436 ;;; Added '.al' to the list of Perl extensions.
437 ;;; Class hierarchy is "mostly" sorted (need to rethink algorthm
438 ;;;  of pruning one-root-branch subtrees to get yet better sorting.)
439 ;;; Regeneration of TAGS was busted.
440 ;;; Can use `syntax-table' property when generating TAGS
441 ;;;  (governed by  `cperl-use-syntax-table-text-property-for-tags').
442
443 ;;;; After 1.35:
444 ;;; Can process several =pod/=cut sections one after another.
445 ;;; Knows of `extproc' when under `emx', indents with `__END__' and `__DATA__'.
446 ;;; `cperl-under-as-char' implemented (XEmacs people like broken behaviour).
447 ;;; Beautifier for regexps fixed.
448 ;;; `cperl-beautify-level', `cperl-contract-level' coded
449 ;;;
450 ;;;; Emacs's 20.2 problems:
451 ;;; `imenu.el' has bugs, `imenu-add-to-menubar' does not work.
452 ;;; Couple of others problems with 20.2 were reported, my ability to check/fix
453 ;;; them is very reduced now.
454
455 ;;;; After 1.36:
456 ;;;  'C-M-|' in XEmacs fixed
457
458 ;;;; After 1.37:
459 ;;;  &&s was not recognized as start of regular expression;
460 ;;;  Will "preprocess" the contents of //e part of s///e too;
461 ;;;  What to do with s# blah # foo #e ?
462 ;;;  Should handle s;blah;foo;; better.
463 ;;;  Now the only known problems with regular expression recognition:
464 ;;;;;;;  s<foo>/bar/    - different delimiters (end ignored)
465 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into one chunk)
466 ;;;;;;;  s/foo//        - empty subst (made into one chunk + '/')
467 ;;;;;;;  s/foo/(bar)/   - start-group at start of subst (internal group will not match backwards)
468
469 ;;;; After 1.38:
470 ;;;  We highlight closing / of s/blah/foo/e;
471 ;;;  This handles s# blah # foo #e too;
472 ;;;  s//blah/, s///, s/blah// works again, and s#blah## too, the algorithm
473 ;;;   is much simpler now;
474 ;;;  Next round of changes: s\\\ works, s<blah>/foo/, 
475 ;;;   comments between the first and the second part allowed
476 ;;;  Another problem discovered:
477 ;;;;;;;  s[foo] <blah>e - e part delimited by different <> (will not match)
478 ;;;  `cperl-find-pods-heres' somehow maybe called when string-face is undefined
479 ;;;   - put a stupid workaround for 20.1
480
481 ;;;; After 1.39:
482 ;;;  Could indent here-docs for comments;
483 ;;;  These problems fixed:
484 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into two chunk)
485 ;;;;;;;  s[foo] <blah>e - "e" part delimited by "different" <> (will match)
486 ;;;  Matching brackets honor prefices, may expand abbreviations;
487 ;;;  When expanding abbrevs, will remove last char only after
488 ;;;    self-inserted whitespace;
489 ;;;  More convenient "Refress hard constructs" in menu;
490 ;;;  `cperl-add-tags-recurse', `cperl-add-tags-recurse-noxs'
491 ;;;    added (for -batch mode);
492 ;;;  Better handling of errors when scanning for Perl constructs;
493 ;;;;;;;  Possible "problem" with class hierarchy in Perl distribution 
494 ;;;;;;;    directory: ./ext duplicates ./lib;
495 ;;;  Write relative paths for generated TAGS;
496
497 ;;;; After 1.40:
498 ;;;  s  /// may be separated by "\n\f" too;
499 ;;;  `s  #blah' recognized as a comment;
500 ;;;  Would highlight s/abc//s wrong;
501 ;;;  Debugging code in `cperl-electric-keywords' was leaking a message;
502
503 ;;;; After 1.41:
504 ;;;  RMS changes for (future?) 20.3 merged
505
506 ;;;; 2.0.1.0: RMS mode (has 3 misprints)
507
508 ;;;; After 2.0:
509 ;;;  RMS whitespace changes for (future?) 20.3 merged
510
511 ;;;; After 2.1:
512 ;;;  History updated
513
514 ;;;; After 2.2:
515 ;;;  Merge `c-style-alist' since `c-mode' is no more.  (Somebody who
516 ;;;    uses the styles should check that they work OK!)
517 ;;;  All the variable warnings go away, some undef functions too.
518
519 ;;;; After 2.3:
520 ;;;  Added `cperl-perldoc' (thanks to Anthony Foiani <afoiani@uswest.com>)
521 ;;;  Added `cperl-pod-to-manpage' (thanks to Nick Roberts <Nick.Roberts@src.bae.co.uk>)
522 ;;;  All the function warnings go away.
523
524 ;;;; After 2.4:
525 ;;;  `Perl doc', `Regexp' submenus created (latter to allow short displays).
526 ;;;  `cperl-clobber-lisp-bindings' added.
527 ;;;  $a->y() is not y///.
528 ;;;  `cperl-after-block-p' was missing a `save-excursion' => wrong results.
529 ;;;  `cperl-val' was defined too late. 
530 ;;;  `cperl-init-faces' was failing.
531 ;;;  Init faces when loading `ps-print'.
532
533 ;;;; After 2.4:
534 ;;;  `cperl-toggle-autohelp' implemented.
535 ;;;  `while SPACE LESS' was buggy.
536 ;;;  `-text' in `[-text => 1]' was not highlighted.
537 ;;;  `cperl-after-block-p' was FALSE after `sub f {}'.
538
539 ;;;; After 2.5:
540 ;;;  `foreachmy', `formy' expanded too.
541 ;;;  Expand `=pod-directive'.
542 ;;;  `cperl-linefeed' behaves reasonable in POD-directive lines.
543 ;;;  `cperl-electric-keyword' prints a message, governed by
544 ;;;    `cperl-message-electric-keyword'.
545
546 ;;;; After 2.6:
547 ;;;  Typing `}' was not checking for being block or not.
548 ;;;  Beautifying levels in RE: Did not know about lookbehind;
549 ;;;                            finding *which* level was not intuitive;
550 ;;;                            `cperl-beautify-levels' added.
551 ;;;  Allow here-docs contain `=head1' and friends (at least for keywords).
552
553 ;;;; After 2.7:
554 ;;;  Fix for broken `font-lock-unfontify-region-function'.  Should
555 ;;;    preserve `syntax-table' properties even with `lazy-lock'.
556
557 ;;;; After 2.8:
558 ;;;  Some more compile time warnings crept in.
559 ;;;  `cperl-indent-region-fix-else' implemented.
560 ;;;  `cperl-fix-line-spacing' implemented.
561 ;;;  `cperl-invert-if-unless' implemented (C-c C-t and in Menu).
562 ;;;  Upgraded hints to mention 20.2's goods/bads.
563 ;;;  Started to use `cperl-extra-newline-before-brace-multiline',
564 ;;;    `cperl-break-one-line-blocks-when-indent', 
565 ;;;    `cperl-fix-hanging-brace-when-indent', `cperl-merge-trailing-else'.
566
567 ;;;; After 2.9:
568 ;;;  Workaround for another `font-lock's `syntax-table' text-property bug.
569 ;;;  `zerop' could be applied to nil.
570 ;;;  At last, may work with `font-lock' without setting `cperl-font-lock'.
571 ;;;    (We expect that starting from 19.33, `font-lock' supports keywords
572 ;;;     being a function - what is a correct version?)
573 ;;;  Rename `cperl-indent-region-fix-else' to 
574 ;;;    `cperl-indent-region-fix-constructs'.
575 ;;;  `cperl-fix-line-spacing' could be triggered inside strings, would not
576 ;;;     know what to do with BLOCKs of map/printf/etc.
577 ;;;  `cperl-merge-trailing-else' and `cperl-fix-line-spacing' handle
578 ;;;     `continue' too.
579 ;;;  Indentation after {BLOCK} knows about map/printf/etc.
580 ;;;  Finally: treat after-comma lines as continuation lines.
581
582 ;;;; After 2.10:
583 ;;;  `continue' made electric.
584 ;;;  Electric `do' inserts `do/while'.
585 ;;;  Some extra compile-time warnings crept in.
586 ;;;  `font-lock' of 19.33 could not handle font-lock-keywords being a function
587 ;;;      returning a symbol.
588
589 ;;;; After 2.11:
590 ;;;  Changes to make syntaxification to be autoredone via `font-lock'.
591 ;;;    Switched on by `cperl-syntaxify-by-font-lock', off by default so far.
592
593 ;;;; After 2.12:
594 ;;;  Remove some commented out chunks.
595 ;;;  Styles are slightly updated (a lot of work is needed, especially 
596 ;;;    with new `cperl-fix-line-spacing').
597
598 ;;;; After 2.13:
599 ;;;  Old value of style is memorized when choosing a new style, may be 
600 ;;;    restored from the same menu.
601 ;;;  Mode-documentation added to micro-docs.
602 ;;;  `cperl-praise' updated.
603 ;;;  `cperl-toggle-construct-fix' added on C-c C-w and menu.
604 ;;;  `auto-fill-mode' added on C-c C-f and menu.
605 ;;;  `PerlStyle' style added.
606 ;;;  Message for termination of scan corrected.
607
608 ;;;; After 2.14:
609
610 ;;;  Did not work with -q
611
612 ;;;; After 2.15:
613
614 ;;;  `cperl-speed' hints added.
615 ;;;  Minor style fixes.
616
617 ;;;; After 2.15:
618 ;;;  Make backspace electric after expansion of `else/continue' too.
619
620 ;;;; After 2.16:
621 ;;;  Starting to merge changes to RMS emacs version.
622
623 ;;;; After 2.17:
624 ;;;  Merged custom stuff and darn `font-lock-constant-face'.
625
626 ;;;; After 2.18:
627 ;;;  Bumped the version to 3.1
628
629 ;;;; After 3.1:
630 ;;;  Fixed customization to honor cperl-hairy.
631 ;;;  Created customization groups.  Sent to RMS to include into 2.3.
632
633 ;;;; After 3.2:
634 ;;;  Interaction of `font-lock-hot-pass' and `cperl-syntaxify-by-font-lock'.
635 ;;;  (`cperl-after-block-and-statement-beg'):
636 ;;;  (`cperl-after-block-p'):
637 ;;;  (`cperl-after-expr-p'):    It is BLOCK if we reach lim when backup sexp.
638 ;;;  (`cperl-indent-region'):   Make a marker for END - text added/removed.
639 ;;;  (`cperl-style-alist', `cperl-styles-entries')
640 ;;;             Include `cperl-merge-trailing-else' where the value is clear.
641
642 ;;;; After 3.3:
643 ;;;  (`cperl-tips'):
644 ;;;  (`cperl-problems'):        Improvements to docs.
645
646 ;;;; After 3.4:
647 ;;;  (`cperl-mode'):            Make lazy syntaxification possible.
648 ;;;  (`cperl-find-pods-heres'): Safe a position in buffer where it is safe to 
649 ;;;                             restart syntaxification.
650 ;;;  (`cperl-syntaxify-by-font-lock'): Set to t, should be safe now.
651
652 ;;;; After 3.5:
653 ;;;  (`cperl-syntaxify-by-font-lock'): Better default, customizes to 
654 ;;;                             `message' too.
655
656 ;;;; After 3.6:
657 ;;;  (`cperl-find-pods-heres'): changed so that -d ?foo? is a RE.
658 ;;;  (`cperl-array-face'): changed name from `font-lock-emphasized-face'.
659 ;;;  (`cperl-hash-face'): changed name from  `font-lock-other-emphasized-face'.
660 ;;;  Use `defface' to define these two extra faces.
661
662 ;;;; After 3.7:
663 ;;;  Can use linear algorithm for indentation if Emacs supports it:
664 ;;;  indenting DB::DB (800+ lines) improved from 69 sec to 11 sec
665 ;;;  (73 vs 15 with imenu).
666 ;;;  (`cperl-emacs-can-parse'): New state.
667 ;;;  (`cperl-indent-line'):     Corrected to use global state.
668 ;;;  (`cperl-calculate-indent'):        Likewise.
669 ;;;  (`cperl-fix-line-spacing'):        Likewise (not used yet).
670
671 ;;;; After 3.8:
672 ;;;  (`cperl-choose-color'):    Converted to a function (to be compilable in text-mode).
673
674 ;;;; After 3.9:
675 ;;;  (`cperl-dark-background '):        Disable without window-system.
676
677 ;;;; After 3.10:
678 ;;;  Do `defface' only if window-system.
679
680 ;;;; After 3.11:
681 ;;;  (`cperl-fix-line-spacing'):        sped up to bail out early.
682 ;;;  (`cperl-indent-region'):   Disable hooks during the call (how to call them later?).
683
684 ;;;  Now indents 820-line-long function in 6.5 sec (including syntaxification) the first time
685 ;;;  (when buffer has few properties), 7.1 sec the second time.
686
687 ;;;Function Name                              Call Count  Elapsed Time  Average Time
688 ;;;=========================================  ==========  ============  ============
689 ;;;cperl-indent-exp                           1           10.039999999  10.039999999
690 ;;;cperl-indent-region                        1           10.0          10.0
691 ;;;cperl-indent-line                          821         6.2100000000  0.0075639464
692 ;;;cperl-calculate-indent                     821         5.0199999999  0.0061144945
693 ;;;cperl-backward-to-noncomment               2856        2.0500000000  0.0007177871
694 ;;;cperl-fontify-syntaxically                 2           1.78          0.8900000000
695 ;;;cperl-find-pods-heres                      2           1.78          0.8900000000
696 ;;;cperl-update-syntaxification               1           1.78          1.78
697 ;;;cperl-fix-line-spacing                     769         1.4800000000  0.0019245773
698 ;;;cperl-after-block-and-statement-beg        163         1.4100000000  0.0086503067
699 ;;;cperl-block-p                              775         1.1800000000  0.0015225806
700 ;;;cperl-to-comment-or-eol                    3652        1.1200000000  0.0003066812
701 ;;;cperl-after-block-p                        165         1.0500000000  0.0063636363
702 ;;;cperl-commentify                           141         0.22          0.0015602836
703 ;;;cperl-get-state                            813         0.16          0.0001968019
704 ;;;cperl-backward-to-start-of-continued-exp   26          0.12          0.0046153846
705 ;;;cperl-delay-update-hook                    2107        0.0899999999  4.271...e-05
706 ;;;cperl-protect-defun-start                  141         0.0700000000  0.0004964539
707 ;;;cperl-after-label                          407         0.0599999999  0.0001474201
708 ;;;cperl-forward-re                           139         0.0299999999  0.0002158273
709 ;;;cperl-comment-indent                       26          0.0299999999  0.0011538461
710 ;;;cperl-use-region-p                         8           0.0           0.0
711 ;;;cperl-lazy-hook                            15          0.0           0.0
712 ;;;cperl-after-expr-p                         8           0.0           0.0
713 ;;;cperl-font-lock-unfontify-region-function  1           0.0           0.0
714
715 ;;;Function Name                              Call Count  Elapsed Time  Average Time
716 ;;;=========================================  ==========  ============  ============
717 ;;;cperl-fix-line-spacing                     769         1.4500000000  0.0018855656
718 ;;;cperl-indent-line                          13          0.3100000000  0.0238461538
719 ;;;cperl-after-block-and-statement-beg        69          0.2700000000  0.0039130434
720 ;;;cperl-after-block-p                        69          0.2099999999  0.0030434782
721 ;;;cperl-calculate-indent                     13          0.1000000000  0.0076923076
722 ;;;cperl-backward-to-noncomment               177         0.0700000000  0.0003954802
723 ;;;cperl-get-state                            13          0.0           0.0
724 ;;;cperl-to-comment-or-eol                    179         0.0           0.0
725 ;;;cperl-get-help-defer                       1           0.0           0.0
726 ;;;cperl-lazy-hook                            11          0.0           0.0
727 ;;;cperl-after-expr-p                         2           0.0           0.0
728 ;;;cperl-block-p                              13          0.0           0.0
729 ;;;cperl-after-label                          5           0.0           0.0
730
731 ;;;; After 3.12:
732 ;;;  (`cperl-find-pods-heres'): do not warn on `=cut' if doing a chunk only.
733
734 ;;;; After 3.13:
735 ;;;  (`cperl-mode'): load pseudo-faces on `cperl-find-pods-heres' (for 19.30).
736 ;;;  (`x-color-defined-p'): was not compiling on XEmacs
737 ;;;  (`cperl-find-pods-heres'): 1 << 6 was OK, but 1<<6 was considered as HERE
738 ;;;                             <file/glob> made into a string.
739
740 ;;; Code:
741
742 \f
743 (if (fboundp 'eval-when-compile)
744     (eval-when-compile
745       (condition-case nil
746           (require 'custom)
747         (error nil))
748       (or (fboundp 'defgroup)
749           (defmacro defgroup (name val doc &rest arr)
750             nil))
751       (or (fboundp 'custom-declare-variable)
752           (defmacro defcustom (name val doc &rest arr)
753             (` (defvar (, name) (, val) (, doc)))))
754       (or (and (fboundp 'custom-declare-variable)
755                (string< "19.31" emacs-version))  ;  Checked with 19.30: defface does not work
756           (defmacro defface (&rest arr)
757             nil))
758             ;; Avoid warning (tmp definitions)
759       (or (fboundp 'x-color-defined-p)
760           (defmacro 'x-color-defined-p (col)
761             (cond ((fboundp 'color-defined-p) (` (color-defined-p (, col))))
762                   ;; XEmacs >= 19.12
763                   ((fboundp 'valid-color-name-p) (` (valid-color-name-p (, col))))
764                   ;; XEmacs 19.11
765                   (t (` (x-valid-color-name-p (, col)))))))
766       (fset 'cperl-is-face
767             (cond ((fboundp 'find-face)
768                    (symbol-function 'find-face))
769                   ((and (fboundp 'face-list)
770                         (face-list))
771                    (function (lambda (face) 
772                                (member face (and (fboundp 'face-list)
773                                                  (face-list))))))
774                   (t
775                    (function (lambda (face) (boundp face))))))))
776
777 (require 'custom)
778 (defun cperl-choose-color (&rest list)
779   (let (answer)
780     (while list
781       (or answer
782           (if (or (x-color-defined-p (car list))
783                   (null (cdr list)))
784               (setq answer (car list))))
785       (setq list (cdr list)))
786     answer))
787
788 \f
789 (defgroup cperl nil
790   "Major mode for editing Perl code."
791   :prefix "cperl-"
792   :group 'languages)
793
794 (defgroup cperl-indentation-details nil
795   "Indentation."
796   :prefix "cperl-"
797   :group 'cperl)
798
799 (defgroup cperl-affected-by-hairy nil
800   "Variables affected by `cperl-hairy'."
801   :prefix "cperl-"
802   :group 'cperl)
803
804 (defgroup cperl-autoinsert-details nil
805   "Auto-insert tuneup."
806   :prefix "cperl-"
807   :group 'cperl)
808
809 (defgroup cperl-faces nil
810   "Fontification colors."
811   :prefix "cperl-"
812   :group 'cperl)
813
814 (defgroup cperl-speed nil
815   "Speed vs. validity tuneup."
816   :prefix "cperl-"
817   :group 'cperl)
818
819 (defgroup cperl-help-system nil
820   "Help system tuneup."
821   :prefix "cperl-"
822   :group 'cperl)
823
824 \f
825 (defcustom cperl-extra-newline-before-brace nil
826   "*Non-nil means that if, elsif, while, until, else, for, foreach
827 and do constructs look like:
828
829         if ()
830         {
831         }
832
833 instead of:
834
835         if () {
836         }
837 "
838   :type 'boolean
839   :group 'cperl-autoinsert-details)
840
841 (defcustom cperl-extra-newline-before-brace-multiline 
842   cperl-extra-newline-before-brace
843   "*Non-nil means the same as `cperl-extra-newline-before-brace', but
844 for constructs with multiline if/unless/while/until/for/foreach condition."
845   :type 'boolean
846   :group 'cperl-autoinsert-details)
847
848 (defcustom cperl-indent-level 2
849   "*Indentation of CPerl statements with respect to containing block."
850   :type 'integer
851   :group 'cperl-indentation-details)
852
853 (defcustom cperl-lineup-step nil
854   "*`cperl-lineup' will always lineup at multiple of this number.
855 If `nil', the value of `cperl-indent-level' will be used."
856   :type '(choice (const nil) integer)
857   :group 'cperl-indentation-details)
858
859 (defcustom cperl-brace-imaginary-offset 0
860   "*Imagined indentation of a Perl open brace that actually follows a statement.
861 An open brace following other text is treated as if it were this far
862 to the right of the start of its line."
863   :type 'integer
864   :group 'cperl-indentation-details)
865
866 (defcustom cperl-brace-offset 0
867   "*Extra indentation for braces, compared with other text in same context."
868   :type 'integer
869   :group 'cperl-indentation-details)
870 (defcustom cperl-label-offset -2
871   "*Offset of CPerl label lines relative to usual indentation."
872   :type 'integer
873   :group 'cperl-indentation-details)
874 (defcustom cperl-min-label-indent 1
875   "*Minimal offset of CPerl label lines."
876   :type 'integer
877   :group 'cperl-indentation-details)
878 (defcustom cperl-continued-statement-offset 2
879   "*Extra indent for lines not starting new statements."
880   :type 'integer
881   :group 'cperl-indentation-details)
882 (defcustom cperl-continued-brace-offset 0
883   "*Extra indent for substatements that start with open-braces.
884 This is in addition to cperl-continued-statement-offset."
885   :type 'integer
886   :group 'cperl-indentation-details)
887 (defcustom cperl-close-paren-offset -1
888   "*Extra indent for substatements that start with close-parenthesis."
889   :type 'integer
890   :group 'cperl-indentation-details)
891
892 (defcustom cperl-auto-newline nil
893   "*Non-nil means automatically newline before and after braces,
894 and after colons and semicolons, inserted in CPerl code.  The following
895 \\[cperl-electric-backspace] will remove the inserted whitespace.
896 Insertion after colons requires both this variable and 
897 `cperl-auto-newline-after-colon' set."
898   :type 'boolean
899   :group 'cperl-autoinsert-details)
900
901 (defcustom cperl-auto-newline-after-colon nil
902   "*Non-nil means automatically newline even after colons.
903 Subject to `cperl-auto-newline' setting."
904   :type 'boolean
905   :group 'cperl-autoinsert-details)
906
907 (defcustom cperl-tab-always-indent t
908   "*Non-nil means TAB in CPerl mode should always reindent the current line,
909 regardless of where in the line point is when the TAB command is used."
910   :type 'boolean
911   :group 'cperl-indentation-details)
912
913 (defcustom cperl-font-lock nil
914   "*Non-nil (and non-null) means CPerl buffers will use font-lock-mode.
915 Can be overwritten by `cperl-hairy' if nil."
916   :type '(choice (const null) boolean)
917   :group 'cperl-affected-by-hairy)
918
919 (defcustom cperl-electric-lbrace-space nil
920   "*Non-nil (and non-null) means { after $ in CPerl buffers should be preceded by ` '.
921 Can be overwritten by `cperl-hairy' if nil."
922   :type '(choice (const null) boolean)
923   :group 'cperl-affected-by-hairy)
924
925 (defcustom cperl-electric-parens-string "({[]})<"
926   "*String of parentheses that should be electric in CPerl.
927 Closing ones are electric only if the region is highlighted."
928   :type 'string
929   :group 'cperl-affected-by-hairy)
930
931 (defcustom cperl-electric-parens nil
932   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
933 Can be overwritten by `cperl-hairy' if nil."
934   :type '(choice (const null) boolean)
935   :group 'cperl-affected-by-hairy)
936
937 (defvar zmacs-regions)                  ; Avoid warning
938
939 (defcustom cperl-electric-parens-mark  
940   (and window-system
941        (or (and (boundp 'transient-mark-mode) ; For Emacs
942                 transient-mark-mode)
943            (and (boundp 'zmacs-regions) ; For XEmacs
944                 zmacs-regions)))
945   "*Not-nil means that electric parens look for active mark.
946 Default is yes if there is visual feedback on mark."
947   :type 'boolean
948   :group 'cperl-autoinsert-details)
949
950 (defcustom cperl-electric-linefeed nil
951   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
952 In any case these two mean plain and hairy linefeeds together.
953 Can be overwritten by `cperl-hairy' if nil."
954   :type '(choice (const null) boolean)
955   :group 'cperl-affected-by-hairy)
956
957 (defcustom cperl-electric-keywords nil
958   "*Not-nil (and non-null) means keywords are electric in CPerl.
959 Can be overwritten by `cperl-hairy' if nil."
960   :type '(choice (const null) boolean)
961   :group 'cperl-affected-by-hairy)
962
963 (defcustom cperl-hairy nil
964   "*Not-nil means most of the bells and whistles are enabled in CPerl.
965 Affects: `cperl-font-lock', `cperl-electric-lbrace-space', 
966 `cperl-electric-parens', `cperl-electric-linefeed', `cperl-electric-keywords',
967 `cperl-info-on-command-no-prompt', `cperl-clobber-lisp-bindings',
968 `cperl-lazy-help-time'."
969   :type 'boolean
970   :group 'cperl-affected-by-hairy)
971
972 (defcustom cperl-comment-column 32
973   "*Column to put comments in CPerl (use \\[cperl-indent] to lineup with code)."
974   :type 'integer
975   :group 'cperl-indentation-details)
976
977 (defcustom cperl-vc-header-alist '((SCCS "$sccs = '%W\%' ;")
978                                    (RCS "$rcs = ' $Id\$ ' ;"))
979   "*What to use as `vc-header-alist' in CPerl."
980   :type '(repeat (list symbol string))
981   :group 'cperl)
982
983 (defcustom cperl-info-on-command-no-prompt nil
984   "*Not-nil (and non-null) means not to prompt on C-h f.
985 The opposite behaviour is always available if prefixed with C-c.
986 Can be overwritten by `cperl-hairy' if nil."
987   :type '(choice (const null) boolean)
988   :group 'cperl-affected-by-hairy)
989
990 (defcustom cperl-clobber-lisp-bindings nil
991   "*Not-nil (and non-null) means not overwrite C-h f.
992 The function is available on \\[cperl-info-on-command], \\[cperl-get-help].
993 Can be overwritten by `cperl-hairy' if nil."
994   :type '(choice (const null) boolean)
995   :group 'cperl-affected-by-hairy)
996
997 (defcustom cperl-lazy-help-time nil
998   "*Not-nil (and non-null) means to show lazy help after given idle time.
999 Can be overwritten by `cperl-hairy' to be 5 sec if nil."
1000   :type '(choice (const null) integer)
1001   :group 'cperl-affected-by-hairy)
1002
1003 (defcustom cperl-pod-face 'font-lock-comment-face
1004   "*The result of evaluation of this expression is used for pod highlighting."
1005   :type 'face
1006   :group 'cperl-faces)
1007
1008 (defcustom cperl-pod-head-face 'font-lock-variable-name-face
1009   "*The result of evaluation of this expression is used for pod highlighting.
1010 Font for POD headers."
1011   :type 'face
1012   :group 'cperl-faces)
1013
1014 (defcustom cperl-here-face 'font-lock-string-face
1015   "*The result of evaluation of this expression is used for here-docs highlighting."
1016   :type 'face
1017   :group 'cperl-faces)
1018
1019 (defcustom cperl-pod-here-fontify '(featurep 'font-lock)
1020   "*Not-nil after evaluation means to highlight pod and here-docs sections."
1021   :type 'boolean
1022   :group 'cperl-faces)
1023
1024 (defcustom cperl-pod-here-scan t
1025   "*Not-nil means look for pod and here-docs sections during startup.
1026 You can always make lookup from menu or using \\[cperl-find-pods-heres]."
1027   :type 'boolean
1028   :group 'cperl-speed)
1029
1030 (defcustom cperl-imenu-addback nil
1031   "*Not-nil means add backreferences to generated `imenu's.
1032 May require patched `imenu' and `imenu-go'.  Obsolete."
1033   :type 'boolean
1034   :group 'cperl-help-system)
1035
1036 (defcustom cperl-max-help-size 66
1037   "*Non-nil means shrink-wrapping of info-buffer allowed up to these percents."
1038   :type '(choice integer (const nil))
1039   :group 'cperl-help-system)
1040
1041 (defcustom cperl-shrink-wrap-info-frame t
1042   "*Non-nil means shrink-wrapping of info-buffer-frame allowed."
1043   :type 'boolean
1044   :group 'cperl-help-system)
1045
1046 (defcustom cperl-info-page "perl"
1047   "*Name of the info page containing perl docs.
1048 Older version of this page was called `perl5', newer `perl'."
1049   :type 'string
1050   :group 'cperl-help-system)
1051
1052 (defcustom cperl-use-syntax-table-text-property 
1053   (boundp 'parse-sexp-lookup-properties)
1054   "*Non-nil means CPerl sets up and uses `syntax-table' text property."
1055   :type 'boolean
1056   :group 'cperl-speed)
1057
1058 (defcustom cperl-use-syntax-table-text-property-for-tags 
1059   cperl-use-syntax-table-text-property
1060   "*Non-nil means: set up and use `syntax-table' text property generating TAGS."
1061   :type 'boolean
1062   :group 'cperl-speed)
1063
1064 (defcustom cperl-scan-files-regexp "\\.\\([pP][Llm]\\|xs\\)$"
1065   "*Regexp to match files to scan when generating TAGS."
1066   :type 'regexp
1067   :group 'cperl)
1068
1069 (defcustom cperl-noscan-files-regexp "/\\(\\.\\.?\\|SCCS\\|RCS\\|blib\\)$"
1070   "*Regexp to match files/dirs to skip when generating TAGS."
1071   :type 'regexp
1072   :group 'cperl)
1073
1074 (defcustom cperl-regexp-indent-step nil
1075   "*Indentation used when beautifying regexps.
1076 If `nil', the value of `cperl-indent-level' will be used."
1077   :type '(choice integer (const nil))
1078   :group 'cperl-indentation-details)
1079
1080 (defcustom cperl-indent-left-aligned-comments t
1081   "*Non-nil means that the comment starting in leftmost column should indent."
1082   :type 'boolean
1083   :group 'cperl-indentation-details)
1084
1085 (defcustom cperl-under-as-char t
1086   "*Non-nil means that the _ (underline) should be treated as word char."
1087   :type 'boolean
1088   :group 'cperl)
1089
1090 (defcustom cperl-extra-perl-args ""
1091   "*Extra arguments to use when starting Perl.
1092 Currently used with `cperl-check-syntax' only."
1093   :type 'string
1094   :group 'cperl)
1095
1096 (defcustom cperl-message-electric-keyword t
1097   "*Non-nil means that the `cperl-electric-keyword' prints a help message."
1098   :type 'boolean
1099   :group 'cperl-help-system)
1100
1101 (defcustom cperl-indent-region-fix-constructs 1
1102   "*Amount of space to insert between `}' and `else' or `elsif'
1103 in `cperl-indent-region'.  Set to nil to leave as is.  Values other
1104 than 1 and nil will probably not work."
1105   :type '(choice (const nil) (const 1))
1106   :group 'cperl-indentation-details)
1107
1108 (defcustom cperl-break-one-line-blocks-when-indent t
1109   "*Non-nil means that one-line if/unless/while/until/for/foreach BLOCKs
1110 need to be reformated into multiline ones when indenting a region."
1111   :type 'boolean
1112   :group 'cperl-indentation-details)
1113
1114 (defcustom cperl-fix-hanging-brace-when-indent t
1115   "*Non-nil means that BLOCK-end `}' may be put on a separate line
1116 when indenting a region. 
1117 Braces followed by else/elsif/while/until are excepted."
1118   :type 'boolean
1119   :group 'cperl-indentation-details)
1120
1121 (defcustom cperl-merge-trailing-else t
1122   "*Non-nil means that BLOCK-end `}' followed by else/elsif/continue 
1123 may be merged to be on the same line when indenting a region."
1124   :type 'boolean
1125   :group 'cperl-indentation-details)
1126
1127 (defcustom cperl-syntaxify-by-font-lock 
1128   (boundp 'parse-sexp-lookup-properties)
1129   "*Non-nil means that CPerl uses `font-lock's routines for syntaxification.
1130 Having it TRUE may be not completely debugged yet."
1131   :type '(choice (const message) boolean)
1132   :group 'cperl-speed)
1133
1134 (if window-system
1135     (progn
1136       (defvar cperl-dark-background 
1137         (cperl-choose-color "navy" "os2blue" "darkgreen"))
1138
1139       (defface cperl-array-face
1140         (` ((((class grayscale) (background light))
1141              (:background "Gray90" :bold t))
1142             (((class grayscale) (background dark))
1143              (:foreground "Gray80" :bold t))
1144             (((class color) (background light)) 
1145              (:foreground "Blue" :background "lightyellow2" :bold t))
1146             (((class color) (background dark)) 
1147              (:foreground "yellow" :background (, cperl-dark-background) :bold t))
1148             (t (:bold t))))
1149         "Font Lock mode face used to highlight array names."
1150         :group 'cperl-faces)
1151
1152       (defface cperl-hash-face
1153         (` ((((class grayscale) (background light))
1154              (:background "Gray90" :bold t :italic t))
1155             (((class grayscale) (background dark))
1156              (:foreground "Gray80" :bold t :italic t))
1157             (((class color) (background light)) 
1158              (:foreground "Red" :background "lightyellow2" :bold t :italic t))
1159             (((class color) (background dark)) 
1160              (:foreground "Red" :background (, cperl-dark-background) :bold t :italic t))
1161             (t (:bold t :italic t))))
1162         "Font Lock mode face used to highlight hash names."
1163         :group 'cperl-faces)))
1164
1165 \f
1166
1167 ;;; Short extra-docs.
1168
1169 (defvar cperl-tips 'please-ignore-this-line
1170   "Get newest version of this package from
1171   ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
1172 and/or
1173   ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
1174 Subdirectory `cperl-mode' may contain yet newer development releases and/or
1175 patches to related files.
1176
1177 Get support packages choose-color.el (or font-lock-extra.el before
1178 19.30), imenu-go.el from the same place.  \(Look for other files there
1179 too... ;-).  Get a patch for imenu.el in 19.29.  Note that for 19.30 and
1180 later you should use choose-color.el *instead* of font-lock-extra.el 
1181 \(and you will not get smart highlighting in C :-().
1182
1183 Note that to enable Compile choices in the menu you need to install
1184 mode-compile.el.
1185
1186 Get perl5-info from 
1187   $CPAN/doc/manual/info/perl-info.tar.gz
1188 older version was on
1189   http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz
1190
1191 If you use imenu-go, run imenu on perl5-info buffer (you can do it
1192 from CPerl menu).  If many files are related, generate TAGS files from
1193 Tools/Tags submenu in CPerl menu.
1194
1195 If some class structure is too complicated, use Tools/Hierarchy-view
1196 from CPerl menu, or hierarchic view of imenu. The second one uses the
1197 current buffer only, the first one requires generation of TAGS from
1198 CPerl/Tools/Tags menu beforehand.
1199
1200 Run CPerl/Tools/Insert-spaces-if-needed to fix your lazy typing.
1201
1202 Switch auto-help on/off with CPerl/Tools/Auto-help.
1203
1204 Before reporting (non-)problems look in the problem section on what I
1205 know about them.")
1206
1207 (defvar cperl-problems 'please-ignore-this-line
1208 "Some faces will not be shown on some versions of Emacs unless you
1209 install choose-color.el, available from
1210    ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs/
1211
1212 Emacs had a _very_ restricted syntax parsing engine until RMS's Emacs
1213 20.1.  Most problems below are corrected starting from this version of
1214 Emacs, and all of them should go with (future) RMS's version 20.3.
1215
1216 Note that even with newer Emacsen interaction of `font-lock' and
1217 syntaxification is not cleaned up.  You may get slightly different
1218 colors basing on the order of fontification and syntaxification.  This
1219 might be corrected by setting `cperl-syntaxify-by-font-lock' to t, but
1220 the corresponding code is still extremely buggy.
1221
1222 Even with older Emacsen CPerl mode tries to corrects some Emacs
1223 misunderstandings, however, for efficiency reasons the degree of
1224 correction is different for different operations.  The partially
1225 corrected problems are: POD sections, here-documents, regexps.  The
1226 operations are: highlighting, indentation, electric keywords, electric
1227 braces.
1228
1229 This may be confusing, since the regexp s#//#/#\; may be highlighted
1230 as a comment, but it will be recognized as a regexp by the indentation
1231 code.  Or the opposite case, when a pod section is highlighted, but
1232 may break the indentation of the following code (though indentation
1233 should work if the balance of delimiters is not broken by POD).
1234
1235 The main trick (to make $ a \"backslash\") makes constructions like
1236 ${aaa} look like unbalanced braces.  The only trick I can think of is
1237 to insert it as $ {aaa} (legal in perl5, not in perl4). 
1238
1239 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
1240 as /($|\\s)/.  Note that such a transposition is not always possible.
1241
1242 The solution is to upgrade your Emacs.  Note that RMS's 20.2 has some
1243 bugs related to `syntax-table' text properties.  Patches are available
1244 on the main CPerl download site, and on CPAN.
1245
1246 If these bugs cannot be fixed on your machine (say, you have an inferior
1247 environment and cannot recompile), you may still disable all the fancy stuff
1248 via `cperl-use-syntax-table-text-property'." )
1249
1250 (defvar cperl-non-problems 'please-ignore-this-line
1251 "As you know from `problems' section, Perl syntax is too hard for CPerl on 
1252 older Emacsen.
1253
1254 Most of the time, if you write your own code, you may find an equivalent
1255 \(and almost as readable) expression (what is discussed below is usually
1256 not relevant on newer Emacsen, since they can do it automatically).
1257
1258 Try to help CPerl: add comments with embedded quotes to fix CPerl
1259 misunderstandings about the end of quotation:
1260
1261 $a='500$';      # ';
1262
1263 You won't need it too often.  The reason: $ \"quotes\" the following
1264 character (this saves a life a lot of times in CPerl), thus due to
1265 Emacs parsing rules it does not consider tick (i.e., ' ) after a
1266 dollar as a closing one, but as a usual character.  This is usually
1267 correct, but not in the above context.
1268
1269 Even with older Emacsen the indentation code is pretty wise.  The only
1270 drawback is that it relied on Emacs parsing to find matching
1271 parentheses.  And Emacs *could not* match parentheses in Perl 100%
1272 correctly.  So
1273         1 if s#//#/#;
1274 would not break indentation, but
1275         1 if ( s#//#/# );
1276 would.  Upgrade.
1277
1278 By similar reasons
1279         s\"abc\"def\";
1280 would confuse CPerl a lot.
1281
1282 If you still get wrong indentation in situation that you think the
1283 code should be able to parse, try:
1284
1285 a) Check what Emacs thinks about balance of your parentheses.
1286 b) Supply the code to me (IZ).
1287
1288 Pods were treated _very_ rudimentally.  Here-documents were not
1289 treated at all (except highlighting and inhibiting indentation).  Upgrade.
1290
1291 To speed up coloring the following compromises exist:
1292    a) sub in $mypackage::sub may be highlighted.
1293    b) -z in [a-z] may be highlighted.
1294    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
1295
1296
1297 Imenu in 19.31 is broken.  Set `imenu-use-keymap-menu' to t, and remove
1298 `car' before `imenu-choose-buffer-index' in `imenu'.
1299 `imenu-add-to-menubar' in 20.2 is broken.  
1300 A lot of things on XEmacs may be broken too, judging by bug reports I
1301 recieve.  Note that some releases of XEmacs are better than the others
1302 as far as bugs reports I see are concerned.")
1303
1304 (defvar cperl-praise 'please-ignore-this-line
1305   "RMS asked me to list good things about CPerl.  Here they go:
1306
1307 0) It uses the newest `syntax-table' property ;-);
1308
1309 1) It does 99% of Perl syntax correct (as opposed to 80-90% in Perl
1310 mode - but the latter number may have improved too in last years) even 
1311 without `syntax-table' property; When using this property, it should 
1312 handle 99.995% of lines correct - or somesuch.
1313
1314 2) It is generally believed to be \"the most user-friendly Emacs
1315 package\" whatever it may mean (I doubt that the people who say similar
1316 things tried _all_ the rest of Emacs ;-), but this was not a lonely
1317 voice);
1318
1319 3) Everything is customizable, one-by-one or in a big sweep;
1320
1321 4) It has many easily-accessable \"tools\":
1322         a) Can run program, check syntax, start debugger;
1323         b) Can lineup vertically \"middles\" of rows, like `=' in
1324                 a  = b;
1325                 cc = d;
1326         c) Can insert spaces where this impoves readability (in one
1327                 interactive sweep over the buffer);
1328         d) Has support for imenu, including:
1329                 1) Separate unordered list of \"interesting places\";
1330                 2) Separate TOC of POD sections;
1331                 3) Separate list of packages;
1332                 4) Hierarchical view of methods in (sub)packages;
1333                 5) and functions (by the full name - with package);
1334         e) Has an interface to INFO docs for Perl; The interface is
1335                 very flexible, including shrink-wrapping of
1336                 documentation buffer/frame;
1337         f) Has a builtin list of one-line explanations for perl constructs.
1338         g) Can show these explanations if you stay long enough at the
1339                 corresponding place (or on demand);
1340         h) Has an enhanced fontification (using 3 or 4 additional faces
1341                 comparing to font-lock - basically, different
1342                 namespaces in Perl have different colors);
1343         i) Can construct TAGS basing on its knowledge of Perl syntax,
1344                 the standard menu has 6 different way to generate
1345                 TAGS (if \"by directory\", .xs files - with C-language
1346                 bindings - are included in the scan);
1347         j) Can build a hierarchical view of classes (via imenu) basing
1348                 on generated TAGS file;
1349         k) Has electric parentheses, electric newlines, uses Abbrev
1350                 for electric logical constructs
1351                         while () {}
1352                 with different styles of expansion (context sensitive
1353                 to be not so bothering).  Electric parentheses behave
1354                 \"as they should\" in a presence of a visible region.
1355         l) Changes msb.el \"on the fly\" to insert a group \"Perl files\";
1356         m) Can convert from
1357                 if (A) { B }
1358            to
1359                 B if A;
1360
1361 5) The indentation engine was very smart, but most of tricks may be
1362 not needed anymore with the support for `syntax-table' property.  Has
1363 progress indicator for indentation (with `imenu' loaded).
1364
1365 6) Indent-region improves inline-comments as well; also corrects 
1366 whitespace *inside* the conditional/loop constructs.
1367
1368 7) Fill-paragraph correctly handles multi-line comments;
1369
1370 8) Can switch to different indentation styles by one command, and restore
1371 the settings present before the switch.
1372
1373 9) When doing indentation of control constructs, may correct 
1374 line-breaks/spacing between elements of the construct.
1375 ")
1376
1377 (defvar cperl-speed 'please-ignore-this-line
1378   "This is an incomplete compendium of what is available in other parts
1379 of CPerl documentation.  (Please inform me if I skept anything.)
1380
1381 There is a perception that CPerl is slower than alternatives.  This part
1382 of documentation is designed to overcome this misconception.
1383
1384 *By default* CPerl tries to enable the most comfortable settings.
1385 From most points of view, correctly working package is infinitely more
1386 comfortable than a non-correctly working one, thus by default CPerl
1387 prefers correctness over speed.  Below is the guide how to change
1388 settings if your preferences are different.
1389
1390 A)  Speed of loading the file.  When loading file, CPerl may perform a
1391 scan which indicates places which cannot be parsed by primitive Emacs
1392 syntax-parsing routines, and marks them up so that either
1393
1394     A1) CPerl may work around these deficiencies (for big chunks, mostly
1395         PODs and HERE-documents), or
1396     A2) On capable Emaxen CPerl will use improved syntax-handlings
1397         which reads mark-up hints directly.
1398
1399     The scan in case A2 is much more comprehensive, thus may be slower.
1400
1401     User can disable syntax-engine-helping scan of A2 by setting
1402        `cperl-use-syntax-table-text-property'
1403     variable to nil (if it is set to t).
1404
1405     One can disable the scan altogether (both A1 and A2) by setting
1406        `cperl-pod-here-scan'
1407     to nil.
1408
1409 B) Speed of editing operations.  
1410
1411     One can add a (minor) speedup to editing operations by setting
1412        `cperl-use-syntax-table-text-property'
1413     variable to nil (if it is set to t).  This will disable
1414     syntax-engine-helping scan, thus will make many more Perl
1415     constructs be wrongly recognized by CPerl, thus may lead to
1416     wrongly matched parentheses, wrong indentation, etc.
1417 ")
1418
1419 \f
1420
1421 ;;; Portability stuff:
1422
1423 (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1424
1425 (defmacro cperl-define-key (emacs-key definition &optional xemacs-key)
1426   (` (define-key cperl-mode-map
1427        (, (if xemacs-key
1428               (` (if cperl-xemacs-p (, xemacs-key) (, emacs-key)))
1429             emacs-key))
1430        (, definition))))
1431
1432 (defvar cperl-del-back-ch
1433   (car (append (where-is-internal 'delete-backward-char)
1434                (where-is-internal 'backward-delete-char-untabify)))
1435   "Character generated by key bound to delete-backward-char.")
1436
1437 (and (vectorp cperl-del-back-ch) (= (length cperl-del-back-ch) 1) 
1438      (setq cperl-del-back-ch (aref cperl-del-back-ch 0)))
1439
1440 (defun cperl-mark-active () (mark))     ; Avoid undefined warning
1441 (if cperl-xemacs-p
1442     (progn
1443       ;; "Active regions" are on: use region only if active
1444       ;; "Active regions" are off: use region unconditionally
1445       (defun cperl-use-region-p ()
1446         (if zmacs-regions (mark) t)))
1447   (defun cperl-use-region-p ()
1448     (if transient-mark-mode mark-active t))
1449   (defun cperl-mark-active () mark-active))
1450
1451 (defsubst cperl-enable-font-lock ()
1452   (or cperl-xemacs-p window-system))
1453
1454 (defun cperl-putback-char (c)   ; Emacs 19
1455   (set 'unread-command-events (list c))) ; Avoid undefined warning
1456
1457 (if (boundp 'unread-command-events)
1458     (if cperl-xemacs-p
1459         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
1460           (setq unread-command-events (list (eval '(character-to-event c))))))
1461   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
1462     (set 'unread-command-event (eval '(character-to-event c))))) ; Avoid warnings
1463
1464 (or (fboundp 'uncomment-region)
1465     (defun uncomment-region (beg end)
1466       (interactive "r")
1467       (comment-region beg end -1)))
1468
1469 (defvar cperl-do-not-fontify
1470   (if (string< emacs-version "19.30")
1471       'fontified
1472     'lazy-lock)
1473   "Text property which inhibits refontification.")
1474
1475 (defsubst cperl-put-do-not-fontify (from to)
1476   (put-text-property (max (point-min) (1- from))
1477                      to cperl-do-not-fontify t))
1478
1479 (defcustom cperl-mode-hook nil
1480   "Hook run by `cperl-mode'."
1481   :type 'hook
1482   :group 'cperl)
1483
1484 (defvar cperl-syntax-state nil)
1485 (defvar cperl-syntax-done-to nil)
1486 (defvar cperl-emacs-can-parse (> (length (save-excursion
1487                                            (parse-partial-sexp 1 1))) 9))
1488 \f
1489 ;; Make customization possible "in reverse"
1490 (defsubst cperl-val (symbol &optional default hairy)
1491   (cond
1492    ((eq (symbol-value symbol) 'null) default)
1493    (cperl-hairy (or hairy t))
1494    (t (symbol-value symbol))))
1495 \f
1496 ;;; Probably it is too late to set these guys already, but it can help later:
1497
1498 (setq auto-mode-alist
1499       (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
1500 (and (boundp 'interpreter-mode-alist)
1501      (setq interpreter-mode-alist (append interpreter-mode-alist
1502                                           '(("miniperl" . perl-mode)))))
1503 (if (fboundp 'eval-when-compile)
1504     (eval-when-compile
1505       (condition-case nil
1506           (require 'imenu)
1507         (error nil))
1508       (condition-case nil
1509           (require 'easymenu)
1510         (error nil))
1511       (condition-case nil
1512           (require 'etags)
1513         (error nil))
1514       (condition-case nil
1515           (require 'timer)
1516         (error nil))
1517       (condition-case nil
1518           (require 'man)
1519         (error nil))
1520       (condition-case nil
1521           (require 'info)
1522         (error nil))
1523       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
1524       ;; macros instead of defsubsts don't work on Emacs, so we do the
1525       ;; expansion manually.  Any other suggestions?
1526       (if (or (string-match "XEmacs\\|Lucid" emacs-version)
1527               window-system)
1528           (require 'font-lock))
1529       (require 'cl)))
1530
1531 (defvar cperl-mode-abbrev-table nil
1532   "Abbrev table in use in Cperl-mode buffers.")
1533
1534 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
1535
1536 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
1537
1538 (if cperl-mode-map nil
1539   (setq cperl-mode-map (make-sparse-keymap))
1540   (cperl-define-key "{" 'cperl-electric-lbrace)
1541   (cperl-define-key "[" 'cperl-electric-paren)
1542   (cperl-define-key "(" 'cperl-electric-paren)
1543   (cperl-define-key "<" 'cperl-electric-paren)
1544   (cperl-define-key "}" 'cperl-electric-brace)
1545   (cperl-define-key "]" 'cperl-electric-rparen)
1546   (cperl-define-key ")" 'cperl-electric-rparen)
1547   (cperl-define-key ";" 'cperl-electric-semi)
1548   (cperl-define-key ":" 'cperl-electric-terminator)
1549   (cperl-define-key "\C-j" 'newline-and-indent)
1550   (cperl-define-key "\C-c\C-j" 'cperl-linefeed)
1551   (cperl-define-key "\C-c\C-t" 'cperl-invert-if-unless)
1552   (cperl-define-key "\C-c\C-a" 'cperl-toggle-auto-newline)
1553   (cperl-define-key "\C-c\C-k" 'cperl-toggle-abbrev)
1554   (cperl-define-key "\C-c\C-w" 'cperl-toggle-construct-fix)
1555   (cperl-define-key "\C-c\C-f" 'auto-fill-mode)
1556   (cperl-define-key "\C-c\C-e" 'cperl-toggle-electric)
1557   (cperl-define-key "\C-c\C-ha" 'cperl-toggle-autohelp)
1558   (cperl-define-key "\e\C-q" 'cperl-indent-exp) ; Usually not bound
1559   (cperl-define-key [?\C-\M-\|] 'cperl-lineup
1560                     [(control meta |)])
1561   ;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
1562   ;;(cperl-define-key "\e;" 'cperl-indent-for-comment)
1563   (cperl-define-key "\177" 'cperl-electric-backspace)
1564   (cperl-define-key "\t" 'cperl-indent-command)
1565   ;; don't clobber the backspace binding:
1566   (cperl-define-key "\C-c\C-hf" 'cperl-info-on-current-command
1567                     [(control c) (control h) f])
1568   (cperl-define-key "\C-c\C-hF" 'cperl-info-on-command
1569                     [(control c) (control h) F])
1570   (cperl-define-key "\C-c\C-hv"
1571                     ;;(concat (char-to-string help-char) "v") ; does not work
1572                     'cperl-get-help
1573                     [(control c) (control h) v])
1574   (if (cperl-val 'cperl-clobber-lisp-bindings)
1575       (progn
1576         (cperl-define-key "\C-hf"
1577                           ;;(concat (char-to-string help-char) "f") ; does not work
1578                           'cperl-info-on-command
1579                           [(control h) f])
1580         (cperl-define-key "\C-hv"
1581                           ;;(concat (char-to-string help-char) "v") ; does not work
1582                           'cperl-get-help
1583                           [(control h) v])))
1584   (if (and cperl-xemacs-p 
1585            (<= emacs-minor-version 11) (<= emacs-major-version 19))
1586       (progn
1587         ;; substitute-key-definition is usefulness-deenhanced...
1588         (cperl-define-key "\M-q" 'cperl-fill-paragraph)
1589         (cperl-define-key "\e;" 'cperl-indent-for-comment)
1590         (cperl-define-key "\e\C-\\" 'cperl-indent-region))
1591     (substitute-key-definition
1592      'indent-sexp 'cperl-indent-exp
1593      cperl-mode-map global-map)
1594     (substitute-key-definition
1595      'fill-paragraph 'cperl-fill-paragraph
1596      cperl-mode-map global-map)
1597     (substitute-key-definition
1598      'indent-region 'cperl-indent-region
1599      cperl-mode-map global-map)
1600     (substitute-key-definition
1601      'indent-for-comment 'cperl-indent-for-comment
1602      cperl-mode-map global-map)))
1603
1604 (defvar cperl-menu)
1605 (defvar cperl-lazy-installed)
1606 (defvar cperl-old-style nil)
1607 (condition-case nil
1608     (progn
1609       (require 'easymenu)
1610       (easy-menu-define cperl-menu cperl-mode-map "Menu for CPerl mode"
1611          '("Perl"
1612            ["Beginning of function" beginning-of-defun t]
1613            ["End of function" end-of-defun t]
1614            ["Mark function" mark-defun t]
1615            ["Indent expression" cperl-indent-exp t]
1616            ["Fill paragraph/comment" cperl-fill-paragraph t]
1617            "----"
1618            ["Line up a construction" cperl-lineup (cperl-use-region-p)]
1619            ["Invert if/unless/while/until" cperl-invert-if-unless t]
1620            ("Regexp"
1621             ["Beautify" cperl-beautify-regexp
1622              cperl-use-syntax-table-text-property]
1623             ["Beautify a group" cperl-beautify-level
1624              cperl-use-syntax-table-text-property]
1625             ["Contract a group" cperl-contract-level
1626              cperl-use-syntax-table-text-property]
1627             ["Contract groups" cperl-contract-levels
1628              cperl-use-syntax-table-text-property])
1629            ["Refresh \"hard\" constructions" cperl-find-pods-heres t]
1630            "----"
1631            ["Indent region" cperl-indent-region (cperl-use-region-p)]
1632            ["Comment region" cperl-comment-region (cperl-use-region-p)]
1633            ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
1634            "----"
1635            ["Run" mode-compile (fboundp 'mode-compile)]
1636            ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
1637                                           (get-buffer "*compilation*"))]
1638            ["Next error" next-error (get-buffer "*compilation*")]
1639            ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
1640            "----"
1641            ["Debugger" cperl-db t]
1642            "----"
1643            ("Tools"
1644             ["Imenu" imenu (fboundp 'imenu)]
1645             ["Insert spaces if needed" cperl-find-bad-style t]
1646             ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
1647             ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
1648             ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
1649             ("Tags"
1650 ;;;          ["Create tags for current file" cperl-etags t]
1651 ;;;          ["Add tags for current file" (cperl-etags t) t]
1652 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
1653 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
1654 ;;;          ["Create tags for Perl files in (sub)directories" 
1655 ;;;           (cperl-etags nil 'recursive) t]
1656 ;;;          ["Add tags for Perl files in (sub)directories"
1657 ;;;           (cperl-etags t 'recursive) t]) 
1658 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
1659              ["Create tags for current file" (cperl-write-tags nil t) t]
1660              ["Add tags for current file" (cperl-write-tags) t]
1661              ["Create tags for Perl files in directory" 
1662               (cperl-write-tags nil t nil t) t]
1663              ["Add tags for Perl files in directory" 
1664               (cperl-write-tags nil nil nil t) t]
1665              ["Create tags for Perl files in (sub)directories" 
1666               (cperl-write-tags nil t t t) t]
1667              ["Add tags for Perl files in (sub)directories"
1668               (cperl-write-tags nil nil t t) t]))
1669            ("Perl docs"
1670             ["Define word at point" imenu-go-find-at-position 
1671              (fboundp 'imenu-go-find-at-position)]
1672             ["Help on function" cperl-info-on-command t]
1673             ["Help on function at point" cperl-info-on-current-command t]
1674             ["Help on symbol at point" cperl-get-help t]
1675             ["Perldoc" cperl-perldoc t]
1676             ["Perldoc on word at point" cperl-perldoc-at-point t]
1677             ["View manpage of POD in this file" cperl-pod-to-manpage t]
1678             ["Auto-help on" cperl-lazy-install 
1679              (and (fboundp 'run-with-idle-timer)
1680                   (not cperl-lazy-installed))]
1681             ["Auto-help off" (eval '(cperl-lazy-unstall)) 
1682              (and (fboundp 'run-with-idle-timer)
1683                   cperl-lazy-installed)])
1684            ("Toggle..."
1685             ["Auto newline" cperl-toggle-auto-newline t]
1686             ["Electric parens" cperl-toggle-electric t]
1687             ["Electric keywords" cperl-toggle-abbrev t]
1688             ["Fix whitespace on indent" cperl-toggle-construct-fix t]
1689             ["Auto fill" auto-fill-mode t]) 
1690            ("Indent styles..."
1691             ["CPerl" (cperl-set-style "CPerl") t]
1692             ["PerlStyle" (cperl-set-style "PerlStyle") t]
1693             ["GNU" (cperl-set-style "GNU") t]
1694             ["C++" (cperl-set-style "C++") t]
1695             ["FSF" (cperl-set-style "FSF") t]
1696             ["BSD" (cperl-set-style "BSD") t]
1697             ["Whitesmith" (cperl-set-style "Whitesmith") t]
1698             ["Current" (cperl-set-style "Current") t]
1699             ["Memorized" (cperl-set-style-back) cperl-old-style])
1700            ("Micro-docs"
1701             ["Tips" (describe-variable 'cperl-tips) t]
1702             ["Problems" (describe-variable 'cperl-problems) t]
1703             ["Non-problems" (describe-variable 'cperl-non-problems) t]
1704             ["Speed" (describe-variable 'cperl-speed) t]
1705             ["Praise" (describe-variable 'cperl-praise) t]
1706             ["CPerl mode" (describe-function 'cperl-mode) t]))))
1707   (error nil))
1708
1709 (autoload 'c-macro-expand "cmacexp"
1710   "Display the result of expanding all C macros occurring in the region.
1711 The expansion is entirely correct because it uses the C preprocessor."
1712   t)
1713
1714 (defvar cperl-mode-syntax-table nil
1715   "Syntax table in use in Cperl-mode buffers.")
1716
1717 (defvar cperl-string-syntax-table nil
1718   "Syntax table in use in Cperl-mode string-like chunks.")
1719
1720 (if cperl-mode-syntax-table
1721     ()
1722   (setq cperl-mode-syntax-table (make-syntax-table))
1723   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
1724   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
1725   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
1726   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
1727   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
1728   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
1729   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
1730   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
1731   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
1732   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
1733   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
1734   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
1735   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
1736   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
1737   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
1738   (if cperl-under-as-char
1739       (modify-syntax-entry ?_ "w" cperl-mode-syntax-table))
1740   (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
1741   (modify-syntax-entry ?| "." cperl-mode-syntax-table)
1742   (setq cperl-string-syntax-table (copy-syntax-table cperl-mode-syntax-table))
1743   (modify-syntax-entry ?$ "." cperl-string-syntax-table)
1744   (modify-syntax-entry ?# "." cperl-string-syntax-table) ; (?# comment )
1745 )
1746
1747
1748 \f
1749 ;; provide an alias for working with emacs 19.  the perl-mode that comes
1750 ;; with it is really bad, and this lets us seamlessly replace it.
1751 ;;;###autoload
1752 (fset 'perl-mode 'cperl-mode)
1753 (defvar cperl-faces-init nil)
1754 ;; Fix for msb.el
1755 (defvar cperl-msb-fixed nil)
1756 (defvar font-lock-syntactic-keywords)
1757 (defvar perl-font-lock-keywords)
1758 (defvar perl-font-lock-keywords-1)
1759 (defvar perl-font-lock-keywords-2)
1760 ;;;###autoload
1761 (defun cperl-mode ()
1762   "Major mode for editing Perl code.
1763 Expression and list commands understand all C brackets.
1764 Tab indents for Perl code.
1765 Paragraphs are separated by blank lines only.
1766 Delete converts tabs to spaces as it moves back.
1767
1768 Various characters in Perl almost always come in pairs: {}, (), [],
1769 sometimes <>.  When the user types the first, she gets the second as
1770 well, with optional special formatting done on {}.  (Disabled by
1771 default.)  You can always quote (with \\[quoted-insert]) the left
1772 \"paren\" to avoid the expansion.  The processing of < is special,
1773 since most the time you mean \"less\".  Cperl mode tries to guess
1774 whether you want to type pair <>, and inserts is if it
1775 appropriate.  You can set `cperl-electric-parens-string' to the string that
1776 contains the parenths from the above list you want to be electrical.
1777 Electricity of parenths is controlled by `cperl-electric-parens'.
1778 You may also set `cperl-electric-parens-mark' to have electric parens
1779 look for active mark and \"embrace\" a region if possible.'
1780
1781 CPerl mode provides expansion of the Perl control constructs:
1782
1783    if, else, elsif, unless, while, until, continue, do, 
1784    for, foreach, formy and foreachmy.
1785
1786 and POD directives (Disabled by default, see `cperl-electric-keywords'.)
1787
1788 The user types the keyword immediately followed by a space, which
1789 causes the construct to be expanded, and the point is positioned where
1790 she is most likely to want to be.  eg. when the user types a space
1791 following \"if\" the following appears in the buffer: if () { or if ()
1792 } { } and the cursor is between the parentheses.  The user can then
1793 type some boolean expression within the parens.  Having done that,
1794 typing \\[cperl-linefeed] places you - appropriately indented - on a
1795 new line between the braces (if you typed \\[cperl-linefeed] in a POD
1796 directive line, then appropriate number of new lines is inserted).  
1797
1798 If CPerl decides that you want to insert \"English\" style construct like
1799
1800             bite if angry;
1801
1802 it will not do any expansion.  See also help on variable
1803 `cperl-extra-newline-before-brace'.  (Note that one can switch the
1804 help message on expansion by setting `cperl-message-electric-keyword'
1805 to nil.)
1806
1807 \\[cperl-linefeed] is a convenience replacement for typing carriage
1808 return.  It places you in the next line with proper indentation, or if
1809 you type it inside the inline block of control construct, like
1810
1811             foreach (@lines) {print; print}
1812
1813 and you are on a boundary of a statement inside braces, it will
1814 transform the construct into a multiline and will place you into an
1815 appropriately indented blank line.  If you need a usual 
1816 `newline-and-indent' behaviour, it is on \\[newline-and-indent], 
1817 see documentation on `cperl-electric-linefeed'.
1818
1819 Use \\[cperl-invert-if-unless] to change a construction of the form
1820
1821             if (A) { B }
1822
1823 into
1824
1825             B if A;
1826
1827 \\{cperl-mode-map}
1828
1829 Setting the variable `cperl-font-lock' to t switches on font-lock-mode
1830 \(even with older Emacsen), `cperl-electric-lbrace-space' to t switches
1831 on electric space between $ and {, `cperl-electric-parens-string' is
1832 the string that contains parentheses that should be electric in CPerl
1833 \(see also `cperl-electric-parens-mark' and `cperl-electric-parens'),
1834 setting `cperl-electric-keywords' enables electric expansion of
1835 control structures in CPerl.  `cperl-electric-linefeed' governs which
1836 one of two linefeed behavior is preferable.  You can enable all these
1837 options simultaneously (recommended mode of use) by setting
1838 `cperl-hairy' to t.  In this case you can switch separate options off
1839 by setting them to `null'.  Note that one may undo the extra
1840 whitespace inserted by semis and braces in `auto-newline'-mode by
1841 consequent \\[cperl-electric-backspace].
1842
1843 If your site has perl5 documentation in info format, you can use commands
1844 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
1845 These keys run commands `cperl-info-on-current-command' and
1846 `cperl-info-on-command', which one is which is controlled by variable
1847 `cperl-info-on-command-no-prompt' and `cperl-clobber-lisp-bindings' 
1848 \(in turn affected by `cperl-hairy').
1849
1850 Even if you have no info-format documentation, short one-liner-style
1851 help is available on \\[cperl-get-help], and one can run perldoc or
1852 man via menu.
1853
1854 It is possible to show this help automatically after some idle time.
1855 This is regulated by variable `cperl-lazy-help-time'.  Default with
1856 `cperl-hairy' (if the value of `cperl-lazy-help-time' is nil) is 5
1857 secs idle time .  It is also possible to switch this on/off from the
1858 menu, or via \\[cperl-toggle-autohelp].  Requires `run-with-idle-timer'.
1859
1860 Use \\[cperl-lineup] to vertically lineup some construction - put the
1861 beginning of the region at the start of construction, and make region
1862 span the needed amount of lines.
1863
1864 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
1865 `cperl-pod-face', `cperl-pod-head-face' control processing of pod and
1866 here-docs sections.  With capable Emaxen results of scan are used
1867 for indentation too, otherwise they are used for highlighting only.
1868
1869 Variables controlling indentation style:
1870  `cperl-tab-always-indent'
1871     Non-nil means TAB in CPerl mode should always reindent the current line,
1872     regardless of where in the line point is when the TAB command is used.
1873  `cperl-indent-left-aligned-comments'
1874     Non-nil means that the comment starting in leftmost column should indent.
1875  `cperl-auto-newline'
1876     Non-nil means automatically newline before and after braces,
1877     and after colons and semicolons, inserted in Perl code.  The following
1878     \\[cperl-electric-backspace] will remove the inserted whitespace.
1879     Insertion after colons requires both this variable and 
1880     `cperl-auto-newline-after-colon' set. 
1881  `cperl-auto-newline-after-colon'
1882     Non-nil means automatically newline even after colons.
1883     Subject to `cperl-auto-newline' setting.
1884  `cperl-indent-level'
1885     Indentation of Perl statements within surrounding block.
1886     The surrounding block's indentation is the indentation
1887     of the line on which the open-brace appears.
1888  `cperl-continued-statement-offset'
1889     Extra indentation given to a substatement, such as the
1890     then-clause of an if, or body of a while, or just a statement continuation.
1891  `cperl-continued-brace-offset'
1892     Extra indentation given to a brace that starts a substatement.
1893     This is in addition to `cperl-continued-statement-offset'.
1894  `cperl-brace-offset'
1895     Extra indentation for line if it starts with an open brace.
1896  `cperl-brace-imaginary-offset'
1897     An open brace following other text is treated as if it the line started
1898     this far to the right of the actual line indentation.
1899  `cperl-label-offset'
1900     Extra indentation for line that is a label.
1901  `cperl-min-label-indent'
1902     Minimal indentation for line that is a label.
1903
1904 Settings for K&R and BSD indentation styles are
1905   `cperl-indent-level'                5    8
1906   `cperl-continued-statement-offset'  5    8
1907   `cperl-brace-offset'               -5   -8
1908   `cperl-label-offset'               -5   -8
1909
1910 CPerl knows several indentation styles, and may bulk set the
1911 corresponding variables.  Use \\[cperl-set-style] to do this.  Use
1912 \\[cperl-set-style-back] to restore the memorized preexisting values
1913 \(both available from menu).
1914
1915 If `cperl-indent-level' is 0, the statement after opening brace in
1916 column 0 is indented on 
1917 `cperl-brace-offset'+`cperl-continued-statement-offset'.
1918
1919 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
1920 with no args.
1921
1922 DO NOT FORGET to read micro-docs (available from `Perl' menu)
1923 or as help on variables `cperl-tips', `cperl-problems',
1924 `cperl-non-problems', `cperl-praise', `cperl-speed'."
1925   (interactive)
1926   (kill-all-local-variables)
1927   (use-local-map cperl-mode-map)
1928   (if (cperl-val 'cperl-electric-linefeed)
1929       (progn
1930         (local-set-key "\C-J" 'cperl-linefeed)
1931         (local-set-key "\C-C\C-J" 'newline-and-indent)))
1932   (if (and
1933        (cperl-val 'cperl-clobber-lisp-bindings)
1934        (cperl-val 'cperl-info-on-command-no-prompt))
1935       (progn
1936         ;; don't clobber the backspace binding:
1937         (cperl-define-key "\C-hf" 'cperl-info-on-current-command [(control h) f])
1938         (cperl-define-key "\C-c\C-hf" 'cperl-info-on-command
1939                           [(control c) (control h) f])))
1940   (setq major-mode 'perl-mode)
1941   (setq mode-name "CPerl")
1942   (if (not cperl-mode-abbrev-table)
1943       (let ((prev-a-c abbrevs-changed))
1944         (define-abbrev-table 'cperl-mode-abbrev-table '(
1945                 ("if" "if" cperl-electric-keyword 0)
1946                 ("elsif" "elsif" cperl-electric-keyword 0)
1947                 ("while" "while" cperl-electric-keyword 0)
1948                 ("until" "until" cperl-electric-keyword 0)
1949                 ("unless" "unless" cperl-electric-keyword 0)
1950                 ("else" "else" cperl-electric-else 0)
1951                 ("continue" "continue" cperl-electric-else 0)
1952                 ("for" "for" cperl-electric-keyword 0)
1953                 ("foreach" "foreach" cperl-electric-keyword 0)
1954                 ("formy" "formy" cperl-electric-keyword 0)
1955                 ("foreachmy" "foreachmy" cperl-electric-keyword 0)
1956                 ("do" "do" cperl-electric-keyword 0)
1957                 ("pod" "pod" cperl-electric-pod 0)
1958                 ("over" "over" cperl-electric-pod 0)
1959                 ("head1" "head1" cperl-electric-pod 0)
1960                 ("head2" "head2" cperl-electric-pod 0)))
1961         (setq abbrevs-changed prev-a-c)))
1962   (setq local-abbrev-table cperl-mode-abbrev-table)
1963   (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
1964   (set-syntax-table cperl-mode-syntax-table)
1965   (make-local-variable 'paragraph-start)
1966   (setq paragraph-start (concat "^$\\|" page-delimiter))
1967   (make-local-variable 'paragraph-separate)
1968   (setq paragraph-separate paragraph-start)
1969   (make-local-variable 'paragraph-ignore-fill-prefix)
1970   (setq paragraph-ignore-fill-prefix t)
1971   (make-local-variable 'indent-line-function)
1972   (setq indent-line-function 'cperl-indent-line)
1973   (make-local-variable 'require-final-newline)
1974   (setq require-final-newline t)
1975   (make-local-variable 'comment-start)
1976   (setq comment-start "# ")
1977   (make-local-variable 'comment-end)
1978   (setq comment-end "")
1979   (make-local-variable 'comment-column)
1980   (setq comment-column cperl-comment-column)
1981   (make-local-variable 'comment-start-skip)
1982   (setq comment-start-skip "#+ *")
1983   (make-local-variable 'defun-prompt-regexp)
1984   (setq defun-prompt-regexp "^[ \t]*sub[ \t]+\\([^ \t\n{(;]+\\)[ \t]*")
1985   (make-local-variable 'comment-indent-function)
1986   (setq comment-indent-function 'cperl-comment-indent)
1987   (make-local-variable 'parse-sexp-ignore-comments)
1988   (setq parse-sexp-ignore-comments t)
1989   (make-local-variable 'indent-region-function)
1990   (setq indent-region-function 'cperl-indent-region)
1991   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
1992   (make-local-variable 'imenu-create-index-function)
1993   (setq imenu-create-index-function
1994         (function imenu-example--create-perl-index))
1995   (make-local-variable 'imenu-sort-function)
1996   (setq imenu-sort-function nil)
1997   (make-local-variable 'vc-header-alist)
1998   (set 'vc-header-alist cperl-vc-header-alist) ; Avoid warning
1999   (make-local-variable 'font-lock-defaults)
2000   (setq font-lock-defaults
2001         (cond
2002          ((string< emacs-version "19.30")
2003           '(perl-font-lock-keywords-2))
2004          ((string< emacs-version "19.33") ; Which one to use?
2005           '((perl-font-lock-keywords
2006              perl-font-lock-keywords-1
2007              perl-font-lock-keywords-2)))
2008          (t
2009           '((cperl-load-font-lock-keywords
2010              cperl-load-font-lock-keywords-1
2011              cperl-load-font-lock-keywords-2)))))
2012   (make-local-variable 'cperl-syntax-state)
2013   (if cperl-use-syntax-table-text-property
2014       (progn
2015         (make-variable-buffer-local 'parse-sexp-lookup-properties)
2016         ;; Do not introduce variable if not needed, we check it!
2017         (set 'parse-sexp-lookup-properties t)
2018         ;; Fix broken font-lock:
2019         (or (boundp 'font-lock-unfontify-region-function)
2020             (set 'font-lock-unfontify-region-function
2021                   'font-lock-default-unfontify-buffer))
2022         (make-variable-buffer-local 'font-lock-unfontify-region-function)
2023         (set 'font-lock-unfontify-region-function 
2024               'cperl-font-lock-unfontify-region-function)
2025         (make-variable-buffer-local 'cperl-syntax-done-to)
2026         ;; Another bug: unless font-lock-syntactic-keywords, font-lock
2027         ;;  ignores syntax-table text-property.  (t) is a hack
2028         ;;  to make font-lock think that font-lock-syntactic-keywords
2029         ;;  are defined
2030         (make-variable-buffer-local 'font-lock-syntactic-keywords)
2031         (setq font-lock-syntactic-keywords 
2032               (if cperl-syntaxify-by-font-lock
2033                   '(t (cperl-fontify-syntaxically))
2034                 '(t)))))
2035   (make-local-variable 'cperl-old-style)
2036   (or (fboundp 'cperl-old-auto-fill-mode)
2037       (progn
2038         (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
2039         (defun auto-fill-mode (&optional arg)
2040           (interactive "P")
2041           (eval '(cperl-old-auto-fill-mode arg)) ; Avoid a warning
2042           (and auto-fill-function (eq major-mode 'perl-mode)
2043                (setq auto-fill-function 'cperl-do-auto-fill)))))
2044   (if (cperl-enable-font-lock)
2045       (if (cperl-val 'cperl-font-lock) 
2046           (progn (or cperl-faces-init (cperl-init-faces))
2047                  (font-lock-mode 1))))
2048   (and (boundp 'msb-menu-cond)
2049        (not cperl-msb-fixed)
2050        (cperl-msb-fix))
2051   (if (featurep 'easymenu)
2052       (easy-menu-add cperl-menu))       ; A NOP in RMS Emacs.
2053   (run-hooks 'cperl-mode-hook)
2054   ;; After hooks since fontification will break this
2055   (if cperl-pod-here-scan 
2056       (or ;;(and (boundp 'font-lock-mode)
2057           ;;     (eval 'font-lock-mode) ; Avoid warning
2058           ;;     (boundp 'font-lock-hot-pass) ; Newer font-lock
2059        cperl-syntaxify-by-font-lock  ;;)
2060        (progn (or cperl-faces-init (cperl-init-faces-weak))
2061               (cperl-find-pods-heres)))))
2062 \f
2063 ;; Fix for perldb - make default reasonable
2064 (defvar gud-perldb-history)
2065 (defun cperl-db ()
2066   (interactive)
2067   (require 'gud)
2068   (perldb (read-from-minibuffer "Run perldb (like this): "
2069                                 (if (consp gud-perldb-history)
2070                                     (car gud-perldb-history)
2071                                   (concat "perl " ;;(file-name-nondirectory
2072                                                    ;; I have problems
2073                                                    ;; in OS/2
2074                                                    ;; otherwise
2075                                                    (buffer-file-name)))
2076                                 nil nil
2077                                 '(gud-perldb-history . 1))))
2078 \f
2079 (defvar msb-menu-cond)
2080 (defun cperl-msb-fix ()
2081   ;; Adds perl files to msb menu, supposes that msb is already loaded
2082   (setq cperl-msb-fixed t)
2083   (let* ((l (length msb-menu-cond))
2084          (last (nth (1- l) msb-menu-cond))
2085          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
2086          (handle (1- (nth 1 last))))
2087     (setcdr precdr (list
2088                     (list
2089                      '(eq major-mode 'perl-mode)
2090                      handle
2091                      "Perl Files (%d)")
2092                     last))))
2093 \f
2094 ;; This is used by indent-for-comment
2095 ;; to decide how much to indent a comment in CPerl code
2096 ;; based on its context.  Do fallback if comment is found wrong.
2097
2098 (defvar cperl-wrong-comment)
2099
2100 (defun cperl-comment-indent ()
2101   (let ((p (point)) (c (current-column)) was)
2102     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
2103       ;; Wrong comment found
2104       (save-excursion
2105         (setq was (cperl-to-comment-or-eol))
2106         (if (= (point) p)
2107             (progn
2108               (skip-chars-backward " \t")
2109               (max (1+ (current-column)) ; Else indent at comment column
2110                    comment-column))
2111           (if was nil
2112             (insert comment-start)
2113             (backward-char (length comment-start)))
2114           (setq cperl-wrong-comment t)
2115           (indent-to comment-column 1)  ; Indent minimum 1
2116           c)))))                        ; except leave at least one space.
2117
2118 ;;;(defun cperl-comment-indent-fallback ()
2119 ;;;  "Is called if the standard comment-search procedure fails.
2120 ;;;Point is at start of real comment."
2121 ;;;  (let ((c (current-column)) target cnt prevc)
2122 ;;;    (if (= c comment-column) nil
2123 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
2124 ;;;      (setq target (max (1+ (setq prevc 
2125 ;;;                          (current-column))) ; Else indent at comment column
2126 ;;;                comment-column))
2127 ;;;      (if (= c comment-column) nil
2128 ;;;     (delete-backward-char cnt)
2129 ;;;     (while (< prevc target)
2130 ;;;       (insert "\t")
2131 ;;;       (setq prevc (current-column)))
2132 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
2133 ;;;     (while (< prevc target)
2134 ;;;       (insert " ")
2135 ;;;       (setq prevc (current-column)))))))
2136
2137 (defun cperl-indent-for-comment ()
2138   "Substitute for `indent-for-comment' in CPerl."
2139   (interactive)
2140   (let (cperl-wrong-comment)
2141     (indent-for-comment)
2142     (if cperl-wrong-comment
2143         (progn (cperl-to-comment-or-eol)
2144                (forward-char (length comment-start))))))
2145
2146 (defun cperl-comment-region (b e arg)
2147   "Comment or uncomment each line in the region in CPerl mode.
2148 See `comment-region'."
2149   (interactive "r\np")
2150   (let ((comment-start "#"))
2151     (comment-region b e arg)))
2152
2153 (defun cperl-uncomment-region (b e arg)
2154   "Uncomment or comment each line in the region in CPerl mode.
2155 See `comment-region'."
2156   (interactive "r\np")
2157   (let ((comment-start "#"))
2158     (comment-region b e (- arg))))
2159
2160 (defvar cperl-brace-recursing nil)
2161
2162 (defun cperl-electric-brace (arg &optional only-before)
2163   "Insert character and correct line's indentation.
2164 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
2165 place (even in empty line), but not after.  If after \")\" and the inserted
2166 char is \"{\", insert extra newline before only if 
2167 `cperl-extra-newline-before-brace'."
2168   (interactive "P")
2169   (let (insertpos
2170         (other-end (if (and cperl-electric-parens-mark
2171                             (cperl-mark-active) 
2172                             (< (mark) (point)))
2173                        (mark) 
2174                      nil)))
2175     (if (and other-end
2176              (not cperl-brace-recursing)
2177              (cperl-val 'cperl-electric-parens)
2178              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point)))
2179         ;; Need to insert a matching pair
2180         (progn
2181           (save-excursion
2182             (setq insertpos (point-marker))
2183             (goto-char other-end)
2184             (setq last-command-char ?\{)
2185             (cperl-electric-lbrace arg insertpos))
2186           (forward-char 1))
2187       ;: Check whether we close something "usual" with `}'
2188       (if (and (eq last-command-char ?\})
2189                (not 
2190                 (condition-case nil
2191                     (save-excursion
2192                       (up-list (- (prefix-numeric-value arg)))
2193                       ;;(cperl-after-block-p (point-min))
2194                       (cperl-after-expr-p nil "{;)"))
2195                   (error nil))))
2196           ;; Just insert the guy
2197           (self-insert-command (prefix-numeric-value arg))
2198         (if (and (not arg)              ; No args, end (of empty line or auto)
2199                  (eolp)
2200                  (or (and (null only-before)
2201                           (save-excursion
2202                             (skip-chars-backward " \t")
2203                             (bolp)))
2204                      (and (eq last-command-char ?\{) ; Do not insert newline
2205                           ;; if after ")" and `cperl-extra-newline-before-brace'
2206                           ;; is nil, do not insert extra newline.
2207                           (not cperl-extra-newline-before-brace)
2208                           (save-excursion
2209                             (skip-chars-backward " \t")
2210                             (eq (preceding-char) ?\))))
2211                      (if cperl-auto-newline 
2212                          (progn (cperl-indent-line) (newline) t) nil)))
2213             (progn
2214               (self-insert-command (prefix-numeric-value arg))
2215               (cperl-indent-line)
2216               (if cperl-auto-newline
2217                   (setq insertpos (1- (point))))
2218               (if (and cperl-auto-newline (null only-before))
2219                   (progn
2220                     (newline)
2221                     (cperl-indent-line)))
2222               (save-excursion
2223                 (if insertpos (progn (goto-char insertpos)
2224                                      (search-forward (make-string 
2225                                                       1 last-command-char))
2226                                      (setq insertpos (1- (point)))))
2227                 (delete-char -1))))
2228         (if insertpos
2229             (save-excursion
2230               (goto-char insertpos)
2231               (self-insert-command (prefix-numeric-value arg)))
2232           (self-insert-command (prefix-numeric-value arg)))))))
2233
2234 (defun cperl-electric-lbrace (arg &optional end)
2235   "Insert character, correct line's indentation, correct quoting by space."
2236   (interactive "P")
2237   (let (pos after 
2238             (cperl-brace-recursing t)
2239             (cperl-auto-newline cperl-auto-newline)
2240             (other-end (or end
2241                            (if (and cperl-electric-parens-mark
2242                                     (cperl-mark-active)
2243                                     (> (mark) (point)))
2244                                (save-excursion
2245                                  (goto-char (mark))
2246                                  (point-marker)) 
2247                              nil))))
2248     (and (cperl-val 'cperl-electric-lbrace-space)
2249          (eq (preceding-char) ?$)
2250          (save-excursion
2251            (skip-chars-backward "$")
2252            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
2253          (insert ?\ ))
2254     ;; Check whether we are in comment
2255     (if (and 
2256          (save-excursion
2257            (beginning-of-line)
2258            (not (looking-at "[ \t]*#")))
2259          (cperl-after-expr-p nil "{;)"))
2260         nil
2261       (setq cperl-auto-newline nil))
2262     (cperl-electric-brace arg)
2263     (and (cperl-val 'cperl-electric-parens)
2264          (eq last-command-char ?{)
2265          (memq last-command-char 
2266                (append cperl-electric-parens-string nil))
2267          (or (if other-end (goto-char (marker-position other-end)))
2268              t)
2269          (setq last-command-char ?} pos (point))
2270          (progn (cperl-electric-brace arg t)
2271                 (goto-char pos)))))
2272
2273 (defun cperl-electric-paren (arg)
2274   "Insert a matching pair of parentheses."
2275   (interactive "P")
2276   (let ((beg (save-excursion (beginning-of-line) (point)))
2277         (other-end (if (and cperl-electric-parens-mark
2278                             (cperl-mark-active) 
2279                             (> (mark) (point)))
2280                            (save-excursion
2281                              (goto-char (mark))
2282                              (point-marker)) 
2283                      nil)))
2284     (if (and (cperl-val 'cperl-electric-parens)
2285              (memq last-command-char
2286                    (append cperl-electric-parens-string nil))
2287              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
2288              ;;(not (save-excursion (search-backward "#" beg t)))
2289              (if (eq last-command-char ?<)
2290                  (progn
2291                    (and abbrev-mode ; later it is too late, may be after `for'
2292                         (expand-abbrev))
2293                    (cperl-after-expr-p nil "{;(,:="))
2294                1))
2295         (progn
2296           (self-insert-command (prefix-numeric-value arg))
2297           (if other-end (goto-char (marker-position other-end)))
2298           (insert (make-string 
2299                    (prefix-numeric-value arg)
2300                    (cdr (assoc last-command-char '((?{ .?})
2301                                                    (?[ . ?])
2302                                                    (?( . ?))
2303                                                    (?< . ?>))))))
2304           (forward-char (- (prefix-numeric-value arg))))
2305       (self-insert-command (prefix-numeric-value arg)))))
2306
2307 (defun cperl-electric-rparen (arg)
2308   "Insert a matching pair of parentheses if marking is active.
2309 If not, or if we are not at the end of marking range, would self-insert."
2310   (interactive "P")
2311   (let ((beg (save-excursion (beginning-of-line) (point)))
2312         (other-end (if (and cperl-electric-parens-mark
2313                             (cperl-val 'cperl-electric-parens)
2314                             (memq last-command-char
2315                                   (append cperl-electric-parens-string nil))
2316                             (cperl-mark-active) 
2317                             (< (mark) (point)))
2318                        (mark) 
2319                      nil))
2320         p)
2321     (if (and other-end
2322              (cperl-val 'cperl-electric-parens)
2323              (memq last-command-char '( ?\) ?\] ?\} ?\> ))
2324              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
2325              ;;(not (save-excursion (search-backward "#" beg t)))
2326              )
2327         (progn
2328           (self-insert-command (prefix-numeric-value arg))
2329           (setq p (point))
2330           (if other-end (goto-char other-end))
2331           (insert (make-string
2332                    (prefix-numeric-value arg)
2333                    (cdr (assoc last-command-char '((?\} . ?\{)
2334                                                   (?\] . ?\[)
2335                                                   (?\) . ?\()
2336                                                   (?\> . ?\<))))))
2337           (goto-char (1+ p)))
2338       (self-insert-command (prefix-numeric-value arg)))))
2339
2340 (defun cperl-electric-keyword ()
2341   "Insert a construction appropriate after a keyword.
2342 Help message may be switched off by setting `cperl-message-electric-keyword'
2343 to nil."
2344   (let ((beg (save-excursion (beginning-of-line) (point))) 
2345         (dollar (and (eq last-command-char ?$)
2346                      (eq this-command 'self-insert-command)))
2347         (delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
2348                      (memq this-command '(self-insert-command newline))))
2349         my do)
2350     (and (save-excursion
2351            (condition-case nil
2352                (progn
2353                  (backward-sexp 1)
2354                  (setq do (looking-at "do\\>")))
2355              (error nil))
2356            (cperl-after-expr-p nil "{;:"))
2357          (save-excursion 
2358            (not 
2359             (re-search-backward
2360              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
2361              beg t)))
2362          (save-excursion (or (not (re-search-backward "^=" nil t))
2363                              (or
2364                               (looking-at "=cut")
2365                               (and cperl-use-syntax-table-text-property
2366                                    (not (eq (get-text-property (point)
2367                                                                'syntax-type)
2368                                             'pod))))))
2369          (progn
2370            (and (eq (preceding-char) ?y)
2371                 (progn                  ; "foreachmy"
2372                   (forward-char -2)
2373                   (insert " ")
2374                   (forward-char 2)
2375                   (setq my t dollar t 
2376                         delete 
2377                         (memq this-command '(self-insert-command newline)))))
2378            (and dollar (insert " $"))
2379            (cperl-indent-line)
2380            ;;(insert " () {\n}")
2381            (cond
2382             (cperl-extra-newline-before-brace
2383              (insert (if do "\n" " ()\n"))
2384              (insert "{")
2385              (cperl-indent-line)
2386              (insert "\n")
2387              (cperl-indent-line)
2388              (insert "\n}")
2389              (and do (insert " while ();")))
2390             (t
2391              (insert (if do " {\n} while ();" " () {\n}")))
2392             )
2393            (or (looking-at "[ \t]\\|$") (insert " "))
2394            (cperl-indent-line)
2395            (if dollar (progn (search-backward "$")
2396                              (if my 
2397                                  (forward-char 1)
2398                                (delete-char 1)))
2399              (search-backward ")"))
2400            (if delete
2401                (cperl-putback-char cperl-del-back-ch))
2402            (if cperl-message-electric-keyword
2403                (message "Precede char by C-q to avoid expansion"))))))
2404
2405 (defun cperl-ensure-newlines (n &optional pos)
2406   "Make sure there are N newlines after the point."
2407   (or pos (setq pos (point)))
2408   (if (looking-at "\n")
2409       (forward-char 1)
2410     (insert "\n"))
2411   (if (> n 1)
2412       (cperl-ensure-newlines (1- n) pos)
2413     (goto-char pos)))
2414
2415 (defun cperl-electric-pod ()
2416   "Insert a POD chunk appropriate after a =POD directive."
2417   (let ((delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
2418                      (memq this-command '(self-insert-command newline))))
2419         head1 notlast name p really-delete over)
2420     (and (save-excursion
2421            (condition-case nil
2422                (backward-sexp 1)
2423              (error nil))
2424            (and 
2425             (eq (preceding-char) ?=)
2426             (progn
2427               (setq head1 (looking-at "head1\\>"))
2428               (setq over (looking-at "over\\>"))
2429               (forward-char -1)
2430               (bolp))
2431             (or 
2432              (cperl-after-expr-p nil "{;:")
2433              (and (re-search-backward
2434                    "\\(\\`\n?\\|\n\n\\)=\\sw+" (point-min) t)
2435                   (not (or
2436                         (looking-at "=cut")
2437                         (and cperl-use-syntax-table-text-property
2438                              (not (eq (get-text-property (point) 'syntax-type)
2439                                       'pod)))))))))
2440          (progn
2441            (save-excursion
2442              (setq notlast (search-forward "\n\n=" nil t)))
2443            (or notlast
2444                (progn
2445                  (insert "\n\n=cut")
2446                  (cperl-ensure-newlines 2)
2447                  (forward-sexp -2)
2448                  (if (and head1 
2449                           (not 
2450                            (save-excursion
2451                              (forward-char -1)
2452                              (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\>"
2453                                                 nil t)))) ; Only one
2454                      (progn 
2455                        (forward-sexp 1)
2456                        (setq name (file-name-sans-extension
2457                                    (file-name-nondirectory (buffer-file-name)))
2458                              p (point))
2459                        (insert " NAME\n\n" name 
2460                                " - \n\n=head1 SYNOPSYS\n\n\n\n"
2461                                "=head1 DESCRIPTION")
2462                        (cperl-ensure-newlines 4)
2463                        (goto-char p)
2464                        (forward-sexp 2)
2465                        (end-of-line)
2466                        (setq really-delete t))
2467                    (forward-sexp 1))))
2468            (if over
2469                (progn
2470                  (setq p (point))
2471                  (insert "\n\n=item \n\n\n\n"
2472                          "=back")
2473                  (cperl-ensure-newlines 2)
2474                  (goto-char p)
2475                  (forward-sexp 1)
2476                  (end-of-line)
2477                  (setq really-delete t)))
2478            (if (and delete really-delete)
2479                (cperl-putback-char cperl-del-back-ch))))))
2480
2481 (defun cperl-electric-else ()
2482   "Insert a construction appropriate after a keyword.
2483 Help message may be switched off by setting `cperl-message-electric-keyword'
2484 to nil."
2485   (let ((beg (save-excursion (beginning-of-line) (point))))
2486     (and (save-excursion
2487            (backward-sexp 1)
2488            (cperl-after-expr-p nil "{;:"))
2489          (save-excursion 
2490            (not 
2491             (re-search-backward
2492              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
2493              beg t)))
2494          (save-excursion (or (not (re-search-backward "^=" nil t))
2495                              (looking-at "=cut")
2496                              (and cperl-use-syntax-table-text-property
2497                                   (not (eq (get-text-property (point)
2498                                                               'syntax-type)
2499                                            'pod)))))
2500          (progn
2501            (cperl-indent-line)
2502            ;;(insert " {\n\n}")
2503            (cond
2504             (cperl-extra-newline-before-brace
2505              (insert "\n")
2506              (insert "{")
2507              (cperl-indent-line)
2508              (insert "\n\n}"))
2509             (t
2510              (insert " {\n\n}"))
2511             )
2512            (or (looking-at "[ \t]\\|$") (insert " "))
2513            (cperl-indent-line)
2514            (forward-line -1)
2515            (cperl-indent-line)
2516            (cperl-putback-char cperl-del-back-ch)
2517            (setq this-command 'cperl-electric-else)
2518            (if cperl-message-electric-keyword
2519                (message "Precede char by C-q to avoid expansion"))))))
2520
2521 (defun cperl-linefeed ()
2522   "Go to end of line, open a new line and indent appropriately.
2523 If in POD, insert appropriate lines."
2524   (interactive)
2525   (let ((beg (save-excursion (beginning-of-line) (point)))
2526         (end (save-excursion (end-of-line) (point)))
2527         (pos (point)) start over cut res)
2528     (if (and                            ; Check if we need to split:
2529                                         ; i.e., on a boundary and inside "{...}" 
2530          (save-excursion (cperl-to-comment-or-eol)
2531            (>= (point) pos))            ; Not in a comment
2532          (or (save-excursion
2533                (skip-chars-backward " \t" beg)
2534                (forward-char -1)
2535                (looking-at "[;{]"))     ; After { or ; + spaces
2536              (looking-at "[ \t]*}")     ; Before }
2537              (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
2538          (save-excursion
2539            (and
2540             (eq (car (parse-partial-sexp pos end -1)) -1) 
2541                                         ; Leave the level of parens
2542             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
2543                                         ; Are at end
2544             (progn
2545               (backward-sexp 1)
2546               (setq start (point-marker))
2547               (<= start pos)))))        ; Redundant?  Are after the
2548                                         ; start of parens group.
2549         (progn
2550           (skip-chars-backward " \t")
2551           (or (memq (preceding-char) (append ";{" nil))
2552               (insert ";"))
2553           (insert "\n")
2554           (forward-line -1)
2555           (cperl-indent-line)
2556           (goto-char start)
2557           (or (looking-at "{[ \t]*$")   ; If there is a statement
2558                                         ; before, move it to separate line
2559               (progn
2560                 (forward-char 1)
2561                 (insert "\n")
2562                 (cperl-indent-line)))
2563           (forward-line 1)              ; We are on the target line
2564           (cperl-indent-line)
2565           (beginning-of-line)
2566           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
2567                                             ; after, move it to separate line
2568               (progn
2569                 (end-of-line)
2570                 (search-backward "}" beg)
2571                 (skip-chars-backward " \t")
2572                 (or (memq (preceding-char) (append ";{" nil))
2573                     (insert ";"))
2574                 (insert "\n")
2575                 (cperl-indent-line)
2576                 (forward-line -1)))
2577           (forward-line -1)             ; We are on the line before target 
2578           (end-of-line)
2579           (newline-and-indent))
2580       (end-of-line)                     ; else - no splitting
2581       (cond
2582        ((and (looking-at "\n[ \t]*{$")
2583              (save-excursion
2584                (skip-chars-backward " \t")
2585                (eq (preceding-char) ?\)))) ; Probably if () {} group
2586                                            ; with an extra newline.
2587         (forward-line 2)
2588         (cperl-indent-line))
2589        ((save-excursion                 ; In POD header
2590           (forward-paragraph -1)
2591           ;; (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\b")
2592           ;; We are after \n now, so look for the rest
2593           (if (looking-at "\\(\\`\n?\\|\n\\)=\\sw+")
2594               (progn 
2595                 (setq cut (looking-at "\\(\\`\n?\\|\n\\)=cut\\>"))
2596                 (setq over (looking-at "\\(\\`\n?\\|\n\\)=over\\>"))
2597                 t)))
2598         (if (and over
2599                  (progn
2600                    (forward-paragraph -1)
2601                    (forward-word 1)
2602                    (setq pos (point))
2603                    (setq cut (buffer-substring (point)
2604                                                (save-excursion
2605                                                  (end-of-line)
2606                                                  (point))))
2607                    (delete-char (- (save-excursion (end-of-line) (point))
2608                                    (point)))
2609                    (setq res (expand-abbrev))
2610                    (save-excursion
2611                      (goto-char pos)
2612                      (insert cut))
2613                    res))
2614             nil
2615           (cperl-ensure-newlines (if cut 2 4))
2616           (forward-line 2)))
2617        ((get-text-property (point) 'in-pod) ; In POD section
2618         (cperl-ensure-newlines 4)
2619         (forward-line 2))
2620        ((looking-at "\n[ \t]*$")        ; Next line is empty - use it.
2621         (forward-line 1)
2622         (cperl-indent-line))
2623        (t
2624         (newline-and-indent))))))
2625
2626 (defun cperl-electric-semi (arg)
2627   "Insert character and correct line's indentation."
2628   (interactive "P")
2629   (if cperl-auto-newline
2630       (cperl-electric-terminator arg)
2631     (self-insert-command (prefix-numeric-value arg))))
2632
2633 (defun cperl-electric-terminator (arg)
2634   "Insert character and correct line's indentation."
2635   (interactive "P")
2636   (let (insertpos (end (point)) 
2637                   (auto (and cperl-auto-newline
2638                              (or (not (eq last-command-char ?:))
2639                                  cperl-auto-newline-after-colon))))
2640     (if (and ;;(not arg) 
2641              (eolp)
2642              (not (save-excursion
2643                     (beginning-of-line)
2644                     (skip-chars-forward " \t")
2645                     (or
2646                      ;; Ignore in comment lines
2647                      (= (following-char) ?#)
2648                      ;; Colon is special only after a label
2649                      ;; So quickly rule out most other uses of colon
2650                      ;; and do no indentation for them.
2651                      (and (eq last-command-char ?:)
2652                           (save-excursion
2653                             (forward-word 1)
2654                             (skip-chars-forward " \t")
2655                             (and (< (point) end)
2656                                  (progn (goto-char (- end 1))
2657                                         (not (looking-at ":"))))))
2658                      (progn
2659                        (beginning-of-defun)
2660                        (let ((pps (parse-partial-sexp (point) end)))
2661                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
2662         (progn
2663           (self-insert-command (prefix-numeric-value arg))
2664           ;;(forward-char -1)
2665           (if auto (setq insertpos (point-marker)))
2666           ;;(forward-char 1)
2667           (cperl-indent-line)
2668           (if auto
2669               (progn
2670                 (newline)
2671                 (cperl-indent-line)))
2672           (save-excursion
2673             (if insertpos (goto-char (1- (marker-position insertpos)))
2674               (forward-char -1))
2675             (delete-char 1))))
2676     (if insertpos
2677         (save-excursion
2678           (goto-char insertpos)
2679           (self-insert-command (prefix-numeric-value arg)))
2680       (self-insert-command (prefix-numeric-value arg)))))
2681
2682 (defun cperl-electric-backspace (arg)
2683   "Backspace-untabify, or remove the whitespace around the point inserted 
2684 by an electric key."
2685   (interactive "p")
2686   (if (and cperl-auto-newline 
2687            (memq last-command '(cperl-electric-semi 
2688                                 cperl-electric-terminator
2689                                 cperl-electric-lbrace))
2690            (memq (preceding-char) '(?\  ?\t ?\n)))
2691       (let (p)
2692         (if (eq last-command 'cperl-electric-lbrace) 
2693             (skip-chars-forward " \t\n"))
2694         (setq p (point))
2695         (skip-chars-backward " \t\n")
2696         (delete-region (point) p))
2697     (and (eq last-command 'cperl-electric-else)
2698          ;; We are removing the whitespace *inside* cperl-electric-else
2699          (setq this-command 'cperl-electric-else-really))
2700     (if (and cperl-auto-newline 
2701              (eq last-command 'cperl-electric-else-really)
2702              (memq (preceding-char) '(?\  ?\t ?\n)))
2703         (let (p)
2704           (skip-chars-forward " \t\n")
2705           (setq p (point))
2706           (skip-chars-backward " \t\n")
2707           (delete-region (point) p))
2708       (backward-delete-char-untabify arg))))
2709
2710 (defun cperl-inside-parens-p ()
2711   (condition-case ()
2712       (save-excursion
2713         (save-restriction
2714           (narrow-to-region (point)
2715                             (progn (beginning-of-defun) (point)))
2716           (goto-char (point-max))
2717           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
2718     (error nil)))
2719 \f
2720 (defun cperl-indent-command (&optional whole-exp)
2721   "Indent current line as Perl code, or in some cases insert a tab character.
2722 If `cperl-tab-always-indent' is non-nil (the default), always indent current 
2723 line.  Otherwise, indent the current line only if point is at the left margin
2724 or in the line's indentation; otherwise insert a tab.
2725
2726 A numeric argument, regardless of its value,
2727 means indent rigidly all the lines of the expression starting after point
2728 so that this line becomes properly indented.
2729 The relative indentation among the lines of the expression are preserved."
2730   (interactive "P")
2731   (cperl-update-syntaxification (point) (point))
2732   (if whole-exp
2733       ;; If arg, always indent this line as Perl
2734       ;; and shift remaining lines of expression the same amount.
2735       (let ((shift-amt (cperl-indent-line))
2736             beg end)
2737         (save-excursion
2738           (if cperl-tab-always-indent
2739               (beginning-of-line))
2740           (setq beg (point))
2741           (forward-sexp 1)
2742           (setq end (point))
2743           (goto-char beg)
2744           (forward-line 1)
2745           (setq beg (point)))
2746         (if (and shift-amt (> end beg))
2747             (indent-code-rigidly beg end shift-amt "#")))
2748     (if (and (not cperl-tab-always-indent)
2749              (save-excursion
2750                (skip-chars-backward " \t")
2751                (not (bolp))))
2752         (insert-tab)
2753       (cperl-indent-line))))
2754
2755 (defun cperl-indent-line (&optional parse-data)
2756   "Indent current line as Perl code.
2757 Return the amount the indentation changed by."
2758   (let (indent i beg shift-amt
2759         (case-fold-search nil)
2760         (pos (- (point-max) (point))))
2761     (setq indent (cperl-calculate-indent parse-data)
2762           i indent)
2763     (beginning-of-line)
2764     (setq beg (point))
2765     (cond ((or (eq indent nil) (eq indent t))
2766            (setq indent (current-indentation) i nil))
2767           ;;((eq indent t)    ; Never?
2768           ;; (setq indent (cperl-calculate-indent-within-comment)))
2769           ;;((looking-at "[ \t]*#")
2770           ;; (setq indent 0))
2771           (t
2772            (skip-chars-forward " \t")
2773            (if (listp indent) (setq indent (car indent)))
2774            (cond ((looking-at "[A-Za-z_][A-Za-z_0-9]*:[^:]")
2775                   (and (> indent 0)
2776                        (setq indent (max cperl-min-label-indent
2777                                          (+ indent cperl-label-offset)))))
2778                  ((= (following-char) ?})
2779                   (setq indent (- indent cperl-indent-level)))
2780                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
2781                   (setq indent (+ indent cperl-close-paren-offset)))
2782                  ((= (following-char) ?{)
2783                   (setq indent (+ indent cperl-brace-offset))))))
2784     (skip-chars-forward " \t")
2785     (setq shift-amt (and i (- indent (current-column))))
2786     (if (or (not shift-amt)
2787             (zerop shift-amt))
2788         (if (> (- (point-max) pos) (point))
2789             (goto-char (- (point-max) pos)))
2790       (delete-region beg (point))
2791       (indent-to indent)
2792       ;; If initial point was within line's indentation,
2793       ;; position after the indentation.  Else stay at same point in text.
2794       (if (> (- (point-max) pos) (point))
2795           (goto-char (- (point-max) pos))))
2796     shift-amt))
2797
2798 (defun cperl-after-label ()
2799   ;; Returns true if the point is after label.  Does not do save-excursion.
2800   (and (eq (preceding-char) ?:)
2801        (memq (char-syntax (char-after (- (point) 2)))
2802              '(?w ?_))
2803        (progn
2804          (backward-sexp)
2805          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))
2806
2807 (defun cperl-get-state (&optional parse-start start-state)
2808   ;; returns list (START STATE DEPTH PRESTART), START is a good place
2809   ;; to start parsing, STATE is what is returned by
2810   ;; `parse-partial-sexp'.  DEPTH is true is we are immediately after
2811   ;; end of block which contains START.  PRESTART is the position
2812   ;; basing on which START was found.
2813   (save-excursion
2814     (let ((start-point (point)) depth state start prestart)
2815       (if (and parse-start
2816                (<= parse-start start-point))
2817           (goto-char parse-start)
2818         (beginning-of-defun)
2819         (setq start-state nil))
2820       (setq prestart (point))
2821       (if start-state nil
2822         ;; Try to go out, if sub is not on the outermost level
2823         (while (< (point) start-point)
2824           (setq start (point) parse-start start depth nil
2825                 state (parse-partial-sexp start start-point -1))
2826           (if (> (car state) -1) nil
2827             ;; The current line could start like }}}, so the indentation
2828             ;; corresponds to a different level than what we reached
2829             (setq depth t)
2830             (beginning-of-line 2)))     ; Go to the next line.
2831         (if start (goto-char start)))   ; Not at the start of file
2832       (setq start (point))
2833       (if (< start start-point) (setq parse-start start))
2834       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
2835       (list start state depth prestart))))
2836
2837 (defun cperl-block-p ()                 ; Do not C-M-q !  One string contains ";" !
2838   ;; Positions is before ?\{.  Checks whether it starts a block.
2839   ;; No save-excursion!
2840   (cperl-backward-to-noncomment (point-min))
2841   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label!  \C-@ at bobp
2842                                         ; Label may be mixed up with `$blah :'
2843       (save-excursion (cperl-after-label))
2844       (and (memq (char-syntax (preceding-char)) '(?w ?_))
2845            (progn
2846              (backward-sexp)
2847              ;; Need take into account `bless', `return', `tr',...
2848              (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
2849                       (not (looking-at "\\(bless\\|return\\|qw\\|tr\\|[smy]\\)\\>")))
2850                  (progn
2851                    (skip-chars-backward " \t\n\f")
2852                    (and (memq (char-syntax (preceding-char)) '(?w ?_))
2853                         (progn
2854                           (backward-sexp)
2855                           (looking-at 
2856                            "sub[ \t]+[a-zA-Z0-9_:]+[ \t\n\f]*\\(([^()]*)[ \t\n\f]*\\)?[#{]")))))))))
2857
2858 (defvar cperl-look-for-prop '((pod in-pod) (here-doc-delim here-doc-group)))
2859
2860 (defun cperl-calculate-indent (&optional parse-data) ; was parse-start
2861   "Return appropriate indentation for current line as Perl code.
2862 In usual case returns an integer: the column to indent to.
2863 Returns nil if line starts inside a string, t if in a comment."
2864   (save-excursion
2865     (if (or
2866          (memq (get-text-property (point) 'syntax-type) 
2867                '(pod here-doc here-doc-delim format))
2868          ;; before start of POD - whitespace found since do not have 'pod!
2869          (and (looking-at "[ \t]*\n=")
2870               (error "Spaces before pod section!"))
2871          (and (not cperl-indent-left-aligned-comments)
2872               (looking-at "^#")))
2873         nil
2874      (beginning-of-line)
2875      (let ((indent-point (point))
2876            (char-after (save-excursion
2877                            (skip-chars-forward " \t")
2878                            (following-char)))
2879            (in-pod (get-text-property (point) 'in-pod))
2880            (pre-indent-point (point))
2881            p prop look-prop)
2882       (cond
2883        (in-pod                          
2884         ;; In the verbatim part, probably code example.  What to do???
2885         )
2886        (t 
2887         (save-excursion
2888           ;; Not in pod
2889           (cperl-backward-to-noncomment nil)
2890           (setq p (max (point-min) (1- (point)))
2891                 prop (get-text-property p 'syntax-type)
2892                 look-prop (or (nth 1 (assoc prop cperl-look-for-prop))
2893                               'syntax-type))
2894           (if (memq prop '(pod here-doc format here-doc-delim))
2895               (progn
2896                 (goto-char (or (previous-single-property-change p look-prop) 
2897                                (point-min)))
2898                 (beginning-of-line)
2899                 (setq pre-indent-point (point)))))))
2900       (goto-char pre-indent-point)
2901       (let* ((case-fold-search nil)
2902              (s-s (cperl-get-state (car parse-data) (nth 1 parse-data)))
2903              (start (nth 0 s-s))
2904              (state (nth 1 s-s))
2905              (containing-sexp (car (cdr state)))
2906              (start-indent (save-excursion
2907                              (goto-char start)
2908                              (- (current-indentation)
2909                                 (if (nth 2 s-s) cperl-indent-level 0))))
2910              old-indent)
2911         (if parse-data
2912             (progn
2913               (setcar parse-data pre-indent-point)
2914               (setcar (cdr parse-data) state)))
2915         ;;      (or parse-start (null symbol)
2916         ;;        (setq parse-start (symbol-value symbol) 
2917         ;;              start-indent (nth 2 parse-start) 
2918         ;;              parse-start (car parse-start)))
2919         ;;      (if parse-start
2920         ;;        (goto-char parse-start)
2921         ;;      (beginning-of-defun))
2922         ;;      ;; Try to go out
2923         ;;      (while (< (point) indent-point)
2924         ;;      (setq start (point) parse-start start moved nil
2925         ;;            state (parse-partial-sexp start indent-point -1))
2926         ;;      (if (> (car state) -1) nil
2927         ;;        ;; The current line could start like }}}, so the indentation
2928         ;;        ;; corresponds to a different level than what we reached
2929         ;;        (setq moved t)
2930         ;;        (beginning-of-line 2)))       ; Go to the next line.
2931         ;;      (if start                               ; Not at the start of file
2932         ;;        (progn
2933         ;;          (goto-char start)
2934         ;;          (setq start-indent (current-indentation))
2935         ;;          (if moved                   ; Should correct...
2936         ;;              (setq start-indent (- start-indent cperl-indent-level))))
2937         ;;      (setq start-indent 0))
2938         ;;      (if (< (point) indent-point) (setq parse-start (point)))
2939         ;;      (or state (setq state (parse-partial-sexp 
2940         ;;                           (point) indent-point -1 nil start-state)))
2941         ;;      (setq containing-sexp 
2942         ;;          (or (car (cdr state)) 
2943         ;;              (and (>= (nth 6 state) 0) old-containing-sexp))
2944         ;;          old-containing-sexp nil start-state nil)
2945 ;;;;      (while (< (point) indent-point)
2946 ;;;;    (setq parse-start (point))
2947 ;;;;    (setq state (parse-partial-sexp (point) indent-point -1 nil start-state))
2948 ;;;;    (setq containing-sexp 
2949 ;;;;          (or (car (cdr state)) 
2950 ;;;;              (and (>= (nth 6 state) 0) old-containing-sexp))
2951 ;;;;          old-containing-sexp nil start-state nil))
2952         ;;      (if symbol (set symbol (list indent-point state start-indent)))
2953         ;;      (goto-char indent-point)
2954         (cond ((or (nth 3 state) (nth 4 state))
2955                ;; return nil or t if should not change this line
2956                (nth 4 state))
2957               ((null containing-sexp)
2958                ;; Line is at top level.  May be data or function definition,
2959                ;; or may be function argument declaration.
2960                ;; Indent like the previous top level line
2961                ;; unless that ends in a closeparen without semicolon,
2962                ;; in which case this line is the first argument decl.
2963                (skip-chars-forward " \t")
2964                (+ start-indent
2965                   (if (= (following-char) ?{) cperl-continued-brace-offset 0)
2966                   (progn
2967                     (cperl-backward-to-noncomment (or (car parse-data) (point-min)))
2968                     ;; Look at previous line that's at column 0
2969                     ;; to determine whether we are in top-level decls
2970                     ;; or function's arg decls.  Set basic-indent accordingly.
2971                     ;; Now add a little if this is a continuation line.
2972                     (if (or (bobp)
2973                             (eq (preceding-char) ?\;)
2974                             ;;  Had ?\) too
2975                             (and (eq (preceding-char) ?\})
2976                                  (cperl-after-block-and-statement-beg start))
2977                             (memq char-after (append ")]}" nil))
2978                             (and (eq (preceding-char) ?\:) ; label
2979                                  (progn
2980                                    (forward-sexp -1)
2981                                    (skip-chars-backward " \t")
2982                                    (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*[ \t]*:")))) 
2983                         0
2984                       cperl-continued-statement-offset))))
2985               ((/= (char-after containing-sexp) ?{)
2986                ;; line is expression, not statement:
2987                ;; indent to just after the surrounding open,
2988                ;; skip blanks if we do not close the expression.
2989                (goto-char (1+ containing-sexp))
2990                (or (memq char-after (append ")]}" nil))
2991                    (looking-at "[ \t]*\\(#\\|$\\)")
2992                    (skip-chars-forward " \t"))
2993                (current-column))
2994               ((progn
2995                  ;; Containing-expr starts with \{.  Check whether it is a hash.
2996                  (goto-char containing-sexp)
2997                  (not (cperl-block-p)))
2998                (goto-char (1+ containing-sexp))
2999                (or (eq char-after ?\})
3000                    (looking-at "[ \t]*\\(#\\|$\\)")
3001                    (skip-chars-forward " \t"))
3002                (+ (current-column)      ; Correct indentation of trailing ?\}
3003                   (if (eq char-after ?\}) (+ cperl-indent-level
3004                                              cperl-close-paren-offset) 
3005                     0)))
3006               (t
3007                ;; Statement level.  Is it a continuation or a new statement?
3008                ;; Find previous non-comment character.
3009                (goto-char pre-indent-point)
3010                (cperl-backward-to-noncomment containing-sexp)
3011                ;; Back up over label lines, since they don't
3012                ;; affect whether our line is a continuation.
3013                (while (or (eq (preceding-char) ?\,)
3014                           (and (eq (preceding-char) ?:)
3015                                (or;;(eq (char-after (- (point) 2)) ?\') ; ????
3016                                 (memq (char-syntax (char-after (- (point) 2)))
3017                                       '(?w ?_)))))
3018                  (if (eq (preceding-char) ?\,)
3019                      ;; Will go to beginning of line, essentially.
3020                      ;; Will ignore embedded sexpr XXXX.
3021                      (cperl-backward-to-start-of-continued-exp containing-sexp))
3022                  (beginning-of-line)
3023                  (cperl-backward-to-noncomment containing-sexp))
3024                ;; Now we get the answer.
3025                ;; Had \?, too:
3026                (if (not (or (memq (preceding-char) (append " ;{" '(nil)))
3027                             (and (eq (preceding-char) ?\})
3028                                  (cperl-after-block-and-statement-beg 
3029                                   containing-sexp)))) ; Was ?\,
3030                    ;; This line is continuation of preceding line's statement;
3031                    ;; indent  `cperl-continued-statement-offset'  more than the
3032                    ;; previous line of the statement.
3033                    (progn
3034                      (cperl-backward-to-start-of-continued-exp containing-sexp)
3035                      (+ (if (memq char-after (append "}])" nil))
3036                             0           ; Closing parenth
3037                           cperl-continued-statement-offset)
3038                         (current-column)
3039                         (if (eq char-after ?\{)
3040                             cperl-continued-brace-offset 0)))
3041                  ;; This line starts a new statement.
3042                  ;; Position following last unclosed open.
3043                  (goto-char containing-sexp)
3044                  ;; Is line first statement after an open-brace?
3045                  (or
3046                   ;; If no, find that first statement and indent like
3047                   ;; it.  If the first statement begins with label, do
3048                   ;; not believe when the indentation of the label is too
3049                   ;; small.
3050                   (save-excursion
3051                     (forward-char 1)
3052                     (setq old-indent (current-indentation))
3053                     (let ((colon-line-end 0))
3054                       (while (progn (skip-chars-forward " \t\n")
3055                                     (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]"))
3056                         ;; Skip over comments and labels following openbrace.
3057                         (cond ((= (following-char) ?\#)
3058                                (forward-line 1))
3059                               ;; label:
3060                               (t
3061                                (save-excursion (end-of-line)
3062                                                (setq colon-line-end (point)))
3063                                (search-forward ":"))))
3064                       ;; The first following code counts
3065                       ;; if it is before the line we want to indent.
3066                       (and (< (point) indent-point)
3067                            (if (> colon-line-end (point)) ; After label
3068                                (if (> (current-indentation) 
3069                                       cperl-min-label-indent)
3070                                    (- (current-indentation) cperl-label-offset)
3071                                  ;; Do not believe: `max' is involved
3072                                  (+ old-indent cperl-indent-level))
3073                              (current-column)))))
3074                   ;; If no previous statement,
3075                   ;; indent it relative to line brace is on.
3076                   ;; For open brace in column zero, don't let statement
3077                   ;; start there too.  If cperl-indent-level is zero,
3078                   ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
3079                   ;; For open-braces not the first thing in a line,
3080                   ;; add in cperl-brace-imaginary-offset.
3081
3082                   ;; If first thing on a line:  ?????
3083                   (+ (if (and (bolp) (zerop cperl-indent-level))
3084                          (+ cperl-brace-offset cperl-continued-statement-offset)
3085                        cperl-indent-level)
3086                      ;; Move back over whitespace before the openbrace.
3087                      ;; If openbrace is not first nonwhite thing on the line,
3088                      ;; add the cperl-brace-imaginary-offset.
3089                      (progn (skip-chars-backward " \t")
3090                             (if (bolp) 0 cperl-brace-imaginary-offset))
3091                      ;; If the openbrace is preceded by a parenthesized exp,
3092                      ;; move to the beginning of that;
3093                      ;; possibly a different line
3094                      (progn
3095                        (if (eq (preceding-char) ?\))
3096                            (forward-sexp -1))
3097                        ;; In the case it starts a subroutine, indent with
3098                        ;; respect to `sub', not with respect to the the
3099                        ;; first thing on the line, say in the case of
3100                        ;; anonymous sub in a hash.
3101                        ;;
3102                        (skip-chars-backward " \t")
3103                        (if (and (eq (preceding-char) ?b)
3104                                 (progn
3105                                   (forward-sexp -1)
3106                                   (looking-at "sub\\>"))
3107                                 (setq old-indent 
3108                                       (nth 1 
3109                                            (parse-partial-sexp 
3110                                             (save-excursion (beginning-of-line) (point)) 
3111                                             (point)))))
3112                            (progn (goto-char (1+ old-indent))
3113                                   (skip-chars-forward " \t")
3114                                   (current-column))
3115                          ;; Get initial indentation of the line we are on.
3116                          ;; If line starts with label, calculate label indentation
3117                          (if (save-excursion
3118                                (beginning-of-line)
3119                                (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
3120                              (if (> (current-indentation) cperl-min-label-indent)
3121                                  (- (current-indentation) cperl-label-offset)
3122                                ;; Do not move `parse-data', this should
3123                                ;; be quick anyway:
3124                                (cperl-calculate-indent))
3125                            (current-indentation))))))))))))))
3126
3127 (defvar cperl-indent-alist
3128   '((string nil)
3129     (comment nil)
3130     (toplevel 0)
3131     (toplevel-after-parenth 2)
3132     (toplevel-continued 2)
3133     (expression 1))
3134   "Alist of indentation rules for CPerl mode.
3135 The values mean:
3136   nil: do not indent;
3137   number: add this amount of indentation.
3138
3139 Not finished, not used.")
3140
3141 (defun cperl-where-am-i (&optional parse-start start-state)
3142   ;; Unfinished
3143   "Return a list of lists ((TYPE POS)...) of good points before the point.
3144 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'.
3145
3146 Not finished, not used."
3147   (save-excursion
3148     (let* ((start-point (point))
3149            (s-s (cperl-get-state))
3150            (start (nth 0 s-s))
3151            (state (nth 1 s-s))
3152            (prestart (nth 3 s-s))
3153            (containing-sexp (car (cdr state)))
3154            (case-fold-search nil)
3155            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
3156       (cond ((nth 3 state)              ; In string
3157              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
3158             ((nth 4 state)              ; In comment
3159              (setq res (cons '(comment) res)))
3160             ((null containing-sexp)
3161              ;; Line is at top level.  
3162              ;; Indent like the previous top level line
3163              ;; unless that ends in a closeparen without semicolon,
3164              ;; in which case this line is the first argument decl.
3165              (cperl-backward-to-noncomment (or parse-start (point-min)))
3166              ;;(skip-chars-backward " \t\f\n")
3167              (cond
3168               ((or (bobp)
3169                    (memq (preceding-char) (append ";}" nil)))
3170                (setq res (cons (list 'toplevel start) res)))
3171               ((eq (preceding-char) ?\) )
3172                (setq res (cons (list 'toplevel-after-parenth start) res)))
3173               (t 
3174                (setq res (cons (list 'toplevel-continued start) res)))))
3175             ((/= (char-after containing-sexp) ?{)
3176              ;; line is expression, not statement:
3177              ;; indent to just after the surrounding open.
3178              ;; skip blanks if we do not close the expression.
3179              (setq res (cons (list 'expression-blanks
3180                                    (progn
3181                                      (goto-char (1+ containing-sexp))
3182                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
3183                                          (skip-chars-forward " \t"))
3184                                      (point)))
3185                              (cons (list 'expression containing-sexp) res))))
3186             ((progn
3187               ;; Containing-expr starts with \{.  Check whether it is a hash.
3188               (goto-char containing-sexp)
3189               (not (cperl-block-p)))
3190              (setq res (cons (list 'expression-blanks
3191                                    (progn
3192                                      (goto-char (1+ containing-sexp))
3193                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
3194                                          (skip-chars-forward " \t"))
3195                                      (point)))
3196                              (cons (list 'expression containing-sexp) res))))
3197             (t
3198              ;; Statement level.
3199              (setq res (cons (list 'in-block containing-sexp) res))
3200              ;; Is it a continuation or a new statement?
3201              ;; Find previous non-comment character.
3202              (cperl-backward-to-noncomment containing-sexp)
3203              ;; Back up over label lines, since they don't
3204              ;; affect whether our line is a continuation.
3205              ;; Back up comma-delimited lines too ?????
3206              (while (or (eq (preceding-char) ?\,)
3207                         (save-excursion (cperl-after-label)))
3208                (if (eq (preceding-char) ?\,)
3209                    ;; Will go to beginning of line, essentially
3210                      ;; Will ignore embedded sexpr XXXX.
3211                    (cperl-backward-to-start-of-continued-exp containing-sexp))
3212                (beginning-of-line)
3213                (cperl-backward-to-noncomment containing-sexp))
3214              ;; Now we get the answer.
3215              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
3216                  ;; This line is continuation of preceding line's statement.
3217                  (list (list 'statement-continued containing-sexp))
3218                ;; This line starts a new statement.
3219                ;; Position following last unclosed open.
3220                (goto-char containing-sexp)
3221                ;; Is line first statement after an open-brace?
3222                (or
3223                 ;; If no, find that first statement and indent like
3224                 ;; it.  If the first statement begins with label, do
3225                 ;; not believe when the indentation of the label is too
3226                 ;; small.
3227                 (save-excursion
3228                   (forward-char 1)
3229                   (let ((colon-line-end 0))
3230                     (while (progn (skip-chars-forward " \t\n" start-point)
3231                                   (and (< (point) start-point)
3232                                        (looking-at
3233                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
3234                       ;; Skip over comments and labels following openbrace.
3235                       (cond ((= (following-char) ?\#)
3236                              ;;(forward-line 1)
3237                              (end-of-line))
3238                             ;; label:
3239                             (t
3240                              (save-excursion (end-of-line)
3241                                              (setq colon-line-end (point)))
3242                              (search-forward ":"))))
3243                     ;; Now at the point, after label, or at start 
3244                     ;; of first statement in the block.
3245                     (and (< (point) start-point)
3246                          (if (> colon-line-end (point)) 
3247                              ;; Before statement after label
3248                              (if (> (current-indentation) 
3249                                     cperl-min-label-indent)
3250                                  (list (list 'label-in-block (point)))
3251                                ;; Do not believe: `max' is involved
3252                                (list
3253                                 (list 'label-in-block-min-indent (point))))
3254                            ;; Before statement
3255                            (list 'statement-in-block (point))))))
3256                 ;; If no previous statement,
3257                 ;; indent it relative to line brace is on.
3258                 ;; For open brace in column zero, don't let statement
3259                 ;; start there too.  If cperl-indent-level is zero,
3260                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
3261                 ;; For open-braces not the first thing in a line,
3262                 ;; add in cperl-brace-imaginary-offset.
3263
3264                 ;; If first thing on a line:  ?????
3265                 (+ (if (and (bolp) (zerop cperl-indent-level))
3266                        (+ cperl-brace-offset cperl-continued-statement-offset)
3267                      cperl-indent-level)
3268                    ;; Move back over whitespace before the openbrace.
3269                    ;; If openbrace is not first nonwhite thing on the line,
3270                    ;; add the cperl-brace-imaginary-offset.
3271                    (progn (skip-chars-backward " \t")
3272                           (if (bolp) 0 cperl-brace-imaginary-offset))
3273                    ;; If the openbrace is preceded by a parenthesized exp,
3274                    ;; move to the beginning of that;
3275                    ;; possibly a different line
3276                    (progn
3277                      (if (eq (preceding-char) ?\))
3278                          (forward-sexp -1))
3279                      ;; Get initial indentation of the line we are on.
3280                      ;; If line starts with label, calculate label indentation
3281                      (if (save-excursion
3282                            (beginning-of-line)
3283                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
3284                          (if (> (current-indentation) cperl-min-label-indent)
3285                              (- (current-indentation) cperl-label-offset)
3286                            (cperl-calculate-indent))
3287                        (current-indentation))))))))
3288       res)))
3289
3290 (defun cperl-calculate-indent-within-comment ()
3291   "Return the indentation amount for line, assuming that
3292 the current line is to be regarded as part of a block comment."
3293   (let (end star-start)
3294     (save-excursion
3295       (beginning-of-line)
3296       (skip-chars-forward " \t")
3297       (setq end (point))
3298       (and (= (following-char) ?#)
3299            (forward-line -1)
3300            (cperl-to-comment-or-eol)
3301            (setq end (point)))
3302       (goto-char end)
3303       (current-column))))
3304
3305
3306 (defun cperl-to-comment-or-eol ()
3307   "Goes to position before comment on the current line, or to end of line.
3308 Returns true if comment is found."
3309   (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
3310       (beginning-of-line)
3311       (if (or 
3312            (eq (get-text-property (point) 'syntax-type) 'pod)
3313            (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t))
3314           (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
3315         ;; Else
3316         (while (not stop-in)
3317           (setq state (parse-partial-sexp (point) lim nil nil nil t))
3318                                         ; stop at comment
3319           ;; If fails (beginning-of-line inside sexp), then contains not-comment
3320           (if (nth 4 state)             ; After `#';
3321                                         ; (nth 2 state) can be
3322                                         ; beginning of m,s,qq and so
3323                                         ; on
3324               (if (nth 2 state)
3325                   (progn
3326                     (setq cpoint (point))
3327                     (goto-char (nth 2 state))
3328                     (cond
3329                      ((looking-at "\\(s\\|tr\\)\\>")
3330                       (or (re-search-forward
3331                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
3332                            lim 'move)
3333                           (setq stop-in t)))
3334                      ((looking-at "\\(m\\|q\\([qxw]\\)?\\)\\>")
3335                       (or (re-search-forward
3336                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
3337                            lim 'move)
3338                           (setq stop-in t)))
3339                      (t                 ; It was fair comment
3340                       (setq stop-in t)  ; Finish
3341                       (goto-char (1- cpoint)))))
3342                 (setq stop-in t)        ; Finish
3343                 (forward-char -1))
3344             (setq stop-in t))           ; Finish
3345           )
3346         (nth 4 state))))
3347
3348 (defsubst cperl-1- (p)
3349   (max (point-min) (1- p)))
3350
3351 (defsubst cperl-1+ (p)
3352   (min (point-max) (1+ p)))
3353
3354 (defvar cperl-st-cfence '(14))          ; Comment-fence
3355 (defvar cperl-st-sfence '(15))          ; String-fence
3356 (defvar cperl-st-punct '(1))
3357 (defvar cperl-st-word '(2))
3358 (defvar cperl-st-bra '(4 . ?\>))
3359 (defvar cperl-st-ket '(5 . ?\<))
3360
3361 (defsubst cperl-modify-syntax-type (at how)
3362   (if (< at (point-max))
3363       (progn
3364         (put-text-property at (1+ at) 'syntax-table how)
3365         (put-text-property at (1+ at) 'rear-nonsticky t))))
3366
3367 (defun cperl-protect-defun-start (s e)
3368   ;; C code looks for "^\\s(" to skip comment backward in "hard" situations
3369   (save-excursion
3370     (goto-char s)
3371     (while (re-search-forward "^\\s(" e 'to-end)
3372       (put-text-property (1- (point)) (point) 'syntax-table cperl-st-punct))))
3373
3374 (defun cperl-commentify (bb e string)
3375   (if cperl-use-syntax-table-text-property 
3376       (progn
3377         ;; We suppose that e is _after_ the end of construction, as after eol.
3378         (setq string (if string cperl-st-sfence cperl-st-cfence))
3379         (cperl-modify-syntax-type bb string)
3380         (cperl-modify-syntax-type (1- e) string)
3381         (if (and (eq string cperl-st-sfence) (> (- e 2) bb))
3382             (put-text-property (1+ bb) (1- e) 
3383                                'syntax-table cperl-string-syntax-table))
3384         (cperl-protect-defun-start bb e))))
3385
3386 (defun cperl-forward-re (lim end is-2arg set-st st-l err-l argument
3387                              &optional ostart oend)
3388   ;; Works *before* syntax recognition is done
3389   ;; May modify syntax-type text property if the situation is too hard
3390   (let (b starter ender st i i2 go-forward)
3391     (skip-chars-forward " \t")
3392     ;; ender means matching-char matcher.
3393     (setq b (point) 
3394           starter (char-after b)
3395           ;; ender:
3396           ender (cdr (assoc starter '(( ?\( . ?\) )
3397                                       ( ?\[ . ?\] )
3398                                       ( ?\{ . ?\} )
3399                                       ( ?\< . ?\> )
3400                                       ))))
3401     ;; What if starter == ?\\  ????
3402     (if set-st
3403         (if (car st-l)
3404             (setq st (car st-l))
3405           (setcar st-l (make-syntax-table))
3406           (setq i 0 st (car st-l))
3407           (while (< i 256)
3408             (modify-syntax-entry i "." st)
3409             (setq i (1+ i)))
3410           (modify-syntax-entry ?\\ "\\" st)))
3411     (setq set-st t)
3412     ;; Whether we have an intermediate point
3413     (setq i nil)
3414     ;; Prepare the syntax table:
3415     (and set-st
3416          (if (not ender)                ; m/blah/, s/x//, s/x/y/
3417              (modify-syntax-entry starter "$" st)
3418            (modify-syntax-entry starter (concat "(" (list ender)) st)
3419            (modify-syntax-entry ender  (concat ")" (list starter)) st)))
3420     (condition-case bb
3421         (progn
3422           (if (and (eq starter (char-after (cperl-1+ b)))
3423                    (not ender))
3424               ;; $ has TeXish matching rules, so $$ equiv $...
3425               (forward-char 2)
3426             (set-syntax-table st)
3427             (forward-sexp 1)
3428             (set-syntax-table cperl-mode-syntax-table)
3429             ;; Now the problem is with m;blah;;
3430             (and (not ender)
3431                  (eq (preceding-char)
3432                      (char-after (- (point) 2)))
3433                  (save-excursion
3434                    (forward-char -2)
3435                    (= 0 (% (skip-chars-backward "\\\\") 2)))
3436                  (forward-char -1)))
3437           (and is-2arg                  ; Have trailing part
3438                (not ender)
3439                (eq (following-char) starter) ; Empty trailing part
3440                (progn
3441                  (or (eq (char-syntax (following-char)) ?.)
3442                      ;; Make trailing letter into punctuation
3443                      (cperl-modify-syntax-type (point) cperl-st-punct))
3444                  (setq is-2arg nil go-forward t))) ; Ignore the tail
3445           (if is-2arg                   ; Not number => have second part
3446               (progn
3447                 (setq i (point) i2 i)
3448                 (if ender
3449                     (if (memq (following-char) '(?\  ?\t ?\n ?\f))
3450                         (progn
3451                           (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
3452                               (goto-char (match-end 0))
3453                             (skip-chars-forward " \t\n\f"))
3454                           (setq i2 (point))))
3455                   (forward-char -1))
3456                 (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
3457                 (if ender (modify-syntax-entry ender "." st))           
3458                 (setq set-st nil)
3459                 (setq 
3460                  ender
3461                  (cperl-forward-re lim end nil t st-l err-l argument starter ender)
3462                  ender (nth 2 ender)))))
3463       (error (goto-char lim)
3464              (setq set-st nil)
3465              (or end
3466                  (message
3467                   "End of `%s%s%c ... %c' string not found: %s"
3468                   argument
3469                   (if ostart (format "%c ... %c" ostart (or oend ostart)) "")
3470                   starter (or ender starter) bb)
3471                  (or (car err-l) (setcar err-l b)))))
3472     (if set-st
3473         (progn
3474           (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
3475           (if ender (modify-syntax-entry ender "." st))))
3476     (list i i2 ender starter go-forward)))
3477
3478 (defvar font-lock-string-face)
3479 (defvar font-lock-reference-face)
3480 (defvar font-lock-constant-face)
3481 (defun cperl-find-pods-heres (&optional min max non-inter end ignore-max)
3482   "Scans the buffer for hard-to-parse Perl constructions.
3483 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify 
3484 the sections using `cperl-pod-head-face', `cperl-pod-face', 
3485 `cperl-here-face'."
3486   (interactive)
3487   (or min (setq min (point-min)
3488                 cperl-syntax-state nil
3489                 cperl-syntax-done-to min))
3490   (or max (setq max (point-max)))
3491   (let* (face head-face here-face b e bb tag qtag b1 e1 argument i c tail tb
3492               (cperl-pod-here-fontify (eval cperl-pod-here-fontify)) go tmpend 
3493               (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
3494               (modified (buffer-modified-p))
3495               (after-change-functions nil)
3496               (use-syntax-state (and cperl-syntax-state
3497                                      (>= min (car cperl-syntax-state))))
3498               (state-point (if use-syntax-state
3499                                (car cperl-syntax-state)
3500                              (point-min)))
3501               (state (if use-syntax-state
3502                          (cdr cperl-syntax-state)))
3503               (st-l '(nil)) (err-l '(nil)) i2
3504               ;; Somehow font-lock may be not loaded yet...
3505               (font-lock-string-face (if (boundp 'font-lock-string-face)
3506                                          font-lock-string-face
3507                                        'font-lock-string-face))
3508               (stop-point (if ignore-max 
3509                               (point-max)
3510                             max))
3511               (search
3512                (concat
3513                 "\\(\\`\n?\\|\n\n\\)=" 
3514                 "\\|"
3515                 ;; One extra () before this:
3516                 "<<" 
3517                   "\\("                 ; 1 + 1
3518                   ;; First variant "BLAH" or just ``.
3519                      "\\([\"'`]\\)"     ; 2 + 1
3520                      "\\([^\"'`\n]*\\)" ; 3 + 1
3521                      "\\3"
3522                   "\\|"
3523                   ;; Second variant: Identifier or \ID or empty
3524                     "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
3525                     ;; Do not have <<= or << 30 or <<30 or << $blah.
3526                     ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
3527                     "\\(\\)"            ; To preserve count of pars :-( 6 + 1
3528                   "\\)"
3529                 "\\|"
3530                 ;; 1+6 extra () before this:
3531                 "^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
3532                 (if cperl-use-syntax-table-text-property
3533                     (concat
3534                      "\\|"
3535                      ;; 1+6+2=9 extra () before this:
3536                      "\\<\\(q[wxq]?\\|[msy]\\|tr\\)\\>"
3537                      "\\|"
3538                      ;; 1+6+2+1=10 extra () before this:
3539                      "\\([?/<]\\)"      ; /blah/ or ?blah? or <file*glob>
3540                      "\\|"
3541                      ;; 1+6+2+1+1=11 extra () before this:
3542                      "\\<sub\\>[ \t]*\\([a-zA-Z_:'0-9]+[ \t]*\\)?\\(([^()]*)\\)"
3543                      "\\|"
3544                      ;; 1+6+2+1+1+2=13 extra () before this:
3545                      "\\$\\(['{]\\)"
3546                      "\\|"
3547                      ;; 1+6+2+1+1+2+1=14 extra () before this:
3548                      "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'"
3549                      ;; 1+6+2+1+1+2+1+1=15 extra () before this:
3550                      "\\|"
3551                      "__\\(END\\|DATA\\)__"  ; Commented - does not help with indent...
3552                      )
3553                   ""))))
3554     (unwind-protect
3555         (progn
3556           (save-excursion
3557             (or non-inter
3558                 (message "Scanning for \"hard\" Perl constructions..."))
3559             (and cperl-pod-here-fontify
3560                 ;; We had evals here, do not know why...
3561                 (setq face cperl-pod-face
3562                       head-face cperl-pod-head-face
3563                       here-face cperl-here-face))
3564             (remove-text-properties min max 
3565                                     '(syntax-type t in-pod t syntax-table t))
3566             ;; Need to remove face as well...
3567             (goto-char min)
3568             (and (eq system-type 'emx)
3569                  (looking-at "extproc[ \t]") ; Analogue of #!
3570                  (cperl-commentify min 
3571                                    (save-excursion (end-of-line) (point))
3572                                    nil))
3573             (while (and
3574                     (< (point) max)
3575                     (re-search-forward search max t))
3576               (setq tmpend nil)         ; Valid for most cases
3577               (cond 
3578                ((match-beginning 1)     ; POD section
3579                 ;;  "\\(\\`\n?\\|\n\n\\)=" 
3580                 (if (looking-at "\n*cut\\>")
3581                     (if ignore-max
3582                         nil             ; Doing a chunk only
3583                       (message "=cut is not preceded by a POD section")
3584                       (or (car err-l) (setcar err-l (point))))
3585                   (beginning-of-line)
3586                 
3587                   (setq b (point) 
3588                         bb b
3589                         tb (match-beginning 0))
3590                   ;; We do not search to max, since we may be called from
3591                   ;; some hook of fontification, and max is random
3592                   (or (re-search-forward "\n\n=cut\\>" stop-point 'toend)
3593                       (progn
3594                         (message "End of a POD section not marked by =cut")
3595                         (or (car err-l) (setcar err-l b))))
3596                   (beginning-of-line 2) ; An empty line after =cut is not POD!
3597                   (setq e (point))
3598                   (and (> e max)
3599                        (progn
3600                          (remove-text-properties 
3601                           max e '(syntax-type t in-pod t syntax-table t))
3602                          (setq tmpend tb)))
3603                   (put-text-property b e 'in-pod t)
3604                   (goto-char b)
3605                   (while (re-search-forward "\n\n[ \t]" e t)
3606                     ;; We start 'pod 1 char earlier to include the preceding line
3607                     (beginning-of-line)
3608                     (put-text-property (cperl-1- b) (point) 'syntax-type 'pod)
3609                     (cperl-put-do-not-fontify b (point))
3610                     (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
3611                     (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
3612                     (beginning-of-line)
3613                     (setq b (point)))
3614                   (put-text-property (cperl-1- (point)) e 'syntax-type 'pod)
3615                   (cperl-put-do-not-fontify (point) e)
3616                   (if cperl-pod-here-fontify 
3617                       (progn (put-text-property (point) e 'face face)
3618                              (goto-char bb)
3619                              (if (looking-at 
3620                                   "=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
3621                                  (put-text-property 
3622                                   (match-beginning 1) (match-end 1)
3623                                   'face head-face))
3624                              (while (re-search-forward
3625                                      ;; One paragraph
3626                                      "\n\n=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
3627                                      e 'toend)
3628                                (put-text-property 
3629                                 (match-beginning 1) (match-end 1)
3630                                 'face head-face))))
3631                   (cperl-commentify bb e nil)
3632                   (goto-char e)
3633                   (or (eq e (point-max))
3634                       (forward-char -1)))) ; Prepare for immediate pod start.
3635                ;; Here document
3636                ;; We do only one here-per-line
3637                ;; ;; One extra () before this:
3638                ;;"<<" 
3639                ;;  "\\("                        ; 1 + 1
3640                ;;  ;; First variant "BLAH" or just ``.
3641                ;;     "\\([\"'`]\\)"    ; 2 + 1
3642                ;;     "\\([^\"'`\n]*\\)"        ; 3 + 1
3643                ;;     "\\3"
3644                ;;  "\\|"
3645                ;;  ;; Second variant: Identifier or \ID or empty
3646                ;;    "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
3647                ;;    ;; Do not have <<= or << 30 or <<30 or << $blah.
3648                ;;    ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
3649                ;;    "\\(\\)"           ; To preserve count of pars :-( 6 + 1
3650                ;;  "\\)"
3651                ((match-beginning 2)     ; 1 + 1
3652                 ;; Abort in comment:
3653                 (setq b (point))
3654                 (setq state (parse-partial-sexp state-point b nil nil state)
3655                       state-point b
3656                       tb (match-beginning 0)
3657                       i (or (nth 3 state) (nth 4 state)))
3658                 (if i 
3659                     (setq c t)
3660                   (setq c (and
3661                            (match-beginning 5)
3662                            (not (match-beginning 6)) ; Empty
3663                            (looking-at
3664                             "[ \t]*[=0-9$@%&]"))))
3665                 (if c                   ; Not here-doc
3666                     nil                 ; Skip it.
3667                   (if (match-beginning 5) ;4 + 1
3668                       (setq b1 (match-beginning 5) ; 4 + 1
3669                             e1 (match-end 5)) ; 4 + 1
3670                     (setq b1 (match-beginning 4) ; 3 + 1
3671                           e1 (match-end 4))) ; 3 + 1
3672                   (setq tag (buffer-substring b1 e1)
3673                         qtag (regexp-quote tag))
3674                   (cond (cperl-pod-here-fontify 
3675                          (put-text-property b1 e1 'face font-lock-constant-face)
3676                          (cperl-put-do-not-fontify b1 e1)))
3677                   (forward-line)
3678                   (setq b (point))
3679                   ;; We do not search to max, since we may be called from
3680                   ;; some hook of fontification, and max is random
3681                   (cond ((re-search-forward (concat "^" qtag "$") 
3682                                             stop-point 'toend)
3683                          (if cperl-pod-here-fontify 
3684                              (progn
3685                                (put-text-property (match-beginning 0) (match-end 0) 
3686                                                   'face font-lock-constant-face)
3687                                (cperl-put-do-not-fontify b (match-end 0))
3688                                (put-text-property b (match-beginning 0) 
3689                                                   'face here-face)))
3690                          (setq e1 (cperl-1+ (match-end 0)))
3691                          (put-text-property b (match-beginning 0) 
3692                                             'syntax-type 'here-doc)
3693                          (put-text-property (match-beginning 0) e1
3694                                             'syntax-type 'here-doc-delim)
3695                          (put-text-property b e1
3696                                             'here-doc-group t)
3697                          (cperl-commentify b e1 nil)
3698                          (cperl-put-do-not-fontify b (match-end 0))
3699                          (if (> e1 max)
3700                              (setq tmpend tb)))
3701                         (t (message "End of here-document `%s' not found." tag)
3702                            (or (car err-l) (setcar err-l b))))))
3703                ;; format
3704                ((match-beginning 8)
3705                 ;; 1+6=7 extra () before this:
3706                 ;;"^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
3707                 (setq b (point)
3708                       name (if (match-beginning 8) ; 7 + 1
3709                                (buffer-substring (match-beginning 8) ; 7 + 1
3710                                                  (match-end 8)) ; 7 + 1
3711                              "")
3712                       tb (match-beginning 0))
3713                 (setq argument nil)
3714                 (if cperl-pod-here-fontify 
3715                     (while (and (eq (forward-line) 0)
3716                                 (not (looking-at "^[.;]$")))
3717                       (cond
3718                        ((looking-at "^#")) ; Skip comments
3719                        ((and argument   ; Skip argument multi-lines
3720                              (looking-at "^[ \t]*{")) 
3721                         (forward-sexp 1)
3722                         (setq argument nil))
3723                        (argument        ; Skip argument lines
3724                         (setq argument nil))
3725                        (t               ; Format line
3726                         (setq b1 (point))
3727                         (setq argument (looking-at "^[^\n]*[@^]"))
3728                         (end-of-line)
3729                         (put-text-property b1 (point) 
3730                                            'face font-lock-string-face)
3731                         (cperl-commentify b1 (point) nil)
3732                         (cperl-put-do-not-fontify b1 (point)))))
3733                   ;; We do not search to max, since we may be called from
3734                   ;; some hook of fontification, and max is random
3735                   (re-search-forward "^[.;]$" stop-point 'toend))
3736                 (beginning-of-line)
3737                 (if (looking-at "^[.;]$")
3738                     (progn
3739                       (put-text-property (point) (+ (point) 2)
3740                                          'face font-lock-string-face)
3741                       (cperl-commentify (point) (+ (point) 2) nil)
3742                       (cperl-put-do-not-fontify (point) (+ (point) 2)))
3743                   (message "End of format `%s' not found." name)
3744                   (or (car err-l) (setcar err-l b)))
3745                 (forward-line)
3746                 (if (> (point) max)
3747                     (setq tmpend tb))
3748                 (put-text-property b (point) 'syntax-type 'format))
3749                ;; Regexp:
3750                ((or (match-beginning 10) (match-beginning 11))
3751                 ;; 1+6+2=9 extra () before this:
3752                 ;; "\\<\\(q[wxq]?\\|[msy]\\|tr\\)\\>"
3753                 ;; "\\|"
3754                 ;; "\\([?/<]\\)"        ; /blah/ or ?blah? or <file*glob>
3755                 (setq b1 (if (match-beginning 10) 10 11)
3756                       argument (buffer-substring
3757                                 (match-beginning b1) (match-end b1))
3758                       b (point)
3759                       i b
3760                       c (char-after (match-beginning b1))
3761                       bb (char-after (1- (match-beginning b1))) ; tmp holder
3762                       bb (and           ; user variables/whatever
3763                           (match-beginning 10)
3764                           (or
3765                            (memq bb '(?\$ ?\@ ?\% ?\* ?\#)) ; $#y
3766                            (and (eq bb ?-) (eq c ?s)) ; -s file test
3767                            (and (eq bb ?\&) ; &&m/blah/
3768                                 (not (eq (char-after 
3769                                           (- (match-beginning b1) 2))
3770                                          ?\&)))))
3771                       tb (match-beginning 0))
3772                 (goto-char (match-beginning b1))
3773                 (cperl-backward-to-noncomment (point-min))
3774                 (or bb
3775                     (if (eq b1 11)      ; bare /blah/ or ?blah? or <foo>
3776                         (setq argument ""
3777                               bb        ; Not a regexp?
3778                               (progn
3779                                 (not 
3780                                  ;; What is below: regexp-p?
3781                                  (and
3782                                   (or (memq (preceding-char)
3783                                             (append (if (eq c ?\?)
3784                                                         ;; $a++ ? 1 : 2
3785                                                         "~{(=|&*!,;"
3786                                                       "~{(=|&+-*!,;") nil))
3787                                       (and (eq (preceding-char) ?\})
3788                                            (cperl-after-block-p (point-min)))
3789                                       (and (eq (char-syntax (preceding-char)) ?w)
3790                                            (progn
3791                                              (forward-sexp -1)
3792 ;;; After these keywords `/' starts a RE.  One should add all the
3793 ;;; functions/builtins which expect an argument, but ...
3794                                              (if (eq (preceding-char) ?-)
3795                                                  ;; -d ?foo? is a RE
3796                                                  (looking-at "\\w\\>")
3797                                                (looking-at 
3798                                                 "\\(while\\|if\\|unless\\|until\\|and\\|or\\|not\\|xor\\|split\\|grep\\|map\\|print\\)\\>"))))
3799                                       (and (eq (preceding-char) ?.)
3800                                            (eq (char-after (- (point) 2)) ?.))
3801                                       (bobp))
3802                                   ;;  m|blah| ? foo : bar;
3803                                   (not
3804                                    (and (eq c ?\?)
3805                                         cperl-use-syntax-table-text-property 
3806                                         (not (bobp))
3807                                         (progn
3808                                           (forward-char -1)
3809                                           (looking-at "\\s|"))))
3810                                   ;; <file> or <$file>
3811                                   (not
3812                                    (and (eq c ?\<)
3813                                         (looking-at "\\s *\\$?[_a-zA-Z:][_a-zA-Z0-9:]*\\s *>"))))))
3814                               b (1- b))
3815                       ;; s y tr m
3816                       ;; Check for $a->y
3817                       (if (and (eq (preceding-char) ?>)
3818                                (eq (char-after (- (point) 2)) ?-))
3819                           ;; Not a regexp
3820                           (setq bb t))))
3821                 (or bb (setq state (parse-partial-sexp 
3822                                     state-point b nil nil state)
3823                              state-point b))
3824                 (goto-char b)
3825                 (if (or bb (nth 3 state) (nth 4 state))
3826                     (goto-char i)
3827                   (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
3828                       (goto-char (match-end 0))
3829                     (skip-chars-forward " \t\n\f"))
3830                   ;; qtag means two-arg matcher, may be reset to
3831                   ;;   2 or 3 later if some special quoting is needed.
3832                   ;; e1 means matching-char matcher.
3833                   (setq b (point)
3834                         ;; We do not search to max, since we may be called from
3835                         ;; some hook of fontification, and max is random
3836                         i (cperl-forward-re stop-point end
3837                                             (string-match "^\\([sy]\\|tr\\)$" argument)
3838                                             t st-l err-l argument)
3839                         i2 (nth 1 i)    ; start of the second part
3840                         e1 (nth 2 i)    ; ender, true if matching second part
3841                         go (nth 4 i)    ; There is a 1-char part after the end
3842                         i (car i)       ; intermediate point
3843                         tail (if (and i (not e1)) (1- (point)))
3844                         e nil)          ; need to preserve backslashitis
3845                   ;; Commenting \\ is dangerous, what about ( ?
3846                   (and i tail
3847                        (eq (char-after i) ?\\)
3848                        (setq e t))
3849                   (if (null i)
3850                       (progn
3851                         (cperl-commentify b (point) t)
3852                         (if go (forward-char 1)))
3853                     (cperl-commentify b i t)
3854                     (if (looking-at "\\sw*e") ; s///e
3855                         (progn
3856                           (and
3857                            ;; silent:
3858                            (cperl-find-pods-heres i2 (1- (point)) t end)
3859                            ;; Error
3860                            (goto-char (1+ max)))
3861                           (if (and e1 (eq (preceding-char) ?\>))
3862                               (progn
3863                                 (cperl-modify-syntax-type (1- (point)) cperl-st-ket)
3864                                 (cperl-modify-syntax-type i cperl-st-bra))))
3865                       (cperl-commentify i2 (point) t)
3866                       (if e
3867                           (cperl-modify-syntax-type (1+ i) cperl-st-punct))
3868                       (setq tail nil)))
3869                   (if (eq (char-syntax (following-char)) ?w)
3870                       (progn
3871                         (forward-word 1) ; skip modifiers s///s
3872                         (if tail (cperl-commentify tail (point) t))))
3873                   (if (> (point) max)
3874                       (setq tmpend tb))))
3875                ((match-beginning 13)    ; sub with prototypes
3876                 (setq b (match-beginning 0))
3877                 (if (memq (char-after (1- b))
3878                           '(?\$ ?\@ ?\% ?\& ?\*))
3879                     nil
3880                   (setq state (parse-partial-sexp 
3881                                state-point (1- b) nil nil state)
3882                         state-point (1- b))
3883                   (if (or (nth 3 state) (nth 4 state))
3884                       nil
3885                     ;; Mark as string
3886                     (cperl-commentify (match-beginning 13) (match-end 13) t))
3887                   (goto-char (match-end 0))))
3888                ;; 1+6+2+1+1+2=13 extra () before this:
3889                ;;    "\\$\\(['{]\\)"
3890                ((and (match-beginning 14)
3891                      (eq (preceding-char) ?\')) ; $'
3892                 (setq b (1- (point))
3893                       state (parse-partial-sexp 
3894                              state-point (1- b) nil nil state)
3895                       state-point (1- b))
3896                 (if (nth 3 state)       ; in string
3897                     (cperl-modify-syntax-type (1- b) cperl-st-punct))
3898                 (goto-char (1+ b)))
3899                ;; 1+6+2+1+1+2=13 extra () before this:
3900                ;;    "\\$\\(['{]\\)"
3901                ((match-beginning 14)    ; ${
3902                 (setq bb (match-beginning 0))
3903                 (cperl-modify-syntax-type bb cperl-st-punct))
3904                ;; 1+6+2+1+1+2+1=14 extra () before this:
3905                ;;    "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'")
3906                ((match-beginning 15)    ; old $abc'efg syntax
3907                 (setq bb (match-end 0)
3908                       b (match-beginning 0)
3909                       state (parse-partial-sexp 
3910                              state-point b nil nil state)
3911                       state-point b)
3912                 (if (nth 3 state)       ; in string
3913                     nil
3914                   (put-text-property (1- bb) bb 'syntax-table cperl-st-word))
3915                 (goto-char bb))
3916                ;; 1+6+2+1+1+2+1+1=15 extra () before this:
3917                ;; "__\\(END\\|DATA\\)__"
3918                (t                       ; __END__, __DATA__
3919                 (setq bb (match-end 0)
3920                       b (match-beginning 0)
3921                       state (parse-partial-sexp 
3922                              state-point b nil nil state)
3923                       state-point b)
3924                 (if (or (nth 3 state) (nth 4 state))
3925                     nil
3926                   ;; (put-text-property b (1+ bb) 'syntax-type 'pod) ; Cheat
3927                   (cperl-commentify b bb nil)
3928                   (setq end t))
3929                 (goto-char bb)))
3930               (if (> (point) stop-point)
3931                   (progn
3932                     (if end 
3933                         (message "Garbage after __END__/__DATA__ ignored")
3934                       (message "Unbalanced syntax found while scanning")
3935                       (or (car err-l) (setcar err-l b)))
3936                     (goto-char stop-point))))
3937             (setq cperl-syntax-state (cons state-point state)
3938                   cperl-syntax-done-to (or tmpend (max (point) max))))
3939           (if (car err-l) (goto-char (car err-l))
3940             (or non-inter
3941                 (message "Scanning for \"hard\" Perl constructions... done"))))
3942       (and (buffer-modified-p)
3943            (not modified)
3944            (set-buffer-modified-p nil))
3945       (set-syntax-table cperl-mode-syntax-table))
3946     (car err-l)))
3947
3948 (defun cperl-backward-to-noncomment (lim)
3949   ;; Stops at lim or after non-whitespace that is not in comment
3950   (let (stop p)
3951     (while (and (not stop) (> (point) (or lim 1)))
3952       (skip-chars-backward " \t\n\f" lim)
3953       (setq p (point))
3954       (beginning-of-line)
3955       (if (or (looking-at "^[ \t]*\\(#\\|$\\)")
3956               (progn (cperl-to-comment-or-eol) (bolp)))
3957           nil   ; Only comment, skip
3958         ;; Else
3959         (skip-chars-backward " \t")
3960         (if (< p (point)) (goto-char p))
3961         (setq stop t)))))
3962
3963 (defun cperl-after-block-p (lim)
3964   ;; We suppose that the preceding char is }.
3965   (save-excursion
3966     (condition-case nil
3967         (progn
3968           (forward-sexp -1)
3969           (cperl-backward-to-noncomment lim)
3970           (or (eq (point) lim)
3971               (eq (preceding-char) ?\) ) ; if () {}    sub f () {}
3972               (if (eq (char-syntax (preceding-char)) ?w) ; else {}
3973                   (save-excursion
3974                     (forward-sexp -1)
3975                     (or (looking-at "\\(else\\|grep\\|map\\)\\>")
3976                         ;; sub f {}
3977                         (progn
3978                           (cperl-backward-to-noncomment lim)
3979                           (and (eq (char-syntax (preceding-char)) ?w)
3980                                (progn
3981                                  (forward-sexp -1)
3982                                  (looking-at "sub\\>"))))))
3983                 (cperl-after-expr-p lim))))
3984       (error nil))))
3985
3986 (defun cperl-after-expr-p (&optional lim chars test)
3987   "Returns true if the position is good for start of expression.
3988 TEST is the expression to evaluate at the found position.  If absent,
3989 CHARS is a string that contains good characters to have before us (however,
3990 `}' is treated \"smartly\" if it is not in the list)."
3991   (let (stop p 
3992              (lim (or lim (point-min))))
3993     (save-excursion
3994       (while (and (not stop) (> (point) lim))
3995         (skip-chars-backward " \t\n\f" lim)
3996         (setq p (point))
3997         (beginning-of-line)
3998         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
3999           ;; Else: last iteration (What to do with labels?)
4000           (cperl-to-comment-or-eol) 
4001           (skip-chars-backward " \t")
4002           (if (< p (point)) (goto-char p))
4003           (setq stop t)))
4004       (or (bobp)                        ; ???? Needed
4005           (eq (point) lim)
4006           (progn
4007             (if test (eval test)
4008               (or (memq (preceding-char) (append (or chars "{;") nil))
4009                   (and (eq (preceding-char) ?\})
4010                        (cperl-after-block-p lim)))))))))
4011
4012 (defun cperl-backward-to-start-of-continued-exp (lim)
4013   (if (memq (preceding-char) (append ")]}\"'`" nil))
4014       (forward-sexp -1))
4015   (beginning-of-line)
4016   (if (<= (point) lim)
4017       (goto-char (1+ lim)))
4018   (skip-chars-forward " \t"))
4019
4020 (defun cperl-after-block-and-statement-beg (lim)
4021   ;; We assume that we are after ?\}
4022   (and 
4023    (cperl-after-block-p lim)
4024    (save-excursion
4025      (forward-sexp -1)
4026      (cperl-backward-to-noncomment (point-min))
4027      (or (bobp)
4028          (eq (point) lim)
4029          (not (= (char-syntax (preceding-char)) ?w))
4030          (progn
4031            (forward-sexp -1)
4032            (not 
4033             (looking-at
4034              "\\(map\\|grep\\|printf?\\|system\\|exec\\|tr\\|s\\)\\>")))))))
4035
4036 \f
4037 (defvar innerloop-done nil)
4038 (defvar last-depth nil)
4039
4040 (defun cperl-indent-exp ()
4041   "Simple variant of indentation of continued-sexp.
4042 Should be slow.  Will not indent comment if it starts at `comment-indent'
4043 or looks like continuation of the comment on the previous line.
4044
4045 If `cperl-indent-region-fix-constructs', will improve spacing on 
4046 conditional/loop constructs."
4047   (interactive)
4048   (save-excursion
4049     (let ((tmp-end (progn (end-of-line) (point))) top done)
4050       (save-excursion
4051         (beginning-of-line)
4052         (while (null done)
4053           (setq top (point))
4054           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
4055                                                -1)) -1)
4056             (setq top (point)))         ; Get the outermost parenths in line
4057           (goto-char top)
4058           (while (< (point) tmp-end)
4059             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
4060             (or (eolp) (forward-sexp 1)))
4061           (if (> (point) tmp-end) (progn (end-of-line) (setq tmp-end (point)))
4062             (setq done t)))
4063         (goto-char tmp-end)
4064         (setq tmp-end (point-marker)))
4065       (if cperl-indent-region-fix-constructs
4066           (cperl-fix-line-spacing tmp-end))
4067       (cperl-indent-region (point) tmp-end))))
4068
4069 (defun cperl-fix-line-spacing (&optional end parse-data)
4070   "Improve whitespace in a conditional/loop construct."
4071   (interactive)
4072   (or end
4073       (setq end (point-max)))
4074   (let (p pp ml have-brace
4075           (ee (save-excursion (end-of-line) (point)))
4076           (cperl-indent-region-fix-constructs
4077            (or cperl-indent-region-fix-constructs 1)))
4078     (save-excursion
4079       (beginning-of-line)
4080       ;;  }? continue 
4081       ;;  blah; }
4082       (if (not 
4083            (or (looking-at "[ \t]*\\(els\\(e\\|if\\)\\|continue\\|if\\|while\\|for\\(each\\)?\\|until\\)")
4084                (setq have-brace (save-excursion (search-forward "}" ee t)))))
4085           nil                           ; Do not need to do anything
4086       ;; Looking at:
4087       ;; }  
4088       ;; else
4089       (if (and cperl-merge-trailing-else
4090                (looking-at
4091                 "[ \t]*}[ \t]*\n[ \t\n]*\\(els\\(e\\|if\\)\\|continue\\)\\>"))
4092           (progn
4093             (search-forward "}")
4094             (setq p (point))
4095             (skip-chars-forward " \t\n")
4096             (delete-region p (point))
4097             (insert (make-string cperl-indent-region-fix-constructs ?\ ))
4098             (beginning-of-line)))
4099       ;; Looking at:
4100       ;; }     else
4101       (if (looking-at "[ \t]*}\\(\t*\\|[ \t][ \t]+\\)\\<\\(els\\(e\\|if\\)\\|continue\\)\\>")
4102           (progn
4103             (search-forward "}")
4104             (delete-horizontal-space)
4105             (insert (make-string cperl-indent-region-fix-constructs ?\ ))
4106             (beginning-of-line)))
4107       ;; Looking at:
4108       ;; else   {
4109       (if (looking-at 
4110            "[ \t]*}?[ \t]*\\<\\(\\els\\(e\\|if\\)\\|continue\\|unless\\|if\\|while\\|for\\(each\\)?\\|until\\)\\>\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
4111           (progn
4112             (forward-word 1)
4113             (delete-horizontal-space)
4114             (insert (make-string cperl-indent-region-fix-constructs ?\ ))
4115             (beginning-of-line)))
4116       ;; Looking at:
4117       ;; foreach my    $var
4118       (if (looking-at 
4119            "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\)\\(\t*\\|[ \t][ \t]+\\)[^ \t\n]")
4120           (progn
4121             (forward-word 2)
4122             (delete-horizontal-space)
4123             (insert (make-string cperl-indent-region-fix-constructs ?\ ))
4124             (beginning-of-line)))
4125       ;; Looking at:
4126       ;; foreach my $var     (
4127       (if (looking-at 
4128              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\)[ \t]*\\$[_a-zA-Z0-9]+\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
4129           (progn
4130             (forward-word 3)
4131             (delete-horizontal-space)
4132             (insert
4133              (make-string cperl-indent-region-fix-constructs ?\ ))
4134             (beginning-of-line)))
4135       ;; Looking at:
4136       ;; } foreach my $var ()    {
4137       (if (looking-at 
4138              "[ \t]*\\(}[ \t]*\\)?\\<\\(\\els\\(e\\|if\\)\\|continue\\|if\\|unless\\|while\\|for\\(each\\)?\\(\\([ t]+\\(my\\|local\\)\\)?[ \t]*\\$[_a-zA-Z0-9]+\\)?\\|until\\)\\>\\([ \t]*(\\|[ \t\n]*{\\)\\|[ \t]*{")
4139           (progn
4140             (setq ml (match-beginning 8))
4141             (re-search-forward "[({]")
4142             (forward-char -1)
4143             (setq p (point))
4144             (if (eq (following-char) ?\( )
4145                 (progn
4146                   (forward-sexp 1)
4147                   (setq pp (point)))
4148               ;; after `else' or nothing
4149               (if ml    ; after `else'
4150                   (skip-chars-backward " \t\n")
4151                 (beginning-of-line))
4152               (setq pp nil))
4153             ;; Now after the sexp before the brace
4154             ;; Multiline expr should be special
4155             (setq ml (and pp (save-excursion (goto-char p)
4156                                              (search-forward "\n" pp t))))
4157             (if (and (or (not pp) (< pp end))
4158                      (looking-at "[ \t\n]*{"))
4159                 (progn
4160                   (cond 
4161                    ((bolp)              ; Were before `{', no if/else/etc
4162                     nil)
4163                    ((looking-at "\\(\t*\\| [ \t]+\\){")
4164                     (delete-horizontal-space)
4165                     (if (if ml 
4166                             cperl-extra-newline-before-brace-multiline
4167                           cperl-extra-newline-before-brace)
4168                         (progn
4169                           (delete-horizontal-space)
4170                           (insert "\n")
4171                           (if (cperl-indent-line parse-data)
4172                               (cperl-fix-line-spacing end parse-data)))
4173                       (insert
4174                        (make-string cperl-indent-region-fix-constructs ?\ ))))
4175                    ((and (looking-at "[ \t]*\n")
4176                          (not (if ml 
4177                                   cperl-extra-newline-before-brace-multiline
4178                                 cperl-extra-newline-before-brace)))
4179                     (setq pp (point))
4180                     (skip-chars-forward " \t\n")
4181                     (delete-region pp (point))
4182                     (insert
4183                      (make-string cperl-indent-region-fix-constructs ?\ ))))
4184                   ;; Now we are before `{'
4185                   (if (looking-at "[ \t\n]*{[ \t]*[^ \t\n#]")
4186                       (progn
4187                         (skip-chars-forward " \t\n")
4188                         (setq pp (point))
4189                         (forward-sexp 1)
4190                         (setq p (point))
4191                         (goto-char pp)
4192                         (setq ml (search-forward "\n" p t))
4193                         (if (or cperl-break-one-line-blocks-when-indent ml)
4194                             ;; not good: multi-line BLOCK
4195                             (progn
4196                               (goto-char (1+ pp))
4197                               (delete-horizontal-space)
4198                               (insert "\n")
4199                               (if (cperl-indent-line parse-data)
4200                                   (cperl-fix-line-spacing end parse-data))))))))))
4201       (beginning-of-line)
4202       (setq p (point) pp (save-excursion (end-of-line) (point))) ; May be different from ee.
4203       ;; Now check whether there is a hanging `}'
4204       ;; Looking at:
4205       ;; } blah
4206       (if (and 
4207            cperl-fix-hanging-brace-when-indent
4208            have-brace
4209            (not (looking-at "[ \t]*}[ \t]*\\(\\<\\(els\\(if\\|e\\)\\|continue\\|while\\|until\\)\\>\\|$\\|#\\)"))
4210            (condition-case nil
4211                (progn
4212                  (up-list 1)
4213                  (if (and (<= (point) pp) 
4214                           (eq (preceding-char) ?\} )
4215                           (cperl-after-block-and-statement-beg (point-min))) 
4216                      t
4217                    (goto-char p)
4218                    nil))
4219              (error nil)))
4220           (progn
4221             (forward-char -1)
4222             (skip-chars-backward " \t")
4223             (if (bolp)
4224                 ;; `}' was the first thing on the line, insert NL *after* it.
4225                 (progn
4226                   (cperl-indent-line parse-data)
4227                   (search-forward "}")
4228                   (delete-horizontal-space)
4229                   (insert "\n"))
4230               (delete-horizontal-space)
4231               (or (eq (preceding-char) ?\;)
4232                   (bolp)
4233                   (and (eq (preceding-char) ?\} )
4234                        (cperl-after-block-p (point-min)))
4235                   (insert ";"))
4236               (insert "\n"))
4237             (if (cperl-indent-line parse-data)
4238                 (cperl-fix-line-spacing end parse-data))
4239             (beginning-of-line)))))))
4240
4241 (defvar cperl-update-start)             ; Do not need to make them local
4242 (defvar cperl-update-end)
4243 (defun cperl-delay-update-hook (beg end old-len)
4244   (setq cperl-update-start (min beg (or cperl-update-start (point-max))))
4245   (setq cperl-update-end (max end (or cperl-update-end (point-min)))))
4246
4247 (defun cperl-indent-region (start end)
4248   "Simple variant of indentation of region in CPerl mode.
4249 Should be slow.  Will not indent comment if it starts at `comment-indent' 
4250 or looks like continuation of the comment on the previous line.
4251 Indents all the lines whose first character is between START and END 
4252 inclusive.  
4253
4254 If `cperl-indent-region-fix-constructs', will improve spacing on 
4255 conditional/loop constructs."
4256   (interactive "r")
4257   (cperl-update-syntaxification end end)
4258   (save-excursion
4259     (let (cperl-update-start cperl-update-end (h-a-c after-change-functions))
4260       (let (st comm old-comm-indent new-comm-indent p pp i
4261                (indent-info (if cperl-emacs-can-parse
4262                                 '(nil nil)
4263                               nil))
4264                after-change-functions   ; Speed it up!
4265                (pm 0) (imenu-scanning-message "Indenting... (%3d%%)"))
4266         (if h-a-c (add-hook 'after-change-functions 'cperl-delay-update-hook))
4267         (goto-char start)
4268         (setq old-comm-indent (and (cperl-to-comment-or-eol)
4269                                    (current-column))
4270               new-comm-indent old-comm-indent)
4271         (goto-char start)
4272         (setq end (set-marker (make-marker) end)) ; indentation changes pos
4273         (or (bolp) (beginning-of-line 2))
4274         (or (fboundp 'imenu-progress-message)
4275             (message "Indenting... For feedback load `imenu'..."))
4276         (while (and (<= (point) end) (not (eobp))) ; bol to check start
4277           (and (fboundp 'imenu-progress-message)
4278                (imenu-progress-message 
4279                 pm (/ (* 100 (- (point) start)) (- end start -1))))
4280           (setq st (point))
4281           (if (and (setq comm (looking-at "[ \t]*#"))
4282                    (or (eq (current-indentation) (or old-comm-indent 
4283                                                      comment-column))
4284                        (setq old-comm-indent nil)))
4285               (if (and old-comm-indent
4286                        (= (current-indentation) old-comm-indent)
4287                        (not (eq (get-text-property (point) 'syntax-type) 'pod)))
4288                   (let ((comment-column new-comm-indent))
4289                     (indent-for-comment)))
4290             (progn 
4291               (setq i (cperl-indent-line indent-info))
4292               (or comm
4293                   (not i)
4294                   (progn
4295                     (if cperl-indent-region-fix-constructs
4296                         (cperl-fix-line-spacing end indent-info))
4297                     (if (setq old-comm-indent 
4298                               (and (cperl-to-comment-or-eol)
4299                                    (not (memq (get-text-property (point) 
4300                                                                  'syntax-type)
4301                                               '(pod here-doc)))
4302                                    (current-column)))
4303                         (progn (indent-for-comment)
4304                                (skip-chars-backward " \t")
4305                                (skip-chars-backward "#")
4306                                (setq new-comm-indent (current-column))))))))
4307           (beginning-of-line 2))
4308         (if (fboundp 'imenu-progress-message)
4309             (imenu-progress-message pm 100)
4310           (message nil)))
4311       ;; Now run the update hooks
4312       (if after-change-functions
4313           (save-excursion
4314             (if cperl-update-end
4315                 (progn
4316                   (goto-char cperl-update-end)
4317                   (insert " ")
4318                   (delete-char -1)
4319                   (goto-char cperl-update-start)
4320                   (insert " ")
4321                   (delete-char -1))))))))
4322
4323 ;; Stolen from lisp-mode with a lot of improvements
4324
4325 (defun cperl-fill-paragraph (&optional justify iteration)
4326   "Like \\[fill-paragraph], but handle CPerl comments.
4327 If any of the current line is a comment, fill the comment or the
4328 block of it that point is in, preserving the comment's initial
4329 indentation and initial hashes.  Behaves usually outside of comment."
4330   (interactive "P")
4331   (let (
4332         ;; Non-nil if the current line contains a comment.
4333         has-comment
4334
4335         ;; If has-comment, the appropriate fill-prefix for the comment.
4336         comment-fill-prefix
4337         ;; Line that contains code and comment (or nil)
4338         start
4339         c spaces len dc (comment-column comment-column))
4340     ;; Figure out what kind of comment we are looking at.
4341     (save-excursion
4342       (beginning-of-line)
4343       (cond
4344
4345        ;; A line with nothing but a comment on it?
4346        ((looking-at "[ \t]*#[# \t]*")
4347         (setq has-comment t
4348               comment-fill-prefix (buffer-substring (match-beginning 0)
4349                                                     (match-end 0))))
4350
4351        ;; A line with some code, followed by a comment?  Remember that the
4352        ;; semi which starts the comment shouldn't be part of a string or
4353        ;; character.
4354        ((cperl-to-comment-or-eol)
4355         (setq has-comment t)
4356         (looking-at "#+[ \t]*")
4357         (setq start (point) c (current-column) 
4358               comment-fill-prefix
4359               (concat (make-string (current-column) ?\ )
4360                       (buffer-substring (match-beginning 0) (match-end 0)))
4361               spaces (progn (skip-chars-backward " \t") 
4362                             (buffer-substring (point) start))
4363               dc (- c (current-column)) len (- start (point)) 
4364               start (point-marker))
4365         (delete-char len)
4366         (insert (make-string dc ?-)))))
4367     (if (not has-comment)
4368         (fill-paragraph justify)        ; Do the usual thing outside of comment
4369       ;; Narrow to include only the comment, and then fill the region.
4370       (save-restriction
4371         (narrow-to-region
4372          ;; Find the first line we should include in the region to fill.
4373          (if start (progn (beginning-of-line) (point))
4374            (save-excursion
4375              (while (and (zerop (forward-line -1))
4376                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
4377              ;; We may have gone to far.  Go forward again.
4378              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
4379                  (forward-line 1))
4380              (point)))
4381          ;; Find the beginning of the first line past the region to fill.
4382          (save-excursion
4383            (while (progn (forward-line 1)
4384                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
4385            (point)))
4386         ;; Remove existing hashes
4387         (goto-char (point-min))
4388         (while (progn (forward-line 1) (< (point) (point-max)))
4389           (skip-chars-forward " \t")
4390           (and (looking-at "#+") 
4391                (delete-char (- (match-end 0) (match-beginning 0)))))
4392
4393         ;; Lines with only hashes on them can be paragraph boundaries.
4394         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
4395               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
4396               (fill-prefix comment-fill-prefix))
4397           (fill-paragraph justify)))
4398       (if (and start)
4399           (progn 
4400             (goto-char start)
4401             (if (> dc 0)
4402               (progn (delete-char dc) (insert spaces)))
4403             (if (or (= (current-column) c) iteration) nil
4404               (setq comment-column c)
4405               (indent-for-comment)
4406               ;; Repeat once more, flagging as iteration
4407               (cperl-fill-paragraph justify t)))))))
4408
4409 (defun cperl-do-auto-fill ()
4410   ;; Break out if the line is short enough
4411   (if (> (save-excursion
4412            (end-of-line)
4413            (current-column))
4414          fill-column)
4415   (let ((c (save-excursion (beginning-of-line)
4416                            (cperl-to-comment-or-eol) (point)))
4417         (s (memq (following-char) '(?\ ?\t))) marker)
4418     (if (>= c (point)) nil
4419       (setq marker (point-marker))
4420       (cperl-fill-paragraph)
4421       (goto-char marker)
4422       ;; Is not enough, sometimes marker is a start of line
4423       (if (bolp) (progn (re-search-forward "#+[ \t]*") 
4424                         (goto-char (match-end 0))))
4425       ;; Following space could have gone:
4426       (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
4427         (insert " ")
4428         (backward-char 1))
4429       ;; Previous space could have gone:
4430       (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
4431
4432 (defvar imenu-example--function-name-regexp-perl
4433   (concat 
4434    "^\\("
4435        "[ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*\\(([^()]*)[ \t]*\\)?"
4436      "\\|"
4437        "=head\\([12]\\)[ \t]+\\([^\n]+\\)$"
4438    "\\)"))
4439
4440 (defun cperl-imenu-addback (lst &optional isback name)
4441   ;; We suppose that the lst is a DAG, unless the first element only
4442   ;; loops back, and ISBACK is set.  Thus this function cannot be
4443   ;; applied twice without ISBACK set.
4444   (cond ((not cperl-imenu-addback) lst)
4445         (t
4446          (or name 
4447              (setq name "+++BACK+++"))
4448          (mapcar (function (lambda (elt)
4449                              (if (and (listp elt) (listp (cdr elt)))
4450                                  (progn
4451                                    ;; In the other order it goes up
4452                                    ;; one level only ;-(
4453                                    (setcdr elt (cons (cons name lst)
4454                                                      (cdr elt)))
4455                                    (cperl-imenu-addback (cdr elt) t name)
4456                                    ))))
4457                  (if isback (cdr lst) lst))
4458          lst)))
4459
4460 (defun imenu-example--create-perl-index (&optional regexp)
4461   (require 'cl)
4462   (require 'imenu)                      ; May be called from TAGS creator
4463   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '()) 
4464         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
4465         (index-meth-alist '()) meth
4466         packages ends-ranges p
4467         (prev-pos 0) char fchar index index1 name (end-range 0) package)
4468     (goto-char (point-min))
4469     (if noninteractive
4470         (message "Scanning Perl for index")
4471       (imenu-progress-message prev-pos 0))
4472     ;; Search for the function
4473     (progn ;;save-match-data
4474       (while (re-search-forward
4475               (or regexp imenu-example--function-name-regexp-perl)
4476               nil t)
4477         (or noninteractive
4478             (imenu-progress-message prev-pos))
4479         (cond
4480          ((and                          ; Skip some noise if building tags
4481            (match-beginning 2)          ; package or sub
4482            (eq (char-after (match-beginning 2)) ?p) ; package
4483            (not (save-match-data
4484                   (looking-at "[ \t\n]*;"))))  ; Plain text word 'package'
4485           nil)
4486          ((and
4487            (match-beginning 2)          ; package or sub
4488            ;; Skip if quoted (will not skip multi-line ''-comments :-():
4489            (null (get-text-property (match-beginning 1) 'syntax-table))
4490            (null (get-text-property (match-beginning 1) 'syntax-type))
4491            (null (get-text-property (match-beginning 1) 'in-pod)))
4492           (save-excursion
4493             (goto-char (match-beginning 2))
4494             (setq fchar (following-char))
4495             )
4496           ;; (if (looking-at "([^()]*)[ \t\n\f]*")
4497           ;;    (goto-char (match-end 0)))      ; Messes what follows
4498           (setq char (following-char) 
4499                 meth nil
4500                 p (point))
4501           (while (and ends-ranges (>= p (car ends-ranges)))
4502             ;; delete obsolete entries
4503             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
4504           (setq package (or (car packages) "")
4505                 end-range (or (car ends-ranges) 0))
4506           (if (eq fchar ?p)
4507               (setq name (buffer-substring (match-beginning 3) (match-end 3))
4508                     name (progn
4509                            (set-text-properties 0 (length name) nil name)
4510                            name)
4511                     package (concat name "::") 
4512                     name (concat "package " name)
4513                     end-range 
4514                     (save-excursion
4515                       (parse-partial-sexp (point) (point-max) -1) (point))
4516                     ends-ranges (cons end-range ends-ranges)
4517                     packages (cons package packages)))
4518           ;;   )
4519           ;; Skip this function name if it is a prototype declaration.
4520           (if (and (eq fchar ?s) (eq char ?\;)) nil
4521             (setq index (imenu-example--name-and-position))
4522             (if (eq fchar ?p) nil
4523               (setq name (buffer-substring (match-beginning 3) (match-end 3)))
4524               (set-text-properties 0 (length name) nil name)
4525               (cond ((string-match "[:']" name)
4526                      (setq meth t))
4527                     ((> p end-range) nil)
4528                     (t 
4529                      (setq name (concat package name) meth t))))
4530             (setcar index name)
4531             (if (eq fchar ?p) 
4532                 (push index index-pack-alist)
4533               (push index index-alist))
4534             (if meth (push index index-meth-alist))
4535             (push index index-unsorted-alist)))
4536          ((match-beginning 5)           ; Pod section
4537           ;; (beginning-of-line)
4538           (setq index (imenu-example--name-and-position)
4539                 name (buffer-substring (match-beginning 6) (match-end 6)))
4540           (set-text-properties 0 (length name) nil name)
4541           (if (eq (char-after (match-beginning 5)) ?2)
4542               (setq name (concat "   " name)))
4543           (setcar index name)
4544           (setq index1 (cons (concat "=" name) (cdr index)))
4545           (push index index-pod-alist)
4546           (push index1 index-unsorted-alist)))))
4547     (or noninteractive
4548         (imenu-progress-message prev-pos 100))
4549     (setq index-alist 
4550           (if (default-value 'imenu-sort-function)
4551               (sort index-alist (default-value 'imenu-sort-function))
4552               (nreverse index-alist)))
4553     (and index-pod-alist
4554          (push (cons "+POD headers+..."
4555                      (nreverse index-pod-alist))
4556                index-alist))
4557     (and (or index-pack-alist index-meth-alist)
4558          (let ((lst index-pack-alist) hier-list pack elt group name)
4559            ;; Remove "package ", reverse and uniquify.
4560            (while lst
4561              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
4562              (if (assoc name hier-list) nil
4563                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
4564            (setq lst index-meth-alist)
4565            (while lst
4566              (setq elt (car lst) lst (cdr lst))
4567              (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
4568                     (setq pack (substring (car elt) 0 (match-beginning 0)))
4569                     (if (setq group (assoc pack hier-list)) 
4570                         (if (listp (cdr group))
4571                             ;; Have some functions already
4572                             (setcdr group 
4573                                     (cons (cons (substring 
4574                                                  (car elt)
4575                                                  (+ 2 (match-beginning 0)))
4576                                                 (cdr elt))
4577                                           (cdr group)))
4578                           (setcdr group (list (cons (substring 
4579                                                      (car elt)
4580                                                      (+ 2 (match-beginning 0)))
4581                                                     (cdr elt)))))
4582                       (setq hier-list 
4583                             (cons (cons pack 
4584                                         (list (cons (substring 
4585                                                      (car elt)
4586                                                      (+ 2 (match-beginning 0)))
4587                                                     (cdr elt))))
4588                                   hier-list))))))
4589            (push (cons "+Hierarchy+..."
4590                        hier-list)
4591                  index-alist)))
4592     (and index-pack-alist
4593          (push (cons "+Packages+..."
4594                      (nreverse index-pack-alist))
4595                index-alist))
4596     (and (or index-pack-alist index-pod-alist 
4597              (default-value 'imenu-sort-function))
4598          index-unsorted-alist
4599          (push (cons "+Unsorted List+..."
4600                      (nreverse index-unsorted-alist))
4601                index-alist))
4602     (cperl-imenu-addback index-alist)))
4603
4604 (defvar cperl-compilation-error-regexp-alist 
4605   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
4606   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
4607      2 3))
4608   "Alist that specifies how to match errors in perl output.")
4609
4610 (if (fboundp 'eval-after-load)
4611     (eval-after-load
4612      "mode-compile"
4613      '(setq perl-compilation-error-regexp-alist
4614            cperl-compilation-error-regexp-alist)))
4615
4616
4617 (defun cperl-windowed-init ()
4618   "Initialization under windowed version."
4619   (if (or (featurep 'ps-print) cperl-faces-init)
4620       ;; Need to init anyway:
4621       (or cperl-faces-init (cperl-init-faces))
4622     (add-hook 'font-lock-mode-hook
4623               (function
4624                (lambda ()
4625                  (if (or
4626                       (eq major-mode 'perl-mode)
4627                       (eq major-mode 'cperl-mode))
4628                      (progn
4629                        (or cperl-faces-init (cperl-init-faces)))))))
4630     (if (fboundp 'eval-after-load)
4631         (eval-after-load
4632          "ps-print"
4633          '(or cperl-faces-init (cperl-init-faces))))))
4634
4635 (defun cperl-load-font-lock-keywords ()
4636   (or cperl-faces-init (cperl-init-faces))
4637   perl-font-lock-keywords)
4638
4639 (defun cperl-load-font-lock-keywords-1 ()
4640   (or cperl-faces-init (cperl-init-faces))
4641   perl-font-lock-keywords-1)
4642
4643 (defun cperl-load-font-lock-keywords-2 ()
4644   (or cperl-faces-init (cperl-init-faces))
4645   perl-font-lock-keywords-2)
4646
4647 (defvar perl-font-lock-keywords-1 nil
4648   "Additional expressions to highlight in Perl mode.  Minimal set.")
4649 (defvar perl-font-lock-keywords nil
4650   "Additional expressions to highlight in Perl mode.  Default set.")
4651 (defvar perl-font-lock-keywords-2 nil
4652   "Additional expressions to highlight in Perl mode.  Maximal set")
4653
4654 (defvar font-lock-background-mode)
4655 (defvar font-lock-display-type)
4656 (defun cperl-init-faces-weak ()
4657   ;; Allow `cperl-find-pods-heres' to run.
4658   (or (boundp 'font-lock-constant-face)
4659       (setq font-lock-constant-face 'font-lock-constant-face)))
4660
4661 (defun cperl-init-faces ()
4662   (condition-case nil
4663       (progn
4664         (require 'font-lock)
4665         (and (fboundp 'font-lock-fontify-anchored-keywords)
4666              (featurep 'font-lock-extra)
4667              (message "You have an obsolete package `font-lock-extra'.  Install `choose-color'."))
4668         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
4669           (if (fboundp 'font-lock-fontify-anchored-keywords)
4670               (setq font-lock-anchored t))
4671           (setq 
4672            t-font-lock-keywords
4673            (list
4674             (cons
4675              (concat
4676               "\\(^\\|[^$@%&\\]\\)\\<\\("
4677               (mapconcat
4678                'identity
4679                '("if" "until" "while" "elsif" "else" "unless" "for"
4680                  "foreach" "continue" "exit" "die" "last" "goto" "next"
4681                  "redo" "return" "local" "exec" "sub" "do" "dump" "use"
4682                  "require" "package" "eval" "my" "BEGIN" "END")
4683                "\\|")                   ; Flow control
4684               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
4685                                         ; In what follows we use `type' style
4686                                         ; for overwritable builtins
4687             (list
4688              (concat
4689               "\\(^\\|[^$@%&\\]\\)\\<\\("
4690               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm"
4691               ;; "and" "atan2" "bind" "binmode" "bless" "caller"
4692               ;; "chdir" "chmod" "chown" "chr" "chroot" "close"
4693               ;; "closedir" "cmp" "connect" "continue" "cos" "crypt"
4694               ;; "dbmclose" "dbmopen" "die" "dump" "endgrent"
4695               ;; "endhostent" "endnetent" "endprotoent" "endpwent"
4696               ;; "endservent" "eof" "eq" "exec" "exit" "exp" "fcntl"
4697               ;; "fileno" "flock" "fork" "formline" "ge" "getc"
4698               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr"
4699               ;; "gethostbyname" "gethostent" "getlogin"
4700               ;; "getnetbyaddr" "getnetbyname" "getnetent"
4701               ;; "getpeername" "getpgrp" "getppid" "getpriority"
4702               ;; "getprotobyname" "getprotobynumber" "getprotoent"
4703               ;; "getpwent" "getpwnam" "getpwuid" "getservbyname"
4704               ;; "getservbyport" "getservent" "getsockname"
4705               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int"
4706               ;; "ioctl" "join" "kill" "lc" "lcfirst" "le" "length"
4707               ;; "link" "listen" "localtime" "log" "lstat" "lt"
4708               ;; "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd" "ne"
4709               ;; "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
4710               ;; "quotemeta" "rand" "read" "readdir" "readline"
4711               ;; "readlink" "readpipe" "recv" "ref" "rename" "require"
4712               ;; "reset" "reverse" "rewinddir" "rindex" "rmdir" "seek"
4713               ;; "seekdir" "select" "semctl" "semget" "semop" "send"
4714               ;; "setgrent" "sethostent" "setnetent" "setpgrp"
4715               ;; "setpriority" "setprotoent" "setpwent" "setservent"
4716               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite"
4717               ;; "shutdown" "sin" "sleep" "socket" "socketpair"
4718               ;; "sprintf" "sqrt" "srand" "stat" "substr" "symlink"
4719               ;; "syscall" "sysread" "system" "syswrite" "tell"
4720               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst"
4721               ;; "umask" "unlink" "unpack" "utime" "values" "vec"
4722               ;; "wait" "waitpid" "wantarray" "warn" "write" "x" "xor"
4723               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|" 
4724               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
4725               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
4726               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
4727               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
4728               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
4729               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
4730               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
4731               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
4732               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
4733               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
4734               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
4735               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
4736               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
4737               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
4738               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
4739               "\\(\\|ngth\\)\\|o\\(caltime\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
4740               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
4741               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
4742               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
4743               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
4744               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
4745               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
4746               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
4747               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
4748               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|tem\\|write\\)\\|"
4749               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
4750               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
4751               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
4752               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
4753               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\|PACKAGE__\\)"
4754               "\\)\\>") 2 'font-lock-type-face)
4755             ;; In what follows we use `other' style
4756             ;; for nonoverwritable builtins
4757             ;; Somehow 's', 'm' are not auto-generated???
4758             (list
4759              (concat
4760               "\\(^\\|[^$@%&\\]\\)\\<\\("
4761               ;; "AUTOLOAD" "BEGIN" "DESTROY" "END" "__END__" "chomp"
4762               ;; "chop" "defined" "delete" "do" "each" "else" "elsif"
4763               ;; "eval" "exists" "for" "foreach" "format" "goto"
4764               ;; "grep" "if" "keys" "last" "local" "map" "my" "next"
4765               ;; "no" "package" "pop" "pos" "print" "printf" "push"
4766               ;; "q" "qq" "qw" "qx" "redo" "return" "scalar" "shift"
4767               ;; "sort" "splice" "split" "study" "sub" "tie" "tr"
4768               ;; "undef" "unless" "unshift" "untie" "until" "use"
4769               ;; "while" "y"
4770               "AUTOLOAD\\|BEGIN\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
4771               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
4772               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|if\\|keys\\|"
4773               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|"
4774               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
4775               "q\\(\\|q\\|w\\|x\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
4776               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
4777               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
4778               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
4779               "\\|[sm]"                 ; Added manually
4780               "\\)\\>") 2 'font-lock-other-type-face)
4781             ;;          (mapconcat 'identity
4782             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
4783             ;;                       "#include" "#define" "#undef")
4784             ;;                     "\\|")
4785             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
4786               font-lock-function-name-face keep) ; Not very good, triggers at "[a-z]"
4787             '("\\<sub[ \t]+\\([^ \t{;]+\\)[ \t]*\\(([^()]*)[ \t]*\\)?[#{\n]" 1
4788               font-lock-function-name-face)
4789             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
4790               2 font-lock-function-name-face)
4791             '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
4792               1 font-lock-function-name-face)
4793             (cond ((featurep 'font-lock-extra)
4794                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}" 
4795                      (2 font-lock-string-face t)
4796                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
4797                   (font-lock-anchored
4798                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
4799                      (2 font-lock-string-face t)
4800                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
4801                       nil nil
4802                       (1 font-lock-string-face t))))
4803                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
4804                        2 font-lock-string-face t)))
4805             '("[\[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
4806               font-lock-string-face t)
4807             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1 
4808               font-lock-constant-face) ; labels
4809             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
4810               2 font-lock-constant-face)
4811             (cond ((featurep 'font-lock-extra)
4812                    '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
4813                      (3 font-lock-variable-name-face)
4814                      (4 '(another 4 nil
4815                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
4816                                    (1 font-lock-variable-name-face)
4817                                    (2 '(restart 2 nil) nil t))) 
4818                         nil t)))        ; local variables, multiple
4819                   (font-lock-anchored
4820                    '("^[ \t{}]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
4821                      (3 font-lock-variable-name-face)
4822                      ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)"
4823                       nil nil
4824                       (1 font-lock-variable-name-face))))
4825                   (t '("^[ \t{}]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
4826                        3 font-lock-variable-name-face)))
4827             '("\\<for\\(each\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
4828               2 font-lock-variable-name-face)))
4829           (setq 
4830            t-font-lock-keywords-1
4831            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
4832                 (not cperl-xemacs-p) ; not yet as of XEmacs 19.12
4833                 '(
4834                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
4835                    (if (eq (char-after (match-beginning 2)) ?%)
4836                        cperl-hash-face
4837                      cperl-array-face)
4838                    t)                   ; arrays and hashes
4839                   ("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
4840                    1
4841                    (if (= (- (match-end 2) (match-beginning 2)) 1) 
4842                        (if (eq (char-after (match-beginning 3)) ?{)
4843                            cperl-hash-face
4844                          cperl-array-face) ; arrays and hashes
4845                      font-lock-variable-name-face) ; Just to put something
4846                    t)
4847                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
4848                        ;;; Too much noise from \s* @s[ and friends
4849                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)" 
4850                   ;;(3 font-lock-function-name-face t t)
4851                   ;;(4
4852                   ;; (if (cperl-slash-is-regexp)
4853                   ;;    font-lock-function-name-face 'default) nil t))
4854                   )))
4855           (setq perl-font-lock-keywords-1 t-font-lock-keywords
4856                 perl-font-lock-keywords perl-font-lock-keywords-1
4857                 perl-font-lock-keywords-2 (append
4858                                            t-font-lock-keywords
4859                                            t-font-lock-keywords-1)))
4860         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
4861         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
4862             (eval                       ; Avoid a warning
4863             '(font-lock-require-faces
4864              (list
4865               ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
4866               (list 'font-lock-comment-face
4867                     ["Firebrick"        "OrangeRed"     "DimGray"       "Gray80"]
4868                     nil
4869                     [nil                nil             t               t       t]
4870                     [nil                nil             t               t       t]
4871                     nil)
4872               (list 'font-lock-string-face
4873                     ["RosyBrown"        "LightSalmon"   "Gray50"        "LightGray"]
4874                     nil
4875                     nil
4876                     [nil                nil             t               t       t]
4877                     nil)
4878               (list 'font-lock-keyword-face
4879                     ["Purple"           "LightSteelBlue" "DimGray"      "Gray90"]
4880                     nil
4881                     [nil                nil             t               t       t]
4882                     nil
4883                     nil)
4884               (list 'font-lock-function-name-face
4885                     (vector
4886                      "Blue"             "LightSkyBlue"  "Gray50"        "LightGray"
4887                      (cdr (assq 'background-color ; if mono
4888                                 (frame-parameters))))
4889                     (vector
4890                      nil                nil             nil             nil
4891                      (cdr (assq 'foreground-color ; if mono
4892                                 (frame-parameters))))
4893                     [nil                nil             t               t       t]
4894                     nil
4895                     nil)
4896               (list 'font-lock-variable-name-face
4897                     ["DarkGoldenrod"    "LightGoldenrod" "DimGray"      "Gray90"]
4898                     nil
4899                     [nil                nil             t               t       t]
4900                     [nil                nil             t               t       t]
4901                     nil)
4902               (list 'font-lock-type-face
4903                     ["DarkOliveGreen"   "PaleGreen"     "DimGray"       "Gray80"]
4904                     nil
4905                     [nil                nil             t               t       t]
4906                     nil
4907                     [nil                nil             t               t       t]
4908                     )
4909               (list 'font-lock-constant-face
4910                     ["CadetBlue"        "Aquamarine"    "Gray50"        "LightGray"]
4911                     nil
4912                     [nil                nil             t               t       t]
4913                     nil
4914                     [nil                nil             t               t       t]
4915                     )
4916               (list 'font-lock-other-type-face
4917                     ["chartreuse3"      ("orchid1" "orange")
4918                      nil                "Gray80"]
4919                     [nil                nil             "gray90"]
4920                     [nil                nil             nil             t       t]
4921                     [nil                nil             t               t]
4922                     [nil                nil             t               t       t]
4923                     )
4924               (list 'cperl-array-face
4925                     ["blue"             "yellow"        nil             "Gray80"]
4926                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
4927                      "gray90"]
4928                     t
4929                     nil
4930                     nil)
4931               (list 'cperl-hash-face
4932                     ["red"              "red"           nil             "Gray80"]
4933                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
4934                      "gray90"]
4935                     t
4936                     t
4937                     nil))))
4938           (defvar cperl-guessed-background nil
4939             "Display characteristics as guessed by cperl.")
4940           (or (fboundp 'x-color-defined-p)
4941               (defalias 'x-color-defined-p 
4942                 (cond ((fboundp 'color-defined-p) 'color-defined-p)
4943                       ;; XEmacs >= 19.12
4944                       ((fboundp 'valid-color-name-p) 'valid-color-name-p)
4945                       ;; XEmacs 19.11
4946                       (t 'x-valid-color-name-p))))
4947           (defvar font-lock-constant-face 'font-lock-constant-face)
4948           (defvar font-lock-variable-name-face 'font-lock-variable-name-face)
4949           (or (boundp 'font-lock-type-face)
4950               (defconst font-lock-type-face
4951                 'font-lock-type-face
4952                 "Face to use for data types."))
4953           (or (boundp 'font-lock-other-type-face)
4954               (defconst font-lock-other-type-face
4955                 'font-lock-other-type-face
4956                 "Face to use for data types from another group."))
4957           (if (not cperl-xemacs-p) nil
4958             (or (boundp 'font-lock-comment-face)
4959                 (defconst font-lock-comment-face
4960                   'font-lock-comment-face
4961                   "Face to use for comments."))
4962             (or (boundp 'font-lock-keyword-face)
4963                 (defconst font-lock-keyword-face
4964                   'font-lock-keyword-face
4965                   "Face to use for keywords."))
4966             (or (boundp 'font-lock-function-name-face)
4967                 (defconst font-lock-function-name-face
4968                   'font-lock-function-name-face
4969                   "Face to use for function names.")))
4970           (if (and
4971                (not (cperl-is-face 'cperl-array-face)) 
4972                (cperl-is-face 'font-lock-emphasized-face)) 
4973               (copy-face 'font-lock-emphasized-face 'cperl-emphasized-face))
4974           (if (and
4975                (not (cperl-is-face 'cperl-hash-face)) 
4976                (cperl-is-face 'font-lock-other-emphasized-face)) 
4977               (copy-face 'font-lock-other-emphasized-face 
4978                          'cperl-hash-face))
4979           (or (boundp 'cperl-hash-face)
4980               (defconst cperl-hash-face
4981                 'cperl-hash-face
4982                 "Face to use for another type of emphasizing."))
4983           (or (boundp 'cperl-emphasized-face)
4984               (defconst cperl-emphasized-face
4985                 'cperl-emphasized-face
4986                 "Face to use for emphasizing."))
4987           ;; Here we try to guess background
4988           (let ((background
4989                  (if (boundp 'font-lock-background-mode)
4990                      font-lock-background-mode
4991                    'light)) 
4992                 (face-list (and (fboundp 'face-list) (face-list)))
4993                 cperl-is-face)
4994             (fset 'cperl-is-face
4995                   (cond ((fboundp 'find-face)
4996                          (symbol-function 'find-face))
4997                         (face-list
4998                          (function (lambda (face) (member face face-list))))
4999                         (t
5000                          (function (lambda (face) (boundp face))))))
5001             (defvar cperl-guessed-background
5002               (if (and (boundp 'font-lock-display-type)
5003                        (eq font-lock-display-type 'grayscale))
5004                   'gray
5005                 background)
5006               "Background as guessed by CPerl mode")
5007             (if (and 
5008                  (not (cperl-is-face 'font-lock-constant-face)) 
5009                  (cperl-is-face 'font-lock-reference-face)) 
5010                 nil
5011               (copy-face 'font-lock-reference-face 'font-lock-constant-face))
5012             (if (cperl-is-face 'font-lock-type-face) nil
5013               (copy-face 'default 'font-lock-type-face)
5014               (cond
5015                ((eq background 'light)
5016                 (set-face-foreground 'font-lock-type-face
5017                                      (if (x-color-defined-p "seagreen")
5018                                          "seagreen"
5019                                        "sea green")))
5020                ((eq background 'dark)
5021                 (set-face-foreground 'font-lock-type-face
5022                                      (if (x-color-defined-p "os2pink")
5023                                          "os2pink"
5024                                        "pink")))
5025                (t
5026                 (set-face-background 'font-lock-type-face "gray90"))))
5027             (if (cperl-is-face 'font-lock-other-type-face)
5028                 nil
5029               (copy-face 'font-lock-type-face 'font-lock-other-type-face)
5030               (cond
5031                ((eq background 'light)
5032                 (set-face-foreground 'font-lock-other-type-face
5033                                      (if (x-color-defined-p "chartreuse3")
5034                                          "chartreuse3"
5035                                        "chartreuse")))
5036                ((eq background 'dark)
5037                 (set-face-foreground 'font-lock-other-type-face
5038                                      (if (x-color-defined-p "orchid1")
5039                                          "orchid1"
5040                                        "orange")))))
5041             (if (cperl-is-face 'font-lock-other-emphasized-face) nil
5042               (copy-face 'bold-italic 'font-lock-other-emphasized-face)
5043               (cond
5044                ((eq background 'light)
5045                 (set-face-background 'font-lock-other-emphasized-face
5046                                      (if (x-color-defined-p "lightyellow2")
5047                                          "lightyellow2"
5048                                        (if (x-color-defined-p "lightyellow")
5049                                            "lightyellow"
5050                                          "light yellow"))))
5051                ((eq background 'dark)
5052                 (set-face-background 'font-lock-other-emphasized-face
5053                                      (if (x-color-defined-p "navy")
5054                                          "navy"
5055                                        (if (x-color-defined-p "darkgreen")
5056                                            "darkgreen"
5057                                          "dark green"))))
5058                (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
5059             (if (cperl-is-face 'font-lock-emphasized-face) nil
5060               (copy-face 'bold 'font-lock-emphasized-face)
5061               (cond
5062                ((eq background 'light)
5063                 (set-face-background 'font-lock-emphasized-face
5064                                      (if (x-color-defined-p "lightyellow2")
5065                                          "lightyellow2"
5066                                        "lightyellow")))
5067                ((eq background 'dark)
5068                 (set-face-background 'font-lock-emphasized-face
5069                                      (if (x-color-defined-p "navy")
5070                                          "navy"
5071                                        (if (x-color-defined-p "darkgreen")
5072                                            "darkgreen"
5073                                          "dark green"))))
5074                (t (set-face-background 'font-lock-emphasized-face "gray90"))))
5075             (if (cperl-is-face 'font-lock-variable-name-face) nil
5076               (copy-face 'italic 'font-lock-variable-name-face))
5077             (if (cperl-is-face 'font-lock-constant-face) nil
5078               (copy-face 'italic 'font-lock-constant-face))))
5079         (setq cperl-faces-init t))
5080     (error nil)))
5081
5082
5083 (defun cperl-ps-print-init ()
5084   "Initialization of `ps-print' components for faces used in CPerl."
5085   ;; Guard against old versions
5086   (defvar ps-underlined-faces nil)
5087   (defvar ps-bold-faces nil)
5088   (defvar ps-italic-faces nil)
5089   (setq ps-bold-faces
5090         (append '(font-lock-emphasized-face
5091                   font-lock-keyword-face 
5092                   font-lock-variable-name-face 
5093                   font-lock-constant-face 
5094                   font-lock-reference-face 
5095                   font-lock-other-emphasized-face) 
5096                 ps-bold-faces))
5097   (setq ps-italic-faces
5098         (append '(font-lock-other-type-face
5099                   font-lock-constant-face 
5100                   font-lock-reference-face 
5101                   font-lock-other-emphasized-face)
5102                 ps-italic-faces))
5103   (setq ps-underlined-faces
5104         (append '(font-lock-emphasized-face
5105                   font-lock-other-emphasized-face 
5106                   font-lock-other-type-face font-lock-type-face)
5107                 ps-underlined-faces))
5108   (cons 'font-lock-type-face ps-underlined-faces))
5109
5110
5111 (if (cperl-enable-font-lock) (cperl-windowed-init))
5112
5113 (defconst cperl-styles-entries
5114   '(cperl-indent-level cperl-brace-offset cperl-continued-brace-offset     
5115     cperl-label-offset cperl-extra-newline-before-brace 
5116     cperl-merge-trailing-else
5117     cperl-continued-statement-offset))
5118
5119 (defconst cperl-style-alist
5120   '(("CPerl" ; =GNU without extra-newline-before-brace
5121      (cperl-indent-level               .  2)
5122      (cperl-brace-offset               .  0)
5123      (cperl-continued-brace-offset     .  0)
5124      (cperl-label-offset               . -2)
5125      (cperl-extra-newline-before-brace .  nil)
5126      (cperl-merge-trailing-else        .  t)
5127      (cperl-continued-statement-offset .  2))
5128     ("PerlStyle" ; CPerl with 4 as indent
5129      (cperl-indent-level               .  4)
5130      (cperl-brace-offset               .  0)
5131      (cperl-continued-brace-offset     .  0)
5132      (cperl-label-offset               . -4)
5133      (cperl-extra-newline-before-brace .  nil)
5134      (cperl-merge-trailing-else        .  t)
5135      (cperl-continued-statement-offset .  4))
5136     ("GNU"
5137      (cperl-indent-level               .  2)
5138      (cperl-brace-offset               .  0)
5139      (cperl-continued-brace-offset     .  0)
5140      (cperl-label-offset               . -2)
5141      (cperl-extra-newline-before-brace .  t)
5142      (cperl-merge-trailing-else        .  nil)
5143      (cperl-continued-statement-offset .  2))
5144     ("K&R"
5145      (cperl-indent-level               .  5)
5146      (cperl-brace-offset               .  0)
5147      (cperl-continued-brace-offset     . -5)
5148      (cperl-label-offset               . -5)
5149      ;;(cperl-extra-newline-before-brace .  nil) ; ???
5150      (cperl-merge-trailing-else        .  nil)
5151      (cperl-continued-statement-offset .  5))
5152     ("BSD"
5153      (cperl-indent-level               .  4)
5154      (cperl-brace-offset               .  0)
5155      (cperl-continued-brace-offset     . -4)
5156      (cperl-label-offset               . -4)
5157      ;;(cperl-extra-newline-before-brace .  nil) ; ???
5158      (cperl-continued-statement-offset .  4))
5159     ("C++"
5160      (cperl-indent-level               .  4)
5161      (cperl-brace-offset               .  0)
5162      (cperl-continued-brace-offset     . -4)
5163      (cperl-label-offset               . -4)
5164      (cperl-continued-statement-offset .  4)
5165      (cperl-merge-trailing-else        .  nil)
5166      (cperl-extra-newline-before-brace .  t))
5167     ("Current")
5168     ("Whitesmith"
5169      (cperl-indent-level               .  4)
5170      (cperl-brace-offset               .  0)
5171      (cperl-continued-brace-offset     .  0)
5172      (cperl-label-offset               . -4)
5173      ;;(cperl-extra-newline-before-brace .  nil) ; ???
5174      (cperl-continued-statement-offset .  4)))
5175   "(Experimental) list of variables to set to get a particular indentation style.
5176 Should be used via `cperl-set-style' or via CPerl menu.")
5177
5178 (defun cperl-set-style (style)
5179   "Set CPerl-mode variables to use one of several different indentation styles.
5180 The arguments are a string representing the desired style.
5181 The list of styles is in `cperl-style-alist', available styles 
5182 are GNU, K&R, BSD, C++ and Whitesmith.
5183
5184 The current value of style is memorized (unless there is a memorized
5185 data already), may be restored by `cperl-set-style-back'.
5186
5187 Chosing \"Current\" style will not change style, so this may be used for
5188 side-effect of memorizing only."
5189   (interactive 
5190    (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
5191                        cperl-style-alist)))
5192      (list (completing-read "Enter style: " list nil 'insist))))
5193   (or cperl-old-style
5194       (setq cperl-old-style
5195             (mapcar (function
5196                      (lambda (name)
5197                        (cons name (eval name))))
5198                     cperl-styles-entries)))
5199   (let ((style (cdr (assoc style cperl-style-alist))) setting str sym)
5200     (while style
5201       (setq setting (car style) style (cdr style))
5202       (set (car setting) (cdr setting)))))
5203
5204 (defun cperl-set-style-back ()
5205   "Restore a style memorised by `cperl-set-style'."
5206   (interactive)
5207   (or cperl-old-style (error "The style was not changed"))
5208   (let (setting)
5209     (while cperl-old-style
5210       (setq setting (car cperl-old-style) 
5211             cperl-old-style (cdr cperl-old-style))
5212       (set (car setting) (cdr setting)))))
5213
5214 (defun cperl-check-syntax ()
5215   (interactive)
5216   (require 'mode-compile)
5217   (let ((perl-dbg-flags (concat cperl-extra-perl-args " -wc")))
5218     (eval '(mode-compile))))            ; Avoid a warning
5219
5220 (defun cperl-info-buffer (type)
5221   ;; Returns buffer with documentation.  Creates if missing.
5222   ;; If TYPE, this vars buffer.
5223   ;; Special care is taken to not stomp over an existing info buffer
5224   (let* ((bname (if type "*info-perl-var*" "*info-perl*"))
5225          (info (get-buffer bname))
5226          (oldbuf (get-buffer "*info*")))
5227     (if info info
5228       (save-window-excursion
5229         ;; Get Info running
5230         (require 'info)
5231         (cond (oldbuf
5232                (set-buffer oldbuf)
5233                (rename-buffer "*info-perl-tmp*")))
5234         (save-window-excursion
5235           (info))
5236         (Info-find-node cperl-info-page (if type "perlvar" "perlfunc"))
5237         (set-buffer "*info*")
5238         (rename-buffer bname)
5239         (cond (oldbuf
5240                (set-buffer "*info-perl-tmp*")
5241                (rename-buffer "*info*")
5242                (set-buffer bname)))
5243         (make-variable-buffer-local 'window-min-height)
5244         (setq window-min-height 2)
5245         (current-buffer)))))
5246
5247 (defun cperl-word-at-point (&optional p)
5248   ;; Returns the word at point or at P.
5249   (save-excursion
5250     (if p (goto-char p))
5251     (or (cperl-word-at-point-hard)
5252         (progn
5253           (require 'etags)
5254           (funcall (or (and (boundp 'find-tag-default-function)
5255                             find-tag-default-function)
5256                        (get major-mode 'find-tag-default-function)
5257                        ;; XEmacs 19.12 has `find-tag-default-hook'; it is
5258                        ;; automatically used within `find-tag-default':
5259                        'find-tag-default))))))
5260
5261 (defun cperl-info-on-command (command)
5262   "Shows documentation for Perl command in other window.
5263 If perl-info buffer is shown in some frame, uses this frame.
5264 Customized by setting variables `cperl-shrink-wrap-info-frame',
5265 `cperl-max-help-size'."
5266   (interactive 
5267    (let* ((default (cperl-word-at-point))
5268           (read (read-string 
5269                      (format "Find doc for Perl function (default %s): " 
5270                              default))))
5271      (list (if (equal read "") 
5272                    default 
5273                  read))))
5274
5275   (let ((buffer (current-buffer))
5276         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
5277         pos isvar height iniheight frheight buf win fr1 fr2 iniwin not-loner
5278         max-height char-height buf-list)
5279     (if (string-match "^-[a-zA-Z]$" command)
5280         (setq cmd-desc "^-X[ \t\n]"))
5281     (setq isvar (string-match "^[$@%]" command)
5282           buf (cperl-info-buffer isvar)
5283           iniwin (selected-window)
5284           fr1 (window-frame iniwin))
5285     (set-buffer buf)
5286     (beginning-of-buffer)
5287     (or isvar 
5288         (progn (re-search-forward "^-X[ \t\n]")
5289                (forward-line -1)))
5290     (if (re-search-forward cmd-desc nil t)
5291         (progn
5292           ;; Go back to beginning of the group (ex, for qq)
5293           (if (re-search-backward "^[ \t\n\f]")
5294               (forward-line 1))
5295           (beginning-of-line)
5296           ;; Get some of 
5297           (setq pos (point)
5298                 buf-list (list buf "*info-perl-var*" "*info-perl*"))
5299           (while (and (not win) buf-list)
5300             (setq win (get-buffer-window (car buf-list) t))
5301             (setq buf-list (cdr buf-list)))
5302           (or (not win)
5303               (eq (window-buffer win) buf)
5304               (set-window-buffer win buf))
5305           (and win (setq fr2 (window-frame win)))
5306           (if (or (not fr2) (eq fr1 fr2))
5307               (pop-to-buffer buf)
5308             (special-display-popup-frame buf) ; Make it visible
5309             (select-window win))
5310           (goto-char pos)               ; Needed (?!).
5311           ;; Resize
5312           (setq iniheight (window-height)
5313                 frheight (frame-height)
5314                 not-loner (< iniheight (1- frheight))) ; Are not alone
5315           (cond ((if not-loner cperl-max-help-size 
5316                    cperl-shrink-wrap-info-frame)
5317                  (setq height 
5318                        (+ 2 
5319                           (count-lines 
5320                            pos 
5321                            (save-excursion
5322                              (if (re-search-forward
5323                                   "^[ \t][^\n]*\n+\\([^ \t\n\f]\\|\\'\\)" nil t)
5324                                  (match-beginning 0) (point-max)))))
5325                        max-height 
5326                        (if not-loner
5327                            (/ (* (- frheight 3) cperl-max-help-size) 100)
5328                          (setq char-height (frame-char-height))
5329                          ;; Non-functioning under OS/2:
5330                          (if (eq char-height 1) (setq char-height 18))
5331                          ;; Title, menubar, + 2 for slack
5332                          (- (/ (x-display-pixel-height) char-height) 4)
5333                          ))
5334                  (if (> height max-height) (setq height max-height))
5335                  ;;(message "was %s doing %s" iniheight height)
5336                  (if not-loner
5337                      (enlarge-window (- height iniheight))
5338                    (set-frame-height (window-frame win) (1+ height)))))
5339           (set-window-start (selected-window) pos))
5340       (message "No entry for %s found." command))
5341     ;;(pop-to-buffer buffer)
5342     (select-window iniwin)))
5343
5344 (defun cperl-info-on-current-command ()
5345   "Shows documentation for Perl command at point in other window."
5346   (interactive)
5347   (cperl-info-on-command (cperl-word-at-point)))
5348
5349 (defun cperl-imenu-info-imenu-search ()
5350   (if (looking-at "^-X[ \t\n]") nil
5351     (re-search-backward
5352      "^\n\\([-a-zA-Z_]+\\)[ \t\n]")
5353     (forward-line 1)))
5354
5355 (defun cperl-imenu-info-imenu-name ()  
5356   (buffer-substring
5357    (match-beginning 1) (match-end 1)))
5358
5359 (defun cperl-imenu-on-info ()
5360   (interactive)
5361   (let* ((buffer (current-buffer))
5362          imenu-create-index-function
5363          imenu-prev-index-position-function 
5364          imenu-extract-index-name-function 
5365          (index-item (save-restriction
5366                        (save-window-excursion
5367                          (set-buffer (cperl-info-buffer nil))
5368                          (setq imenu-create-index-function 
5369                                'imenu-default-create-index-function
5370                                imenu-prev-index-position-function
5371                                'cperl-imenu-info-imenu-search
5372                                imenu-extract-index-name-function
5373                                'cperl-imenu-info-imenu-name)
5374                          (imenu-choose-buffer-index)))))
5375     (and index-item
5376          (progn
5377            (push-mark)
5378            (pop-to-buffer "*info-perl*")
5379            (cond
5380             ((markerp (cdr index-item))
5381              (goto-char (marker-position (cdr index-item))))
5382             (t
5383              (goto-char (cdr index-item))))
5384            (set-window-start (selected-window) (point))
5385            (pop-to-buffer buffer)))))
5386
5387 (defun cperl-lineup (beg end &optional step minshift)
5388   "Lineup construction in a region.
5389 Beginning of region should be at the start of a construction.
5390 All first occurrences of this construction in the lines that are
5391 partially contained in the region are lined up at the same column.
5392
5393 MINSHIFT is the minimal amount of space to insert before the construction.
5394 STEP is the tabwidth to position constructions.
5395 If STEP is `nil', `cperl-lineup-step' will be used 
5396 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
5397 Will not move the position at the start to the left."
5398   (interactive "r")
5399   (let (search col tcol seen b e)
5400     (save-excursion
5401       (goto-char end)
5402       (end-of-line)
5403       (setq end (point-marker))
5404       (goto-char beg)
5405       (skip-chars-forward " \t\f")
5406       (setq beg (point-marker))
5407       (indent-region beg end nil)
5408       (goto-char beg)
5409       (setq col (current-column))
5410       (if (looking-at "[a-zA-Z0-9_]")
5411           (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
5412               (setq search
5413                     (concat "\\<" 
5414                             (regexp-quote 
5415                              (buffer-substring (match-beginning 0)
5416                                                (match-end 0))) "\\>"))
5417             (error "Cannot line up in a middle of the word"))
5418         (if (looking-at "$")
5419             (error "Cannot line up end of line"))
5420         (setq search (regexp-quote (char-to-string (following-char)))))
5421       (setq step (or step cperl-lineup-step cperl-indent-level))
5422       (or minshift (setq minshift 1))
5423       (while (progn
5424                (beginning-of-line 2)
5425                (and (< (point) end) 
5426                     (re-search-forward search end t)
5427                     (goto-char (match-beginning 0))))
5428         (setq tcol (current-column) seen t)
5429         (if (> tcol col) (setq col tcol)))
5430       (or seen
5431           (error "The construction to line up occurred only once"))
5432       (goto-char beg)
5433       (setq col (+ col minshift))
5434       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
5435       (while 
5436           (progn
5437             (setq e (point))
5438             (skip-chars-backward " \t")
5439             (delete-region (point) e)
5440             (indent-to-column col); (make-string (- col (current-column)) ?\ ))
5441             (beginning-of-line 2) 
5442             (and (< (point) end) 
5443                  (re-search-forward search end t)
5444                  (goto-char (match-beginning 0)))))))) ; No body
5445
5446 (defun cperl-etags (&optional add all files)
5447   "Run etags with appropriate options for Perl files.
5448 If optional argument ALL is `recursive', will process Perl files
5449 in subdirectories too."
5450   (interactive)
5451   (let ((cmd "etags")
5452         (args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\(([^()]*)[ \t]*\\)?\\([{#]\\|$\\)\\)/\\4/"))
5453         res)
5454     (if add (setq args (cons "-a" args)))
5455     (or files (setq files (list buffer-file-name)))
5456     (cond
5457      ((eq all 'recursive)
5458       ;;(error "Not implemented: recursive")
5459       (setq args (append (list "-e" 
5460                                "sub wanted {push @ARGV, $File::Find::name if /\\.[pP][Llm]$/}
5461                                 use File::Find;
5462                                 find(\\&wanted, '.');
5463                                 exec @ARGV;" 
5464                                cmd) args)
5465             cmd "perl"))
5466      (all 
5467       ;;(error "Not implemented: all")
5468       (setq args (append (list "-e" 
5469                                "push @ARGV, <*.PL *.pl *.pm>;
5470                                 exec @ARGV;" 
5471                                cmd) args)
5472             cmd "perl"))
5473      (t
5474       (setq args (append args files))))
5475     (setq res (apply 'call-process cmd nil nil nil args))
5476     (or (eq res 0)
5477         (message "etags returned \"%s\"" res))))
5478
5479 (defun cperl-toggle-auto-newline ()
5480   "Toggle the state of `cperl-auto-newline'."
5481   (interactive)
5482   (setq cperl-auto-newline (not cperl-auto-newline))
5483   (message "Newlines will %sbe auto-inserted now." 
5484            (if cperl-auto-newline "" "not ")))
5485
5486 (defun cperl-toggle-abbrev ()
5487   "Toggle the state of automatic keyword expansion in CPerl mode."
5488   (interactive)
5489   (abbrev-mode (if abbrev-mode 0 1))
5490   (message "Perl control structure will %sbe auto-inserted now." 
5491            (if abbrev-mode "" "not ")))
5492
5493
5494 (defun cperl-toggle-electric ()
5495   "Toggle the state of parentheses doubling in CPerl mode."
5496   (interactive)
5497   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
5498   (message "Parentheses will %sbe auto-doubled now." 
5499            (if (cperl-val 'cperl-electric-parens) "" "not ")))
5500
5501 (defun cperl-toggle-autohelp ()
5502   "Toggle the state of automatic help message in CPerl mode.
5503 See `cperl-lazy-help-time' too."
5504   (interactive)
5505   (if (fboundp 'run-with-idle-timer)
5506       (progn
5507         (if cperl-lazy-installed
5508             (eval '(cperl-lazy-unstall))
5509           (cperl-lazy-install))
5510         (message "Perl help messages will %sbe automatically shown now." 
5511                  (if cperl-lazy-installed "" "not ")))
5512     (message "Cannot automatically show Perl help messages - run-with-idle-timer missing.")))
5513
5514 (defun cperl-toggle-construct-fix ()
5515   "Toggle whether `indent-region'/`indent-sexp' fix whitespace too."
5516   (interactive)
5517   (setq cperl-indent-region-fix-constructs 
5518         (not cperl-indent-region-fix-constructs))
5519   (message "indent-region/indent-sexp will %sbe automatically fix whitespace." 
5520            (if cperl-indent-region-fix-constructs "" "not ")))
5521
5522 ;;;; Tags file creation.
5523
5524 (defvar cperl-tmp-buffer " *cperl-tmp*")
5525
5526 (defun cperl-setup-tmp-buf ()
5527   (set-buffer (get-buffer-create cperl-tmp-buffer))
5528   (set-syntax-table cperl-mode-syntax-table)
5529   (buffer-disable-undo)
5530   (auto-fill-mode 0)
5531   (if cperl-use-syntax-table-text-property-for-tags
5532       (progn
5533         (make-variable-buffer-local 'parse-sexp-lookup-properties)
5534         ;; Do not introduce variable if not needed, we check it!
5535         (set 'parse-sexp-lookup-properties t))))
5536
5537 (defun cperl-xsub-scan ()
5538   (require 'cl)
5539   (require 'imenu)
5540   (let ((index-alist '()) 
5541         (prev-pos 0) index index1 name package prefix)
5542     (goto-char (point-min))
5543     (if noninteractive
5544         (message "Scanning XSUB for index")
5545       (imenu-progress-message prev-pos 0))
5546     ;; Search for the function
5547     (progn ;;save-match-data
5548       (while (re-search-forward
5549               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
5550               nil t)
5551         (or noninteractive
5552             (imenu-progress-message prev-pos))
5553         (cond
5554          ((match-beginning 2)   ; SECTION
5555           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
5556           (goto-char (match-beginning 0))
5557           (skip-chars-forward " \t")
5558           (forward-char 1)
5559           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
5560               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
5561             (setq prefix nil)))
5562          ((not package) nil)            ; C language section
5563          ((match-beginning 3)           ; XSUB
5564           (goto-char (1+ (match-beginning 3)))
5565           (setq index (imenu-example--name-and-position))
5566           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
5567           (if (and prefix (string-match (concat "^" prefix) name))
5568               (setq name (substring name (length prefix))))
5569           (cond ((string-match "::" name) nil)
5570                 (t
5571                  (setq index1 (cons (concat package "::" name) (cdr index)))
5572                  (push index1 index-alist)))
5573           (setcar index name)
5574           (push index index-alist))
5575          (t                             ; BOOT: section
5576           ;; (beginning-of-line)
5577           (setq index (imenu-example--name-and-position))
5578           (setcar index (concat package "::BOOT:"))
5579           (push index index-alist)))))
5580     (or noninteractive
5581         (imenu-progress-message prev-pos 100))
5582     index-alist))
5583
5584 (defun cperl-find-tags (file xs topdir)
5585   (let (ind (b (get-buffer cperl-tmp-buffer)) lst elt pos ret rel
5586             (cperl-pod-here-fontify nil))
5587     (save-excursion
5588       (if b (set-buffer b)
5589           (cperl-setup-tmp-buf))
5590       (erase-buffer)
5591       (setq file (car (insert-file-contents file)))
5592       (message "Scanning file %s ..." file)
5593       (if (and cperl-use-syntax-table-text-property-for-tags
5594                (not xs))
5595           (condition-case err           ; after __END__ may have garbage
5596               (cperl-find-pods-heres)
5597             (error (message "While scanning for syntax: %s" err))))
5598       (if xs
5599           (setq lst (cperl-xsub-scan))
5600         (setq ind (imenu-example--create-perl-index))
5601         (setq lst (cdr (assoc "+Unsorted List+..." ind))))
5602       (setq lst 
5603             (mapcar 
5604              (function 
5605               (lambda (elt)
5606                 (cond ((string-match "^[_a-zA-Z]" (car elt))
5607                        (goto-char (cdr elt))
5608                        (list (car elt) 
5609                              (point) (count-lines 1 (point))
5610                              (buffer-substring (progn
5611                                                  (skip-chars-forward 
5612                                                   ":_a-zA-Z0-9")
5613                                                  (or (eolp) (forward-char 1))
5614                                                  (point))
5615                                                (progn
5616                                                  (beginning-of-line)
5617                                                  (point))))))))
5618                     lst))
5619       (erase-buffer)
5620       (while lst
5621         (setq elt (car lst) lst (cdr lst))
5622         (if elt
5623             (progn
5624               (insert (elt elt 3) 
5625                       127
5626                       (if (string-match "^package " (car elt))
5627                           (substring (car elt) 8)
5628                         (car elt) )
5629                       1
5630                       (number-to-string (elt elt 1))
5631                       ","
5632                       (number-to-string (elt elt 2))
5633                       "\n")
5634               (if (and (string-match "^[_a-zA-Z]+::" (car elt))
5635                        (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
5636                                      (elt elt 3)))
5637                   ;; Need to insert the name without package as well
5638                   (setq lst (cons (cons (substring (elt elt 3) 
5639                                                    (match-beginning 1)
5640                                                    (match-end 1))
5641                                         (cdr elt))
5642                                   lst))))))
5643       (setq pos (point))
5644       (goto-char 1)
5645       (setq rel file)
5646       ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
5647       (set-text-properties 0 (length rel) nil rel)
5648       (and (equal topdir (substring rel 0 (length topdir)))
5649            (setq rel (substring file (length topdir))))
5650       (insert "\f\n" rel "," (number-to-string (1- pos)) "\n")
5651       (setq ret (buffer-substring 1 (point-max)))
5652       (erase-buffer)
5653       (or noninteractive
5654           (message "Scanning file %s finished" file))
5655       ret)))
5656
5657 (defun cperl-add-tags-recurse-noxs ()
5658   "Add to TAGS data for Perl and XSUB files in the current directory and kids.
5659 Use as
5660   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
5661         -f cperl-add-tags-recurse 
5662 "
5663   (cperl-write-tags nil nil t t nil t))
5664
5665 (defun cperl-add-tags-recurse ()
5666   "Add to TAGS file data for Perl files in the current directory and kids.
5667 Use as
5668   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
5669         -f cperl-add-tags-recurse 
5670 "
5671   (cperl-write-tags nil nil t t))
5672
5673 (defun cperl-write-tags (&optional file erase recurse dir inbuffer noxs topdir)
5674   ;; If INBUFFER, do not select buffer, and do not save
5675   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
5676   (require 'etags)
5677   (if file nil
5678     (setq file (if dir default-directory (buffer-file-name)))
5679     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
5680   (or topdir
5681       (setq topdir default-directory))
5682   (let ((tags-file-name "TAGS")
5683         (case-fold-search (eq system-type 'emx))
5684         xs)
5685     (save-excursion
5686       (cond (inbuffer nil)              ; Already there
5687             ((file-exists-p tags-file-name)
5688              (visit-tags-table-buffer tags-file-name))
5689             (t (set-buffer (find-file-noselect tags-file-name))))
5690       (cond
5691        (dir
5692         (cond ((eq erase 'ignore))
5693               (erase
5694                (erase-buffer)
5695                (setq erase 'ignore)))
5696         (let ((files 
5697                (directory-files file t 
5698                                 (if recurse nil cperl-scan-files-regexp)
5699                                 t)))
5700           (mapcar (function (lambda (file)
5701                               (cond
5702                                ((string-match cperl-noscan-files-regexp file)
5703                                 nil)
5704                                ((not (file-directory-p file))
5705                                 (if (string-match cperl-scan-files-regexp file)
5706                                     (cperl-write-tags file erase recurse nil t noxs topdir)))
5707                                ((not recurse) nil)
5708                                (t (cperl-write-tags file erase recurse t t noxs topdir)))))
5709                   files))
5710         )
5711        (t
5712         (setq xs (string-match "\\.xs$" file))
5713         (if (not (and xs noxs))
5714             (progn
5715               (cond ((eq erase 'ignore) (goto-char (point-max)))
5716                   (erase (erase-buffer))
5717                   (t
5718                    (goto-char 1)
5719                    (if (search-forward (concat "\f\n" file ",") nil t)
5720                        (progn
5721                          (search-backward "\f\n")
5722                          (delete-region (point)
5723                                         (save-excursion
5724                                           (forward-char 1)
5725                                           (if (search-forward "\f\n" 
5726                                                               nil 'toend)
5727                                               (- (point) 2)
5728                                             (point-max)))))
5729                      (goto-char (point-max)))))
5730               (insert (cperl-find-tags file xs topdir))))))
5731       (if inbuffer nil          ; Delegate to the caller
5732         (save-buffer 0)         ; No backup
5733         (if (fboundp 'initialize-new-tags-table) ; Do we need something special in XEmacs?
5734             (initialize-new-tags-table))))))
5735
5736 (defvar cperl-tags-hier-regexp-list
5737   (concat 
5738    "^\\("
5739       "\\(package\\)\\>"
5740      "\\|"
5741       "sub\\>[^\n]+::"
5742      "\\|"
5743       "[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::" ; XSUB?
5744      "\\|"
5745       "[ \t]*BOOT:\C-?[^\n]+::"         ; BOOT section
5746    "\\)"))
5747
5748 (defvar cperl-hierarchy '(() ())
5749   "Global hierarchy of classes")
5750
5751 (defun cperl-tags-hier-fill ()
5752   ;; Suppose we are in a tag table cooked by cperl.
5753   (goto-char 1)
5754   (let (type pack name pos line chunk ord cons1 file str info fileind)
5755     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
5756       (setq pos (match-beginning 0) 
5757             pack (match-beginning 2))
5758       (beginning-of-line)
5759       (if (looking-at (concat
5760                        "\\([^\n]+\\)"
5761                        "\C-?"
5762                        "\\([^\n]+\\)"
5763                        "\C-a"
5764                        "\\([0-9]+\\)"
5765                        ","
5766                        "\\([0-9]+\\)"))
5767           (progn
5768             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
5769                   name (buffer-substring (match-beginning 2) (match-end 2))
5770                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
5771                   line (buffer-substring (match-beginning 4) (match-end 4))
5772                   ord (if pack 1 0)
5773                   info (etags-snarf-tag) ; Moves to beginning of the next line
5774                   file (file-of-tag)
5775                   fileind (format "%s:%s" file line))
5776             ;; Move back
5777             (forward-char -1)
5778             ;; Make new member of hierarchy name ==> file ==> pos if needed
5779             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
5780                 ;; Name known
5781                 (setcdr cons1 (cons (cons fileind (vector file info))
5782                                     (cdr cons1)))
5783               ;; First occurrence of the name, start alist
5784               (setq cons1 (cons name (list (cons fileind (vector file info)))))
5785               (if pack 
5786                   (setcar (cdr cperl-hierarchy)
5787                           (cons cons1 (nth 1 cperl-hierarchy)))
5788                 (setcar cperl-hierarchy
5789                         (cons cons1 (car cperl-hierarchy)))))))
5790       (end-of-line))))
5791
5792 (defun cperl-tags-hier-init (&optional update)
5793   "Show hierarchical menu of classes and methods.
5794 Finds info about classes by a scan of loaded TAGS files.
5795 Supposes that the TAGS files contain fully qualified function names.
5796 One may build such TAGS files from CPerl mode menu."
5797   (interactive)
5798   (require 'etags)
5799   (require 'imenu)
5800   (if (or update (null (nth 2 cperl-hierarchy)))
5801       (let (pack name cons1 to l1 l2 l3 l4
5802                  (remover (function (lambda (elt) ; (name (file1...) (file2..))
5803                                       (or (nthcdr 2 elt)
5804                                           ;; Only in one file
5805                                           (setcdr elt (cdr (nth 1 elt))))))))
5806         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
5807         (setq cperl-hierarchy (list l1 l2 l3))
5808         (or tags-table-list
5809             (call-interactively 'visit-tags-table))
5810         (message "Updating list of classes...")
5811         (mapcar 
5812          (function
5813           (lambda (tagsfile)
5814             (set-buffer (get-file-buffer tagsfile))
5815             (cperl-tags-hier-fill)))
5816          tags-table-list)
5817         (mapcar remover (car cperl-hierarchy))
5818         (mapcar remover (nth 1 cperl-hierarchy))
5819         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
5820                        (cons "Methods: " (car cperl-hierarchy))))
5821         (cperl-tags-treeify to 1)
5822         (setcar (nthcdr 2 cperl-hierarchy)
5823                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
5824         (message "Updating list of classes: done, requesting display...")
5825         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
5826         ))
5827   (or (nth 2 cperl-hierarchy)
5828       (error "No items found"))
5829   (setq update
5830 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
5831         (if window-system
5832             (x-popup-menu t (nth 2 cperl-hierarchy))
5833           (require 'tmm)
5834           (tmm-prompt (nth 2 cperl-hierarchy))))
5835   (if (and update (listp update))
5836       (progn (while (cdr update) (setq update (cdr update)))
5837              (setq update (car update)))) ; Get the last from the list
5838   (if (vectorp update) 
5839       (progn
5840         (find-file (elt update 0))
5841         (etags-goto-tag-location (elt update 1))))
5842   (if (eq update -999) (cperl-tags-hier-init t)))
5843
5844 (defun cperl-tags-treeify (to level)
5845   ;; cadr of `to' is read-write.  On start it is a cons
5846   (let* ((regexp (concat "^\\(" (mapconcat 
5847                                  'identity
5848                                  (make-list level "[_a-zA-Z0-9]+")
5849                                  "::")
5850                          "\\)\\(::\\)?"))
5851          (packages (cdr (nth 1 to)))
5852          (methods (cdr (nth 2 to)))
5853          l1 head tail cons1 cons2 ord writeto packs recurse
5854          root-packages root-functions ms many_ms same_name ps
5855          (move-deeper
5856           (function 
5857            (lambda (elt)
5858              (cond ((and (string-match regexp (car elt))
5859                          (or (eq ord 1) (match-end 2)))
5860                     (setq head (substring (car elt) 0 (match-end 1))
5861                           tail (if (match-end 2) (substring (car elt) 
5862                                                             (match-end 2)))
5863                           recurse t)
5864                     (if (setq cons1 (assoc head writeto)) nil
5865                       ;; Need to init new head
5866                       (setcdr writeto (cons (list head (list "Packages: ")
5867                                                   (list "Methods: "))
5868                                             (cdr writeto)))
5869                       (setq cons1 (nth 1 writeto)))
5870                     (setq cons2 (nth ord cons1)) ; Either packs or meths
5871                     (setcdr cons2 (cons elt (cdr cons2))))
5872                    ((eq ord 2)
5873                     (setq root-functions (cons elt root-functions)))
5874                    (t
5875                     (setq root-packages (cons elt root-packages))))))))
5876     (setcdr to l1)                      ; Init to dynamic space
5877     (setq writeto to)
5878     (setq ord 1)
5879     (mapcar move-deeper packages)
5880     (setq ord 2)
5881     (mapcar move-deeper methods)
5882     (if recurse
5883         (mapcar (function (lambda (elt)
5884                           (cperl-tags-treeify elt (1+ level))))
5885                 (cdr to)))
5886     ;;Now clean up leaders with one child only
5887     (mapcar (function (lambda (elt)
5888                         (if (not (and (listp (cdr elt)) 
5889                                       (eq (length elt) 2))) nil
5890                             (setcar elt (car (nth 1 elt)))
5891                             (setcdr elt (cdr (nth 1 elt))))))
5892             (cdr to))
5893     ;; Sort the roots of subtrees
5894     (if (default-value 'imenu-sort-function)
5895         (setcdr to
5896                 (sort (cdr to) (default-value 'imenu-sort-function))))
5897     ;; Now add back functions removed from display
5898     (mapcar (function (lambda (elt)
5899                         (setcdr to (cons elt (cdr to)))))
5900             (if (default-value 'imenu-sort-function)
5901                 (nreverse
5902                  (sort root-functions (default-value 'imenu-sort-function)))
5903               root-functions))
5904     ;; Now add back packages removed from display
5905     (mapcar (function (lambda (elt)
5906                         (setcdr to (cons (cons (concat "package " (car elt)) 
5907                                                (cdr elt)) 
5908                                          (cdr to)))))
5909             (if (default-value 'imenu-sort-function)
5910                 (nreverse 
5911                  (sort root-packages (default-value 'imenu-sort-function)))
5912               root-packages))
5913     ))
5914
5915 ;;;(x-popup-menu t
5916 ;;;   '(keymap "Name1" 
5917 ;;;         ("Ret1" "aa")
5918 ;;;         ("Head1" "ab"  
5919 ;;;          keymap "Name2" 
5920 ;;;          ("Tail1" "x") ("Tail2" "y"))))
5921
5922 (defun cperl-list-fold (list name limit)
5923   (let (list1 list2 elt1 (num 0))
5924     (if (<= (length list) limit) list
5925       (setq list1 nil list2 nil)
5926       (while list
5927         (setq num (1+ num) 
5928               elt1 (car list)
5929               list (cdr list))
5930         (if (<= num imenu-max-items)
5931             (setq list2 (cons elt1 list2))
5932           (setq list1 (cons (cons name
5933                                   (nreverse list2))
5934                             list1)
5935                 list2 (list elt1)
5936                 num 1)))
5937       (nreverse (cons (cons name
5938                             (nreverse list2))
5939                       list1)))))
5940
5941 (defun cperl-menu-to-keymap (menu &optional name)
5942   (let (list)
5943     (cons 'keymap 
5944           (mapcar 
5945            (function 
5946             (lambda (elt)
5947               (cond ((listp (cdr elt))
5948                      (setq list (cperl-list-fold
5949                                  (cdr elt) (car elt) imenu-max-items))
5950                      (cons nil
5951                            (cons (car elt)
5952                                  (cperl-menu-to-keymap list))))
5953                     (t
5954                      (list (cdr elt) (car elt) t))))) ; t is needed in 19.34
5955            (cperl-list-fold menu "Root" imenu-max-items)))))
5956
5957 \f
5958 (defvar cperl-bad-style-regexp
5959   (mapconcat 'identity
5960    '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
5961      "[-<>=+^&|]+[^- \t\n=+<>~]"        ; sign+ char
5962      )
5963    "\\|")
5964   "Finds places such that insertion of a whitespace may help a lot.")
5965
5966 (defvar cperl-not-bad-style-regexp 
5967   (mapconcat 'identity
5968    '("[^-\t <>=+]\\(--\\|\\+\\+\\)"     ; var-- var++
5969      "[a-zA-Z0-9_][|&][a-zA-Z0-9_$]"    ; abc|def abc&def are often used.
5970      "&[(a-zA-Z0-9_$]"                  ; &subroutine &(var->field)
5971      "<\\$?\\sw+\\(\\.\\sw+\\)?>"       ; <IN> <stdin.h>
5972      "-[a-zA-Z][ \t]+[_$\"'`]"          ; -f file
5973      "-[0-9]"                           ; -5
5974      "\\+\\+"                           ; ++var
5975      "--"                               ; --var
5976      ".->"                              ; a->b
5977      "->"                               ; a SPACE ->b
5978      "\\[-"                             ; a[-1]
5979      "^="                               ; =head
5980      "||"
5981      "&&"
5982      "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
5983      "-[a-zA-Z_0-9]+[ \t]*=>"                   ; -option => value
5984      ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
5985      ;;"[*/+-|&<.]+="
5986      )
5987    "\\|")
5988   "If matches at the start of match found by `my-bad-c-style-regexp',
5989 insertion of a whitespace will not help.")
5990
5991 (defvar found-bad)
5992
5993 (defun cperl-find-bad-style ()
5994   "Find places in the buffer where insertion of a whitespace may help.
5995 Prompts user for insertion of spaces.
5996 Currently it is tuned to C and Perl syntax."
5997   (interactive)
5998   (let (found-bad (p (point)))
5999     (setq last-nonmenu-event 13)        ; To disable popup
6000     (beginning-of-buffer)
6001     (map-y-or-n-p "Insert space here? "
6002                   (function (lambda (arg) (insert " ")))
6003                   'cperl-next-bad-style
6004                   '("location" "locations" "insert a space into") 
6005                   '((?\C-r (lambda (arg)
6006                              (let ((buffer-quit-function
6007                                     'exit-recursive-edit))
6008                                (message "Exit with Esc Esc")
6009                                (recursive-edit)
6010                                t))      ; Consider acted upon
6011                            "edit, exit with Esc Esc") 
6012                     (?e (lambda (arg)
6013                           (let ((buffer-quit-function
6014                                  'exit-recursive-edit))
6015                             (message "Exit with Esc Esc")
6016                             (recursive-edit)
6017                             t))         ; Consider acted upon
6018                         "edit, exit with Esc Esc"))
6019                   t)
6020     (if found-bad (goto-char found-bad)
6021       (goto-char p)
6022       (message "No appropriate place found"))))
6023
6024 (defun cperl-next-bad-style ()
6025   (let (p (not-found t) (point (point)) found)
6026     (while (and not-found
6027                 (re-search-forward cperl-bad-style-regexp nil 'to-end))
6028       (setq p (point))
6029       (goto-char (match-beginning 0))
6030       (if (or
6031            (looking-at cperl-not-bad-style-regexp)
6032            ;; Check for a < -b and friends
6033            (and (eq (following-char) ?\-)
6034                 (save-excursion
6035                   (skip-chars-backward " \t\n")
6036                   (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\(, ?\[, ?\{))))
6037            ;; Now check for syntax type
6038            (save-match-data
6039              (setq found (point))
6040              (beginning-of-defun)
6041              (let ((pps (parse-partial-sexp (point) found)))
6042                (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
6043           (goto-char (match-end 0))
6044         (goto-char (1- p))
6045         (setq not-found nil
6046               found-bad found)))
6047     (not not-found)))
6048
6049 \ 6
6050 ;;; Getting help
6051 (defvar cperl-have-help-regexp 
6052   ;;(concat "\\("
6053   (mapconcat
6054    'identity
6055    '("[$@%*&][0-9a-zA-Z_:]+\\([ \t]*[[{]\\)?"           ; Usual variable
6056      "[$@]\\^[a-zA-Z]"                  ; Special variable
6057      "[$@][^ \n\t]"                     ; Special variable
6058      "-[a-zA-Z]"                        ; File test
6059      "\\\\[a-zA-Z0]"                    ; Special chars
6060      "^=[a-z][a-zA-Z0-9_]*"             ; Pod sections
6061      "[-!&*+,-./<=>?\\\\^|~]+"          ; Operator
6062      "[a-zA-Z_0-9:]+"                   ; symbol or number
6063      "x="
6064      "#!"
6065      )
6066    ;;"\\)\\|\\("
6067    "\\|"
6068    )
6069           ;;"\\)"
6070           ;;)
6071   "Matches places in the buffer we can find help for.")
6072
6073 (defvar cperl-message-on-help-error t)
6074 (defvar cperl-help-from-timer nil)
6075
6076 (defun cperl-word-at-point-hard ()
6077   ;; Does not save-excursion
6078   ;; Get to the something meaningful
6079   (or (eobp) (eolp) (forward-char 1))
6080   (re-search-backward "[-a-zA-Z0-9_:!&*+,-./<=>?\\\\^|~$%@]" 
6081                       (save-excursion (beginning-of-line) (point))
6082                       'to-beg)
6083   ;;  (cond
6084   ;;   ((or (eobp) (looking-at "[][ \t\n{}();,]")) ; Not at a symbol
6085   ;;    (skip-chars-backward " \n\t\r({[]});,")
6086   ;;    (or (bobp) (backward-char 1))))
6087   ;; Try to backtrace
6088   (cond
6089    ((looking-at "[a-zA-Z0-9_:]")        ; symbol
6090     (skip-chars-backward "a-zA-Z0-9_:")
6091     (cond 
6092      ((and (eq (preceding-char) ?^)     ; $^I
6093            (eq (char-after (- (point) 2)) ?\$))
6094       (forward-char -2))
6095      ((memq (preceding-char) (append "*$@%&\\" nil)) ; *glob
6096       (forward-char -1))
6097      ((and (eq (preceding-char) ?\=)
6098            (eq (current-column) 1))
6099       (forward-char -1)))               ; =head1
6100     (if (and (eq (preceding-char) ?\<)
6101              (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <FH>
6102         (forward-char -1)))
6103    ((and (looking-at "=") (eq (preceding-char) ?x)) ; x=
6104     (forward-char -1))
6105    ((and (looking-at "\\^") (eq (preceding-char) ?\$)) ; $^I
6106     (forward-char -1))
6107    ((looking-at "[-!&*+,-./<=>?\\\\^|~]")
6108     (skip-chars-backward "-!&*+,-./<=>?\\\\^|~")
6109     (cond
6110      ((and (eq (preceding-char) ?\$)
6111            (not (eq (char-after (- (point) 2)) ?\$))) ; $-
6112       (forward-char -1))
6113      ((and (eq (following-char) ?\>)
6114            (string-match "[a-zA-Z0-9_]" (char-to-string (preceding-char)))
6115            (save-excursion
6116              (forward-sexp -1)
6117              (and (eq (preceding-char) ?\<)
6118                   (looking-at "\\$?[a-zA-Z0-9_:]+>")))) ; <FH>
6119       (search-backward "<"))))
6120    ((and (eq (following-char) ?\$)
6121          (eq (preceding-char) ?\<)
6122          (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <$fh>
6123     (forward-char -1)))
6124   (if (looking-at cperl-have-help-regexp)
6125       (buffer-substring (match-beginning 0) (match-end 0))))
6126
6127 (defun cperl-get-help ()
6128   "Get one-line docs on the symbol at the point.
6129 The data for these docs is a little bit obsolete and may be in fact longer
6130 than a line.  Your contribution to update/shorten it is appreciated."
6131   (interactive)
6132   (save-match-data                      ; May be called "inside" query-replace
6133     (save-excursion
6134       (let ((word (cperl-word-at-point-hard)))
6135         (if word
6136             (if (and cperl-help-from-timer ; Bail out if not in mainland
6137                      (not (string-match "^#!\\|\\\\\\|^=" word)) ; Show help even in comments/strings.
6138                      (or (memq (get-text-property (point) 'face)
6139                                '(font-lock-comment-face font-lock-string-face))
6140                          (memq (get-text-property (point) 'syntax-type)
6141                                '(pod here-doc format))))
6142                 nil
6143               (cperl-describe-perl-symbol word))
6144           (if cperl-message-on-help-error
6145               (message "Nothing found for %s..." 
6146                        (buffer-substring (point) (min (+ 5 (point)) (point-max))))))))))
6147
6148 ;;; Stolen from perl-descr.el by Johan Vromans:
6149
6150 (defvar cperl-doc-buffer " *perl-doc*"
6151   "Where the documentation can be found.")
6152
6153 (defun cperl-describe-perl-symbol (val)
6154   "Display the documentation of symbol at point, a Perl operator."
6155   (let ((enable-recursive-minibuffers t)
6156         args-file regexp)
6157     (cond
6158         ((string-match "^[&*][a-zA-Z_]" val)
6159          (setq val (concat (substring val 0 1) "NAME")))
6160         ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*\\[" val)
6161          (setq val (concat "@" (substring val 1 (match-end 1)))))
6162         ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*{" val)
6163          (setq val (concat "%" (substring val 1 (match-end 1)))))
6164         ((and (string= val "x") (string-match "^x=" val))
6165          (setq val "x="))
6166         ((string-match "^\\$[\C-a-\C-z]" val)
6167          (setq val (concat "$^" (char-to-string (+ ?A -1 (aref val 1))))))
6168         ((string-match "^CORE::" val)
6169          (setq val "CORE::"))
6170         ((string-match "^SUPER::" val)
6171          (setq val "SUPER::"))
6172         ((and (string= "<" val) (string-match "^<\\$?[a-zA-Z0-9_:]+>" val))
6173          (setq val "<NAME>")))
6174     (setq regexp (concat "^" 
6175                          "\\([^a-zA-Z0-9_:]+[ \t]+\\)?"
6176                          (regexp-quote val) 
6177                          "\\([ \t([/]\\|$\\)"))
6178
6179     ;; get the buffer with the documentation text
6180     (cperl-switch-to-doc-buffer)
6181
6182     ;; lookup in the doc
6183     (goto-char (point-min))
6184     (let ((case-fold-search nil))
6185       (list 
6186        (if (re-search-forward regexp (point-max) t)
6187            (save-excursion
6188              (beginning-of-line 1)
6189              (let ((lnstart (point)))
6190                (end-of-line)
6191                (message "%s" (buffer-substring lnstart (point)))))
6192          (if cperl-message-on-help-error
6193              (message "No definition for %s" val)))))))
6194
6195 (defvar cperl-short-docs "Ignore my value"
6196   ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl)
6197   "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5]
6198 ! ...   Logical negation.       
6199 ... != ...      Numeric inequality.
6200 ... !~ ...      Search pattern, substitution, or translation (negated).
6201 $!      In numeric context: errno.  In a string context: error string.
6202 $\"     The separator which joins elements of arrays interpolated in strings.
6203 $#      The output format for printed numbers.  Initial value is %.15g or close.
6204 $$      Process number of this script.  Changes in the fork()ed child process.
6205 $%      The current page number of the currently selected output channel.
6206
6207         The following variables are always local to the current block:
6208
6209 $1      Match of the 1st set of parentheses in the last match (auto-local).
6210 $2      Match of the 2nd set of parentheses in the last match (auto-local).
6211 $3      Match of the 3rd set of parentheses in the last match (auto-local).
6212 $4      Match of the 4th set of parentheses in the last match (auto-local).
6213 $5      Match of the 5th set of parentheses in the last match (auto-local).
6214 $6      Match of the 6th set of parentheses in the last match (auto-local).
6215 $7      Match of the 7th set of parentheses in the last match (auto-local).
6216 $8      Match of the 8th set of parentheses in the last match (auto-local).
6217 $9      Match of the 9th set of parentheses in the last match (auto-local).
6218 $&      The string matched by the last pattern match (auto-local).
6219 $'      The string after what was matched by the last match (auto-local).
6220 $`      The string before what was matched by the last match (auto-local).
6221
6222 $(      The real gid of this process.
6223 $)      The effective gid of this process.
6224 $*      Deprecated: Set to 1 to do multiline matching within a string.
6225 $+      The last bracket matched by the last search pattern.
6226 $,      The output field separator for the print operator.
6227 $-      The number of lines left on the page.
6228 $.      The current input line number of the last filehandle that was read.
6229 $/      The input record separator, newline by default.
6230 $0      Name of the file containing the perl script being executed.  May be set.
6231 $:     String may be broken after these characters to fill ^-lines in a format.
6232 $;      Subscript separator for multi-dim array emulation.  Default \"\\034\".
6233 $<      The real uid of this process.
6234 $=      The page length of the current output channel.  Default is 60 lines.
6235 $>      The effective uid of this process.
6236 $?      The status returned by the last ``, pipe close or `system'.
6237 $@      The perl error message from the last eval or do @var{EXPR} command.
6238 $ARGV   The name of the current file used with <> .
6239 $[      Deprecated: The index of the first element/char in an array/string.
6240 $\\     The output record separator for the print operator.
6241 $]      The perl version string as displayed with perl -v.
6242 $^      The name of the current top-of-page format.
6243 $^A     The current value of the write() accumulator for format() lines.
6244 $^D     The value of the perl debug (-D) flags.
6245 $^E     Information about the last system error other than that provided by $!.
6246 $^F     The highest system file descriptor, ordinarily 2.
6247 $^H     The current set of syntax checks enabled by `use strict'.
6248 $^I     The value of the in-place edit extension (perl -i option).
6249 $^L     What formats output to perform a formfeed.  Default is \f.
6250 $^O     The operating system name under which this copy of Perl was built.
6251 $^P     Internal debugging flag.
6252 $^T     The time the script was started.  Used by -A/-M/-C file tests.
6253 $^W     True if warnings are requested (perl -w flag).
6254 $^X     The name under which perl was invoked (argv[0] in C-speech).
6255 $_      The default input and pattern-searching space.
6256 $|      Auto-flush after write/print on current output channel?  Default 0. 
6257 $~      The name of the current report format.
6258 ... % ...       Modulo division.
6259 ... %= ...      Modulo division assignment.
6260 %ENV    Contains the current environment.
6261 %INC    List of files that have been require-d or do-ne.
6262 %SIG    Used to set signal handlers for various signals.
6263 ... & ...       Bitwise and.
6264 ... && ...      Logical and.
6265 ... &&= ...     Logical and assignment.
6266 ... &= ...      Bitwise and assignment.
6267 ... * ...       Multiplication.
6268 ... ** ...      Exponentiation.
6269 *NAME   Glob: all objects refered by NAME.  *NAM1 = *NAM2 aliases NAM1 to NAM2.
6270 &NAME(arg0, ...)        Subroutine call.  Arguments go to @_.
6271 ... + ...       Addition.               +EXPR   Makes EXPR into scalar context.
6272 ++      Auto-increment (magical on strings).    ++EXPR  EXPR++
6273 ... += ...      Addition assignment.
6274 ,       Comma operator.
6275 ... - ...       Subtraction.
6276 --      Auto-decrement (NOT magical on strings).        --EXPR  EXPR--
6277 ... -= ...      Subtraction assignment.
6278 -A      Access time in days since script started.
6279 -B      File is a non-text (binary) file.
6280 -C      Inode change time in days since script started.
6281 -M      Age in days since script started.
6282 -O      File is owned by real uid.
6283 -R      File is readable by real uid.
6284 -S      File is a socket .
6285 -T      File is a text file.
6286 -W      File is writable by real uid.
6287 -X      File is executable by real uid.
6288 -b      File is a block special file.
6289 -c      File is a character special file.
6290 -d      File is a directory.
6291 -e      File exists .
6292 -f      File is a plain file.
6293 -g      File has setgid bit set.
6294 -k      File has sticky bit set.
6295 -l      File is a symbolic link.
6296 -o      File is owned by effective uid.
6297 -p      File is a named pipe (FIFO).
6298 -r      File is readable by effective uid.
6299 -s      File has non-zero size.
6300 -t      Tests if filehandle (STDIN by default) is opened to a tty.
6301 -u      File has setuid bit set.
6302 -w      File is writable by effective uid.
6303 -x      File is executable by effective uid.
6304 -z      File has zero size.
6305 .       Concatenate strings.
6306 ..      Alternation, also range operator.
6307 .=      Concatenate assignment strings
6308 ... / ...       Division.       /PATTERN/ioxsmg Pattern match
6309 ... /= ...      Division assignment.
6310 /PATTERN/ioxsmg Pattern match.
6311 ... < ...       Numeric less than.      <pattern>       Glob.   See <NAME>, <> as well.
6312 <NAME>  Reads line from filehandle NAME (a bareword or dollar-bareword).
6313 <pattern>       Glob (Unless pattern is bareword/dollar-bareword - see <NAME>).
6314 <>      Reads line from union of files in @ARGV (= command line) and STDIN.
6315 ... << ...      Bitwise shift left.     <<      start of HERE-DOCUMENT.
6316 ... <= ...      Numeric less than or equal to.
6317 ... <=> ...     Numeric compare.
6318 ... = ...       Assignment.
6319 ... == ...      Numeric equality.
6320 ... =~ ...      Search pattern, substitution, or translation
6321 ... > ...       Numeric greater than.
6322 ... >= ...      Numeric greater than or equal to.
6323 ... >> ...      Bitwise shift right.
6324 ... >>= ...     Bitwise shift right assignment.
6325 ... ? ... : ... Condition=if-then-else operator.   ?PAT? One-time pattern match.
6326 ?PATTERN?       One-time pattern match.
6327 @ARGV   Command line arguments (not including the command name - see $0).
6328 @INC    List of places to look for perl scripts during do/include/use.
6329 @_      Parameter array for subroutines.  Also used by split unless in array context.
6330 \\  Creates reference to what follows, like \$var, or quotes non-\w in strings.
6331 \\0     Octal char, e.g. \\033.
6332 \\E     Case modification terminator.  See \\Q, \\L, and \\U.
6333 \\L     Lowercase until \\E .  See also \l, lc.
6334 \\U     Upcase until \\E .  See also \u, uc.
6335 \\Q     Quote metacharacters until \\E .  See also quotemeta.
6336 \\a     Alarm character (octal 007).
6337 \\b     Backspace character (octal 010).
6338 \\c     Control character, e.g. \\c[ .
6339 \\e     Escape character (octal 033).
6340 \\f     Formfeed character (octal 014).
6341 \\l     Lowercase the next character.  See also \\L and \\u, lcfirst.
6342 \\n     Newline character (octal 012 on most systems).
6343 \\r     Return character (octal 015 on most systems).
6344 \\t     Tab character (octal 011).
6345 \\u     Upcase the next character.  See also \\U and \\l, ucfirst.
6346 \\x     Hex character, e.g. \\x1b.
6347 ... ^ ...       Bitwise exclusive or.
6348 __END__ Ends program source.
6349 __DATA__        Ends program source.
6350 __FILE__        Current (source) filename.
6351 __LINE__        Current line in current source.
6352 __PACKAGE__     Current package.
6353 ARGV    Default multi-file input filehandle.  <ARGV> is a synonym for <>.
6354 ARGVOUT Output filehandle with -i flag.
6355 BEGIN { ... }   Immediately executed (during compilation) piece of code.
6356 END { ... }     Pseudo-subroutine executed after the script finishes.
6357 DATA    Input filehandle for what follows after __END__ or __DATA__.
6358 accept(NEWSOCKET,GENERICSOCKET)
6359 alarm(SECONDS)
6360 atan2(X,Y)
6361 bind(SOCKET,NAME)
6362 binmode(FILEHANDLE)
6363 caller[(LEVEL)]
6364 chdir(EXPR)
6365 chmod(LIST)
6366 chop[(LIST|VAR)]
6367 chown(LIST)
6368 chroot(FILENAME)
6369 close(FILEHANDLE)
6370 closedir(DIRHANDLE)
6371 ... cmp ...     String compare.
6372 connect(SOCKET,NAME)
6373 continue of { block } continue { block }.  Is executed after `next' or at end.
6374 cos(EXPR)
6375 crypt(PLAINTEXT,SALT)
6376 dbmclose(%HASH)
6377 dbmopen(%HASH,DBNAME,MODE)
6378 defined(EXPR)
6379 delete($HASH{KEY})
6380 die(LIST)
6381 do { ... }|SUBR while|until EXPR        executes at least once
6382 do(EXPR|SUBR([LIST]))   (with while|until executes at least once)
6383 dump LABEL
6384 each(%HASH)
6385 endgrent
6386 endhostent
6387 endnetent
6388 endprotoent
6389 endpwent
6390 endservent
6391 eof[([FILEHANDLE])]
6392 ... eq ...      String equality.
6393 eval(EXPR) or eval { BLOCK }
6394 exec(LIST)
6395 exit(EXPR)
6396 exp(EXPR)
6397 fcntl(FILEHANDLE,FUNCTION,SCALAR)
6398 fileno(FILEHANDLE)
6399 flock(FILEHANDLE,OPERATION)
6400 for (EXPR;EXPR;EXPR) { ... }
6401 foreach [VAR] (@ARRAY) { ... }
6402 fork
6403 ... ge ...      String greater than or equal.
6404 getc[(FILEHANDLE)]
6405 getgrent
6406 getgrgid(GID)
6407 getgrnam(NAME)
6408 gethostbyaddr(ADDR,ADDRTYPE)
6409 gethostbyname(NAME)
6410 gethostent
6411 getlogin
6412 getnetbyaddr(ADDR,ADDRTYPE)
6413 getnetbyname(NAME)
6414 getnetent
6415 getpeername(SOCKET)
6416 getpgrp(PID)
6417 getppid
6418 getpriority(WHICH,WHO)
6419 getprotobyname(NAME)
6420 getprotobynumber(NUMBER)
6421 getprotoent
6422 getpwent
6423 getpwnam(NAME)
6424 getpwuid(UID)
6425 getservbyname(NAME,PROTO)
6426 getservbyport(PORT,PROTO)
6427 getservent
6428 getsockname(SOCKET)
6429 getsockopt(SOCKET,LEVEL,OPTNAME)
6430 gmtime(EXPR)
6431 goto LABEL
6432 ... gt ...      String greater than.
6433 hex(EXPR)
6434 if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXPR if EXPR
6435 index(STR,SUBSTR[,OFFSET])
6436 int(EXPR)
6437 ioctl(FILEHANDLE,FUNCTION,SCALAR)
6438 join(EXPR,LIST)
6439 keys(%HASH)
6440 kill(LIST)
6441 last [LABEL]
6442 ... le ...      String less than or equal.
6443 length(EXPR)
6444 link(OLDFILE,NEWFILE)
6445 listen(SOCKET,QUEUESIZE)
6446 local(LIST)
6447 localtime(EXPR)
6448 log(EXPR)
6449 lstat(EXPR|FILEHANDLE|VAR)
6450 ... lt ...      String less than.
6451 m/PATTERN/iogsmx
6452 mkdir(FILENAME,MODE)
6453 msgctl(ID,CMD,ARG)
6454 msgget(KEY,FLAGS)
6455 msgrcv(ID,VAR,SIZE,TYPE.FLAGS)
6456 msgsnd(ID,MSG,FLAGS)
6457 my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, or %HASH).
6458 ... ne ...      String inequality.
6459 next [LABEL]
6460 oct(EXPR)
6461 open(FILEHANDLE[,EXPR])
6462 opendir(DIRHANDLE,EXPR)
6463 ord(EXPR)       ASCII value of the first char of the string.
6464 pack(TEMPLATE,LIST)
6465 package NAME    Introduces package context.
6466 pipe(READHANDLE,WRITEHANDLE)    Create a pair of filehandles on ends of a pipe.
6467 pop(ARRAY)
6468 print [FILEHANDLE] [(LIST)]
6469 printf [FILEHANDLE] (FORMAT,LIST)
6470 push(ARRAY,LIST)
6471 q/STRING/       Synonym for 'STRING'
6472 qq/STRING/      Synonym for \"STRING\"
6473 qx/STRING/      Synonym for `STRING`
6474 rand[(EXPR)]
6475 read(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
6476 readdir(DIRHANDLE)
6477 readlink(EXPR)
6478 recv(SOCKET,SCALAR,LEN,FLAGS)
6479 redo [LABEL]
6480 rename(OLDNAME,NEWNAME)
6481 require [FILENAME | PERL_VERSION]
6482 reset[(EXPR)]
6483 return(LIST)
6484 reverse(LIST)
6485 rewinddir(DIRHANDLE)
6486 rindex(STR,SUBSTR[,OFFSET])
6487 rmdir(FILENAME)
6488 s/PATTERN/REPLACEMENT/gieoxsm
6489 scalar(EXPR)
6490 seek(FILEHANDLE,POSITION,WHENCE)
6491 seekdir(DIRHANDLE,POS)
6492 select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT)
6493 semctl(ID,SEMNUM,CMD,ARG)
6494 semget(KEY,NSEMS,SIZE,FLAGS)
6495 semop(KEY,...)
6496 send(SOCKET,MSG,FLAGS[,TO])
6497 setgrent
6498 sethostent(STAYOPEN)
6499 setnetent(STAYOPEN)
6500 setpgrp(PID,PGRP)
6501 setpriority(WHICH,WHO,PRIORITY)
6502 setprotoent(STAYOPEN)
6503 setpwent
6504 setservent(STAYOPEN)
6505 setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
6506 shift[(ARRAY)]
6507 shmctl(ID,CMD,ARG)
6508 shmget(KEY,SIZE,FLAGS)
6509 shmread(ID,VAR,POS,SIZE)
6510 shmwrite(ID,STRING,POS,SIZE)
6511 shutdown(SOCKET,HOW)
6512 sin(EXPR)
6513 sleep[(EXPR)]
6514 socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
6515 socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
6516 sort [SUBROUTINE] (LIST)
6517 splice(ARRAY,OFFSET[,LENGTH[,LIST]])
6518 split[(/PATTERN/[,EXPR[,LIMIT]])]
6519 sprintf(FORMAT,LIST)
6520 sqrt(EXPR)
6521 srand(EXPR)
6522 stat(EXPR|FILEHANDLE|VAR)
6523 study[(SCALAR)]
6524 sub [NAME [(format)]] { BODY }  sub NAME [(format)];    sub [(format)] {...}
6525 substr(EXPR,OFFSET[,LEN])
6526 symlink(OLDFILE,NEWFILE)
6527 syscall(LIST)
6528 sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
6529 system(LIST)
6530 syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
6531 tell[(FILEHANDLE)]
6532 telldir(DIRHANDLE)
6533 time
6534 times
6535 tr/SEARCHLIST/REPLACEMENTLIST/cds
6536 truncate(FILE|EXPR,LENGTH)
6537 umask[(EXPR)]
6538 undef[(EXPR)]
6539 unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR
6540 unlink(LIST)
6541 unpack(TEMPLATE,EXPR)
6542 unshift(ARRAY,LIST)
6543 until (EXPR) { ... }                                    EXPR until EXPR
6544 utime(LIST)
6545 values(%HASH)
6546 vec(EXPR,OFFSET,BITS)
6547 wait
6548 waitpid(PID,FLAGS)
6549 wantarray       Returns true if the sub/eval is called in list context.
6550 warn(LIST)
6551 while  (EXPR) { ... }                                   EXPR while EXPR
6552 write[(EXPR|FILEHANDLE)]
6553 ... x ...       Repeat string or array.
6554 x= ...  Repetition assignment.
6555 y/SEARCHLIST/REPLACEMENTLIST/
6556 ... | ...       Bitwise or.
6557 ... || ...      Logical or.
6558 ~ ...           Unary bitwise complement.
6559 #!      OS interpreter indicator.  If contains `perl', used for options, and -x.
6560 AUTOLOAD {...}  Shorthand for `sub AUTOLOAD {...}'.
6561 CORE::          Prefix to access builtin function if imported sub obscures it.
6562 SUPER::         Prefix to lookup for a method in @ISA classes.
6563 DESTROY         Shorthand for `sub DESTROY {...}'.
6564 ... EQ ...      Obsolete synonym of `eq'.
6565 ... GE ...      Obsolete synonym of `ge'.
6566 ... GT ...      Obsolete synonym of `gt'.
6567 ... LE ...      Obsolete synonym of `le'.
6568 ... LT ...      Obsolete synonym of `lt'.
6569 ... NE ...      Obsolete synonym of `ne'.
6570 abs [ EXPR ]    absolute value
6571 ... and ...             Low-precedence synonym for &&.
6572 bless REFERENCE [, PACKAGE]     Makes reference into an object of a package.
6573 chomp [LIST]    Strips $/ off LIST/$_.  Returns count.  Special if $/ eq ''!
6574 chr             Converts a number to char with the same ordinal.
6575 else            Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
6576 elsif           Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
6577 exists  $HASH{KEY}      True if the key exists.
6578 format [NAME] =  Start of output format.  Ended by a single dot (.) on a line.
6579 formline PICTURE, LIST  Backdoor into \"format\" processing.
6580 glob EXPR       Synonym of <EXPR>.
6581 lc [ EXPR ]     Returns lowercased EXPR.
6582 lcfirst [ EXPR ]        Returns EXPR with lower-cased first letter.
6583 grep EXPR,LIST  or grep {BLOCK} LIST    Filters LIST via EXPR/BLOCK.
6584 map EXPR, LIST  or map {BLOCK} LIST     Applies EXPR/BLOCK to elts of LIST.
6585 no PACKAGE [SYMBOL1, ...]  Partial reverse for `use'.  Runs `unimport' method.
6586 not ...         Low-precedence synonym for ! - negation.
6587 ... or ...              Low-precedence synonym for ||.
6588 pos STRING    Set/Get end-position of the last match over this string, see \\G.
6589 quotemeta [ EXPR ]      Quote regexp metacharacters.
6590 qw/WORD1 .../           Synonym of split('', 'WORD1 ...')
6591 readline FH     Synonym of <FH>.
6592 readpipe CMD    Synonym of `CMD`.
6593 ref [ EXPR ]    Type of EXPR when dereferenced.
6594 sysopen FH, FILENAME, MODE [, PERM]     (MODE is numeric, see Fcntl.)
6595 tie VAR, PACKAGE, LIST  Hide an object behind a simple Perl variable.
6596 tied            Returns internal object for a tied data.
6597 uc [ EXPR ]     Returns upcased EXPR.
6598 ucfirst [ EXPR ]        Returns EXPR with upcased first letter.
6599 untie VAR       Unlink an object from a simple Perl variable.
6600 use PACKAGE [SYMBOL1, ...]  Compile-time `require' with consequent `import'.
6601 ... xor ...             Low-precedence synonym for exclusive or.
6602 prototype \&SUB Returns prototype of the function given a reference.
6603 =head1          Top-level heading.
6604 =head2          Second-level heading.
6605 =head3          Third-level heading (is there such?).
6606 =over [ NUMBER ]        Start list.
6607 =item [ TITLE ]         Start new item in the list.
6608 =back           End list.
6609 =cut            Switch from POD to Perl.
6610 =pod            Switch from Perl to POD.
6611 ")
6612
6613 (defun cperl-switch-to-doc-buffer ()
6614   "Go to the perl documentation buffer and insert the documentation."
6615   (interactive)
6616   (let ((buf (get-buffer-create cperl-doc-buffer)))
6617     (if (interactive-p)
6618         (switch-to-buffer-other-window buf)
6619       (set-buffer buf))
6620     (if (= (buffer-size) 0)
6621         (progn
6622           (insert (documentation-property 'cperl-short-docs
6623                                           'variable-documentation))
6624           (setq buffer-read-only t)))))
6625
6626 (defun cperl-beautify-regexp-piece (b e embed)
6627   ;; b is before the starting delimiter, e before the ending
6628   ;; e should be a marker, may be changed, but remains "correct".
6629   (let (s c tmp (m (make-marker)) (m1 (make-marker)) c1 spaces inline code)
6630     (if (not embed)
6631         (goto-char (1+ b))
6632       (goto-char b)
6633       (cond ((looking-at "(\\?\\\\#")   ; badly commented (?#)
6634              (forward-char 2)
6635              (delete-char 1)
6636              (forward-char 1))
6637             ((looking-at "(\\?[^a-zA-Z]")
6638              (forward-char 3))
6639             ((looking-at "(\\?")        ; (?i)
6640              (forward-char 2))
6641             (t
6642              (forward-char 1))))
6643     (setq c (if embed (current-indentation) (1- (current-column)))
6644           c1 (+ c (or cperl-regexp-indent-step cperl-indent-level)))
6645     (or (looking-at "[ \t]*[\n#]")
6646         (progn
6647           (insert "\n")))
6648     (goto-char e)
6649     (beginning-of-line)
6650     (if (re-search-forward "[^ \t]" e t)
6651         (progn
6652           (goto-char e)
6653           (insert "\n")
6654           (indent-to-column c)
6655           (set-marker e (point))))
6656     (goto-char b)
6657     (end-of-line 2)
6658     (while (< (point) (marker-position e))
6659       (beginning-of-line)
6660       (setq s (point)
6661             inline t)
6662       (skip-chars-forward " \t")
6663       (delete-region s (point))
6664       (indent-to-column c1)
6665       (while (and
6666               inline
6667               (looking-at 
6668                (concat "\\([a-zA-Z0-9]+[^*+{?]\\)" ; 1 word
6669                        "\\|"            ; Embedded variable
6670                        "\\$\\([a-zA-Z0-9_]+\\([[{]\\)?\\|[^\n \t)|]\\)" ; 2 3
6671                        "\\|"            ; $ ^
6672                        "[$^]"
6673                        "\\|"            ; simple-code simple-code*?
6674                        "\\(\\\\.\\|[^][()#|*+?\n]\\)\\([*+{?]\\??\\)?" ; 4 5
6675                        "\\|"            ; Class
6676                        "\\(\\[\\)"      ; 6
6677                        "\\|"            ; Grouping
6678                        "\\((\\(\\?\\)?\\)" ; 7 8
6679                        "\\|"            ; |
6680                        "\\(|\\)"        ; 9
6681                        )))
6682         (goto-char (match-end 0))
6683         (setq spaces t)
6684         (cond ((match-beginning 1)      ; Alphanum word + junk
6685                (forward-char -1))
6686               ((or (match-beginning 3)  ; $ab[12]
6687                    (and (match-beginning 5) ; X* X+ X{2,3}
6688                         (eq (preceding-char) ?\{)))
6689                (forward-char -1)
6690                (forward-sexp 1))
6691               ((match-beginning 6)      ; []
6692                (setq tmp (point))
6693                (if (looking-at "\\^?\\]")
6694                    (goto-char (match-end 0)))
6695                (or (re-search-forward "\\]\\([*+{?]\\)?" e t)
6696                    (progn
6697                      (goto-char (1- tmp))
6698                      (error "[]-group not terminated")))
6699                (if (not (eq (preceding-char) ?\{)) nil
6700                  (forward-char -1)
6701                  (forward-sexp 1)))
6702               ((match-beginning 7)      ; ()
6703                (goto-char (match-beginning 0))
6704                (or (eq (current-column) c1)
6705                    (progn
6706                      (insert "\n")
6707                      (indent-to-column c1)))
6708                (setq tmp (point))
6709                (forward-sexp 1)
6710                ;;              (or (forward-sexp 1)
6711                ;;                  (progn
6712                ;;                    (goto-char tmp)
6713                ;;                    (error "()-group not terminated")))
6714                (set-marker m (1- (point)))
6715                (set-marker m1 (point))
6716                (cond
6717                 ((not (match-beginning 8))
6718                  (cperl-beautify-regexp-piece tmp m t))
6719                 ((eq (char-after (+ 2 tmp)) ?\{) ; Code
6720                  t)
6721                 ((eq (char-after (+ 2 tmp)) ?\() ; Conditional
6722                  (goto-char (+ 2 tmp))
6723                  (forward-sexp 1)
6724                  (cperl-beautify-regexp-piece (point) m t))
6725                 ((eq (char-after (+ 2 tmp)) ?<) ; Lookbehind
6726                  (goto-char (+ 3 tmp))
6727                  (cperl-beautify-regexp-piece (point) m t))
6728                 (t
6729                  (cperl-beautify-regexp-piece tmp m t)))
6730                (goto-char m1)
6731                (cond ((looking-at "[*+?]\\??")
6732                       (goto-char (match-end 0)))
6733                      ((eq (following-char) ?\{)
6734                       (forward-sexp 1)
6735                       (if (eq (following-char) ?\?)
6736                           (forward-char))))
6737                (skip-chars-forward " \t")
6738                (setq spaces nil)
6739                (if (looking-at "[#\n]")
6740                    (progn
6741                      (or (eolp) (indent-for-comment))
6742                      (beginning-of-line 2))
6743                  (insert "\n"))
6744                (end-of-line)
6745                (setq inline nil))
6746               ((match-beginning 9)      ; |
6747                (forward-char -1)
6748                (setq tmp (point))
6749                (beginning-of-line)
6750                (if (re-search-forward "[^ \t]" tmp t)
6751                    (progn
6752                      (goto-char tmp)
6753                      (insert "\n"))
6754                  ;; first at line
6755                  (delete-region (point) tmp))
6756                (indent-to-column c)
6757                (forward-char 1)
6758                (skip-chars-forward " \t")
6759                (setq spaces nil)
6760                (if (looking-at "[#\n]")
6761                    (beginning-of-line 2)
6762                  (insert "\n"))
6763                (end-of-line)
6764                (setq inline nil)))
6765         (or (looking-at "[ \t\n]")
6766             (not spaces)
6767             (insert " "))
6768         (skip-chars-forward " \t"))
6769         (or (looking-at "[#\n]")
6770             (error "unknown code \"%s\" in a regexp" (buffer-substring (point)
6771                                                                         (1+ (point)))))
6772         (and inline (end-of-line 2)))
6773     ;; Special-case the last line of group
6774     (if (and (>= (point) (marker-position e))
6775              (/= (current-indentation) c))
6776         (progn
6777          (beginning-of-line)
6778          (setq s (point))
6779          (skip-chars-forward " \t")
6780          (delete-region s (point))
6781          (indent-to-column c)))
6782   ))
6783
6784 (defun cperl-make-regexp-x ()
6785   ;; Returns position of the start
6786   (save-excursion
6787     (or cperl-use-syntax-table-text-property
6788         (error "I need to have regex marked!"))
6789     ;; Find the start
6790     (if (looking-at "\\s|")
6791         nil                             ; good already
6792       (if (looking-at "[smy]\\s|")
6793           (forward-char 1)
6794         (re-search-backward "\\s|")))           ; Assume it is scanned already.
6795     ;;(forward-char 1)
6796     (let ((b (point)) (e (make-marker)) have-x delim (c (current-column))
6797           (sub-p (eq (preceding-char) ?s)) s)
6798       (forward-sexp 1)
6799       (set-marker e (1- (point)))
6800       (setq delim (preceding-char))
6801       (if (and sub-p (eq delim (char-after (- (point) 2))))
6802           (error "Possible s/blah// - do not know how to deal with"))
6803       (if sub-p (forward-sexp 1))
6804       (if (looking-at "\\sw*x") 
6805           (setq have-x t)
6806         (insert "x"))
6807       ;; Protect fragile " ", "#"
6808       (if have-x nil
6809         (goto-char (1+ b))
6810         (while (re-search-forward "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*[ \t\n#]" e t) ; Need to include (?#) too?
6811           (forward-char -1)
6812           (insert "\\")
6813           (forward-char 1)))
6814       b)))
6815
6816 (defun cperl-beautify-regexp ()
6817   "do it.  (Experimental, may change semantics, recheck the result.)
6818 We suppose that the regexp is scanned already."
6819   (interactive)
6820   (goto-char (cperl-make-regexp-x))
6821   (let ((b (point)) (e (make-marker)))
6822     (forward-sexp 1)
6823     (set-marker e (1- (point)))
6824     (cperl-beautify-regexp-piece b e nil)))
6825
6826 (defun cperl-regext-to-level-start ()
6827   "Goto start of an enclosing group in regexp.
6828 We suppose that the regexp is scanned already."
6829   (interactive)
6830   (let ((limit (cperl-make-regexp-x)) done)
6831     (while (not done)
6832       (or (eq (following-char) ?\()
6833           (search-backward "(" (1+ limit) t)
6834           (error "Cannot find `(' which starts a group"))
6835       (setq done
6836             (save-excursion
6837               (skip-chars-backward "\\")
6838               (looking-at "\\(\\\\\\\\\\)*(")))
6839       (or done (forward-char -1)))))
6840
6841 (defun cperl-contract-level ()
6842   "Find an enclosing group in regexp and contract it.  Unfinished.
6843 \(Experimental, may change semantics, recheck the result.)
6844 We suppose that the regexp is scanned already."
6845   (interactive)
6846   (cperl-regext-to-level-start)
6847   (let ((b (point)) (e (make-marker)) s c)
6848     (forward-sexp 1)
6849     (set-marker e (1- (point)))
6850     (goto-char b)
6851     (while (re-search-forward "\\(#\\)\\|\n" e t)
6852       (cond 
6853        ((match-beginning 1)             ; #-comment
6854         (or c (setq c (current-indentation)))
6855         (beginning-of-line 2)           ; Skip
6856         (setq s (point))
6857         (skip-chars-forward " \t")
6858         (delete-region s (point))
6859         (indent-to-column c))
6860        (t
6861         (delete-char -1)
6862         (just-one-space))))))
6863
6864 (defun cperl-contract-levels ()
6865   "Find an enclosing group in regexp and contract all the kids.  Unfinished.
6866 \(Experimental, may change semantics, recheck the result.)
6867 We suppose that the regexp is scanned already."
6868   (interactive)
6869   (condition-case nil
6870       (cperl-regext-to-level-start)
6871     (error                              ; We are outside outermost group
6872      (goto-char (cperl-make-regexp-x))))
6873   (let ((b (point)) (e (make-marker)) s c)
6874     (forward-sexp 1)
6875     (set-marker e (1- (point)))
6876     (goto-char (1+ b))
6877     (while (re-search-forward "\\(\\\\\\\\\\)\\|(" e t)
6878       (cond 
6879        ((match-beginning 1)             ; Skip
6880         nil)
6881        (t                               ; Group
6882         (cperl-contract-level))))))
6883
6884 (defun cperl-beautify-level ()
6885   "Find an enclosing group in regexp and beautify it.
6886 \(Experimental, may change semantics, recheck the result.)
6887 We suppose that the regexp is scanned already."
6888   (interactive)
6889   (cperl-regext-to-level-start)
6890   (let ((b (point)) (e (make-marker)))
6891     (forward-sexp 1)
6892     (set-marker e (1- (point)))
6893     (cperl-beautify-regexp-piece b e nil)))
6894
6895 (defun cperl-invert-if-unless ()
6896   "Changes `if (A) {B}' into `B if A;' if possible."
6897   (interactive)
6898   (or (looking-at "\\<")
6899         (forward-sexp -1))
6900   (if (looking-at "\\<\\(if\\|unless\\|while\\|until\\)\\>")
6901       (let ((pos1 (point))
6902             pos2 pos3 pos4 pos5 s1 s2 state p pos45
6903             (s0 (buffer-substring (match-beginning 0) (match-end 0))))
6904         (forward-sexp 2)
6905         (setq pos3 (point))
6906         (forward-sexp -1)
6907         (setq pos2 (point))
6908         (if (eq (following-char) ?\( )
6909             (progn
6910               (goto-char pos3)
6911               (forward-sexp 1)
6912               (setq pos5 (point))
6913               (forward-sexp -1)
6914               (setq pos4 (point))
6915               ;; XXXX In fact may be `A if (B); {C}' ...
6916               (if (and (eq (following-char) ?\{ )
6917                        (progn
6918                          (cperl-backward-to-noncomment pos3)
6919                          (eq (preceding-char) ?\) )))
6920                   (if (condition-case nil
6921                           (progn
6922                             (goto-char pos5)
6923                             (forward-sexp 1)
6924                             (forward-sexp -1)
6925                             (looking-at "\\<els\\(e\\|if\\)\\>"))
6926                         (error nil))
6927                       (error
6928                        "`%s' (EXPR) {BLOCK} with `else'/`elsif'" s0)
6929                     (goto-char (1- pos5))
6930                     (cperl-backward-to-noncomment pos4)
6931                     (if (eq (preceding-char) ?\;)
6932                         (forward-char -1))
6933                     (setq pos45 (point))
6934                     (goto-char pos4)
6935                     (while (re-search-forward "\\<\\(for\\|foreach\\|if\\|unless\\|while\\|until\\)\\>\\|;" pos45 t)
6936                       (setq p (match-beginning 0)
6937                             s1 (buffer-substring p (match-end 0))
6938                             state (parse-partial-sexp pos4 p))
6939                       (or (nth 3 state) 
6940                           (nth 4 state)
6941                           (nth 5 state)
6942                           (error "`%s' inside `%s' BLOCK" s1 s0))
6943                       (goto-char (match-end 0)))
6944                     ;; Finally got it
6945                     (goto-char (1+ pos4))
6946                     (skip-chars-forward " \t\n")
6947                     (setq s2 (buffer-substring (point) pos45))
6948                     (goto-char pos45)
6949                     (or (looking-at ";?[ \t\n]*}")
6950                         (progn
6951                           (skip-chars-forward "; \t\n")
6952                           (setq s2 (concat s2 "\n" (buffer-substring (point) (1- pos5))))))
6953                     (and (equal s2 "")
6954                          (setq s2 "1"))
6955                     (goto-char (1- pos3))
6956                     (cperl-backward-to-noncomment pos2)
6957                     (or (looking-at "[ \t\n]*)")
6958                         (goto-char (1- pos3)))
6959                     (setq p (point))
6960                     (goto-char (1+ pos2))
6961                     (skip-chars-forward " \t\n")
6962                     (setq s1 (buffer-substring (point) p))
6963                     (delete-region pos4 pos5)
6964                     (delete-region pos2 pos3)
6965                     (goto-char pos1)
6966                     (insert s2 " ")
6967                     (just-one-space)
6968                     (forward-word 1)
6969                     (setq pos1 (point))
6970                     (insert " " s1 ";")
6971                     (forward-char -1)
6972                     (delete-horizontal-space)
6973                     (goto-char pos1)
6974                     (just-one-space)
6975                     (cperl-indent-line))
6976                 (error "`%s' (EXPR) not with an {BLOCK}" s0)))
6977           (error "`%s' not with an (EXPR)" s0)))
6978     (error "Not at `if', `unless', `while', or `unless'")))
6979
6980 ;;; By Anthony Foiani <afoiani@uswest.com>
6981 ;;; Getting help on modules in C-h f ?
6982 ;;; Need to teach it how to lookup functions
6983 (defvar Man-filter-list)
6984 (defun cperl-perldoc (word)
6985   "Run a 'perldoc' on WORD."
6986   (interactive
6987    (list (let* ((default-entry (cperl-word-at-point))
6988                 (input (read-string
6989                         (format "perldoc entry%s: "
6990                                 (if (string= default-entry "")
6991                                     ""
6992                                   (format " (default %s)" default-entry))))))
6993            (if (string= input "")
6994                (if (string= default-entry "")
6995                    (error "No perldoc args given")
6996                  default-entry)
6997              input))))
6998   (let* ((is-func (and 
6999                    (string-match "^[a-z]+$" word)
7000                    (string-match (concat "^" word "\\>")
7001                                  (documentation-property
7002                                   'cperl-short-docs
7003                                   'variable-documentation))))
7004          (manual-program (if is-func "perldoc -f" "perldoc")))
7005     (require 'man)
7006     (Man-getpage-in-background word)))
7007
7008 (defun cperl-perldoc-at-point ()
7009   "Run a 'perldoc' on WORD."
7010   (interactive)
7011   (cperl-perldoc (cperl-word-at-point)))
7012
7013 ;;; By Nick Roberts <Nick.Roberts@src.bae.co.uk> (with changes)
7014 (defvar pod2man-program "pod2man")
7015
7016 (defun cperl-pod-to-manpage ()
7017   "Create a virtual manpage in emacs from the Perl Online Documentation"
7018   (interactive)
7019   (require 'man)
7020   (let* ((pod2man-args (concat buffer-file-name " | nroff -man "))
7021          (bufname (concat "Man " buffer-file-name))
7022          (buffer (generate-new-buffer bufname)))
7023     (save-excursion
7024       (set-buffer buffer)
7025       (let ((process-environment (copy-sequence process-environment)))
7026         ;; Prevent any attempt to use display terminal fanciness.
7027         (setenv "TERM" "dumb")
7028         (set-process-sentinel
7029          (start-process pod2man-program buffer "sh" "-c"
7030                         (format (cperl-pod2man-build-command) pod2man-args))
7031          'Man-bgproc-sentinel)))))
7032
7033 (defun cperl-pod2man-build-command ()
7034   "Builds the entire background manpage and cleaning command."
7035   (let ((command (concat pod2man-program " %s 2>/dev/null"))
7036         (flist Man-filter-list))
7037     (while (and flist (car flist))
7038       (let ((pcom (car (car flist)))
7039             (pargs (cdr (car flist))))
7040         (setq command
7041               (concat command " | " pcom " "
7042                       (mapconcat '(lambda (phrase)
7043                                     (if (not (stringp phrase))
7044                                         (error "Malformed Man-filter-list"))
7045                                     phrase)
7046                                  pargs " ")))
7047         (setq flist (cdr flist))))
7048     command))
7049
7050 (defun cperl-lazy-install ())           ; Avoid a warning
7051
7052 (if (fboundp 'run-with-idle-timer)
7053     (progn
7054       (defvar cperl-help-shown nil
7055         "Non-nil means that the help was already shown now.")
7056
7057       (defvar cperl-lazy-installed nil
7058         "Non-nil means that the lazy-help handlers are installed now.")
7059
7060       (defun cperl-lazy-install ()
7061         (interactive)
7062         (make-variable-buffer-local 'cperl-help-shown)
7063         (if (and (cperl-val 'cperl-lazy-help-time)
7064                  (not cperl-lazy-installed))
7065             (progn
7066               (add-hook 'post-command-hook 'cperl-lazy-hook)
7067               (run-with-idle-timer 
7068                (cperl-val 'cperl-lazy-help-time 1000000 5) 
7069                t 
7070                'cperl-get-help-defer)
7071               (setq cperl-lazy-installed t))))
7072
7073       (defun cperl-lazy-unstall ()
7074         (interactive)
7075         (remove-hook 'post-command-hook 'cperl-lazy-hook)
7076         (cancel-function-timers 'cperl-get-help-defer)
7077         (setq cperl-lazy-installed nil))
7078
7079       (defun cperl-lazy-hook ()
7080         (setq cperl-help-shown nil))
7081
7082       (defun cperl-get-help-defer ()
7083         (if (not (eq major-mode 'perl-mode)) nil
7084           (let ((cperl-message-on-help-error nil) (cperl-help-from-timer t))
7085             (cperl-get-help)
7086             (setq cperl-help-shown t))))
7087       (cperl-lazy-install)))
7088
7089
7090 ;;; Plug for wrong font-lock:
7091
7092 (defun cperl-font-lock-unfontify-region-function (beg end)
7093   (let* ((modified (buffer-modified-p)) (buffer-undo-list t)
7094          (inhibit-read-only t) (inhibit-point-motion-hooks t)
7095          before-change-functions after-change-functions
7096          deactivate-mark buffer-file-name buffer-file-truename)
7097     (remove-text-properties beg end '(face nil))
7098     (when (and (not modified) (buffer-modified-p))
7099       (set-buffer-modified-p nil))))
7100
7101 (defvar cperl-d-l nil)
7102 (defun cperl-fontify-syntaxically (end)
7103   (let ((start (point)) (dbg (point)))
7104     (or cperl-syntax-done-to
7105         (setq cperl-syntax-done-to (point-min)))
7106     (if (or (not (boundp 'font-lock-hot-pass))
7107             (eval 'font-lock-hot-pass)
7108             t)                          ; Not debugged otherwise
7109         ;; Need to forget what is after `start'
7110         (setq start (min cperl-syntax-done-to start))
7111       ;; Fontification without a change
7112       (setq start (max cperl-syntax-done-to start)))
7113     (and (> end start)
7114          (setq cperl-syntax-done-to start) ; In case what follows fails
7115          (cperl-find-pods-heres start end t nil t))
7116     ;;(setq cperl-d-l (cons (format "Syntaxifying %s..%s from %s to %s\n" 
7117         ;;                        dbg end start cperl-syntax-done-to) 
7118                 ;;        cperl-d-l))
7119     ;;(let ((standard-output (get-buffer "*Messages*")))
7120         ;;(princ (format "Syntaxifying %s..%s from %s to %s\n" 
7121                 ;;       dbg end start cperl-syntax-done-to)))
7122     (if (eq cperl-syntaxify-by-font-lock 'message)
7123         (message "Syntaxified %s..%s from %s to %s, state at %s" 
7124                  dbg end start cperl-syntax-done-to
7125                  (car cperl-syntax-state))) ; For debugging 
7126     nil))                               ; Do not iterate
7127
7128 (defun cperl-update-syntaxification (from to)
7129   (if (and cperl-use-syntax-table-text-property
7130            cperl-syntaxify-by-font-lock
7131            (or (null cperl-syntax-done-to)
7132                (< cperl-syntax-done-to to)))
7133       (progn
7134         (save-excursion
7135           (goto-char from)
7136           (cperl-fontify-syntaxically to)))))
7137
7138 (provide 'cperl-mode)
7139
7140 ;;; cperl-mode.el ends here
7141