z/OS: changes for building threaded from "Brian De Pradine"
[p5sagit/p5-mst-13.2.git] / emacs / cperl-mode.el
1 ;;; cperl-mode.el --- Perl code editing commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2003
4 ;;     Free Software Foundation, Inc.
5
6 ;; Author: Ilya Zakharevich and Bob Olson
7 ;; Maintainer: Ilya Zakharevich <cperl@ilyaz.org>
8 ;; Keywords: languages, Perl
9
10 ;; This file is part of GNU Emacs.
11
12 ;;; This code started from the following message of long time ago
13 ;;; (IZ), but Bob does not maintain this mode any more:
14
15 ;;; From: olson@mcs.anl.gov (Bob Olson)
16 ;;; Newsgroups: comp.lang.perl
17 ;;; Subject: cperl-mode: Another perl mode for Gnuemacs
18 ;;; Date: 14 Aug 91 15:20:01 GMT
19
20 ;; Copyright (C) Ilya Zakharevich and Bob Olson
21
22 ;; This file may be distributed
23 ;; either under the same terms as GNU Emacs, or under the same terms
24 ;; as Perl. You should have received a copy of Perl Artistic license
25 ;; along with the Perl distribution.
26
27 ;; GNU Emacs is free software; you can redistribute it and/or modify
28 ;; it under the terms of the GNU General Public License as published by
29 ;; the Free Software Foundation; either version 2, or (at your option)
30 ;; any later version.
31
32 ;; GNU Emacs is distributed in the hope that it will be useful,
33 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
34 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35 ;; GNU General Public License for more details.
36
37 ;; You should have received a copy of the GNU General Public License
38 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
39 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
40 ;; Boston, MA 02111-1307, USA.
41
42 ;;; Corrections made by Ilya Zakharevich cperl@ilyaz.org
43 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
44
45 ;;; Commentary:
46
47 ;; $Id: cperl-mode.el,v 5.0 2003/02/17 01:33:20 vera Exp vera $
48
49 ;;; If your Emacs does not default to `cperl-mode' on Perl files:
50 ;;; To use this mode put the following into
51 ;;; your .emacs file:
52
53 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
54
55 ;; You can either fine-tune the bells and whistles of this mode or
56 ;; bulk enable them by putting
57
58 ;; (setq cperl-hairy t)
59
60 ;; in your .emacs file.  (Emacs rulers do not consider it politically
61 ;; correct to make whistles enabled by default.)
62
63 ;; DO NOT FORGET to read micro-docs (available from `Perl' menu)   <<<<<<
64 ;; or as help on variables `cperl-tips', `cperl-problems',         <<<<<<
65 ;; `cperl-non-problems', `cperl-praise', `cperl-speed'.            <<<<<<
66
67 ;; Additional useful commands to put into your .emacs file (before
68 ;; RMS Emacs 20.3):
69
70 ;; (setq auto-mode-alist
71 ;;      (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
72 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
73 ;;                                      '(("miniperl" . perl-mode))))
74
75 ;; The mode information (on C-h m) provides some customization help.
76 ;; If you use font-lock feature of this mode, it is advisable to use
77 ;; either lazy-lock-mode or fast-lock-mode.  I prefer lazy-lock.
78
79 ;; Faces used now: three faces for first-class and second-class keywords
80 ;; and control flow words, one for each: comments, string, labels,
81 ;; functions definitions and packages, arrays, hashes, and variable
82 ;; definitions.  If you do not see all these faces, your font-lock does
83 ;; not define them, so you need to define them manually.
84 ;; Maybe you have an obsolete font-lock from 19.28 or earlier.  Upgrade.
85
86 ;; If you have a grayscale monitor, and do not have the variable
87 ;; font-lock-display-type bound to 'grayscale, insert
88
89 ;; (setq font-lock-display-type 'grayscale)
90
91 ;; into your .emacs file (this is relevant before RMS Emacs 20).
92
93 ;; This mode supports font-lock, imenu and mode-compile.  In the
94 ;; hairy version font-lock is on, but you should activate imenu
95 ;; yourself (note that mode-compile is not standard yet).  Well, you
96 ;; can use imenu from keyboard anyway (M-x imenu), but it is better
97 ;; to bind it like that:
98
99 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
100
101 ;;; Font lock bugs as of v4.32:
102
103 ;; The following kinds of Perl code erroneously start strings:
104 ;; \$`  \$'  \$"
105 ;; $opt::s  $opt_s  $opt{s}  (s => ...)  /\s+.../
106 ;; likewise with m, tr, y, q, qX instead of s
107
108 ;;; In fact the version of font-lock that this version supports can be
109 ;;; much newer than the version you actually have. This means that a
110 ;;; lot of faces can be set up, but are not visible on your screen
111 ;;; since the coloring rules for this faces are not defined.
112
113 ;;; Updates: ========================================
114
115 ;;; Made less hairy by default: parentheses not electric,
116 ;;; linefeed not magic. Bug with abbrev-mode corrected.
117
118 ;;;; After 1.4:
119 ;;;  Better indentation:
120 ;;;  subs inside braces should work now,
121 ;;;  Toplevel braces obey customization.
122 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
123 ;;;  moves cursor to a correct place.
124 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-(
125 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
126 ;;;  Minor documentation fixes.
127 ;;;  Imenu understands packages as prefixes (including nested).
128 ;;;  Hairy options can be switched off one-by-one by setting to null.
129 ;;;  Names of functions and variables changed to conform to `cperl-' style.
130
131 ;;;; After 1.5:
132 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
133 ;;;  `cperl-indent-region' done (slow :-()).
134 ;;;  `cperl-fill-paragraph' done.
135 ;;;  Better package support for `imenu'.
136 ;;;  Progress indicator for indentation (with `imenu' loaded).
137 ;;;  `Cperl-set' was busted, now setting the individual hairy option
138 ;;;     should be better.
139
140 ;;;; After 1.6:
141 ;;; `cperl-set-style' done.
142 ;;; `cperl-check-syntax' done.
143 ;;; Menu done.
144 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
145 ;;; Bugs with `cperl-auto-newline' corrected.
146 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation
147 ;;; like $hash{.
148
149 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
150 ;;; - use `next-command-event', if `next-command-events' does not exist
151 ;;; - use `find-face' as def. of `is-face'
152 ;;; - corrected def. of `x-color-defined-p'
153 ;;; - added const defs for font-lock-comment-face,
154 ;;;   font-lock-keyword-face and font-lock-function-name-face
155 ;;; - added def. of font-lock-variable-name-face
156 ;;; - added (require 'easymenu) inside an `eval-when-compile'
157 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
158 ;;;   `define-key's
159 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
160 ;;; Todo (at least):
161 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
162 ;;;   for portable code?
163 ;;; - should `cperl-mode' do a
164 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
165 ;;;   or should this be left to the user's `cperl-mode-hook'?
166
167 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
168 ;;; Some bugs under XEmacs introduced by the correction corrected.
169
170 ;;; Some more can remain since there are two many different variants.
171 ;;; Please feedback!
172
173 ;;; We do not support fontification of arrays and hashes under
174 ;;; obsolete font-lock any more. Upgrade.
175
176 ;;;; after 1.8 Minor bug with parentheses.
177 ;;;; after 1.9 Improvements from Joe Marzot.
178 ;;;; after 1.10
179 ;;;  Does not need easymenu to compile under XEmacs.
180 ;;;  `vc-insert-headers' should work better.
181 ;;;  Should work with 19.29 and 19.12.
182 ;;;  Small improvements to fontification.
183 ;;;  Expansion of keywords does not depend on C-? being backspace.
184
185 ;;; after 1.10+
186 ;;; 19.29 and 19.12 supported.
187 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
188 ;;; Support for font-lock-extra.el.
189
190 ;;;; After 1.11:
191 ;;; Tools submenu.
192 ;;; Support for perl5-info.
193 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
194 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
195 ;;; Fontifies `require a if b;', __DATA__.
196 ;;; Arglist for auto-fill-mode was incorrect.
197
198 ;;;; After 1.12:
199 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions
200 ;;; vertically.
201 ;;; `cperl-do-auto-fill' updated for 19.29 style.
202 ;;; `cperl-info-on-command' now has a default.
203 ;;; Workaround for broken C-h on XEmacs.
204 ;;; VC strings escaped.
205 ;;; C-h f now may prompt for function name instead of going on,
206 ;;; controlled by `cperl-info-on-command-no-prompt'.
207
208 ;;;; After 1.13:
209 ;;; Msb buffer list includes perl files
210 ;;; Indent-for-comment uses indent-to
211 ;;; Can write tag files using etags.
212
213 ;;;; After 1.14:
214 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
215 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
216 ;;; Bug with auto-filling comments started with "##" corrected.
217
218 ;;;; Very slow now: on DB::DB 0.91, 486/66:
219
220 ;;;Function Name                             Call Count  Elapsed Time  Average Time
221 ;;;========================================  ==========  ============  ============
222 ;;;cperl-block-p                             469         3.7799999999  0.0080597014
223 ;;;cperl-get-state                           505         163.39000000  0.3235445544
224 ;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
225 ;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
226 ;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
227 ;;;cperl-indent-line                         505         172.88000000  0.3423366336
228 ;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
229 ;;;cperl-indent-exp                          1           177.97000000  177.97000000
230 ;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
231 ;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
232 ;;;cperl-indent-region                       1           177.94000000  177.94000000
233
234 ;;;; After 1.15:
235 ;;; Takes into account white space after opening parentheses during indent.
236 ;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
237 ;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
238 ;;; for indentation so far.
239 ;;; Fontification updated to 19.30 style.
240 ;;; The change 19.29->30 did not add all the required functionality,
241 ;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
242 ;;;       ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
243
244 ;;;; After 1.16:
245 ;;;       else # comment
246 ;;;    recognized as a start of a block.
247 ;;;  Two different font-lock-levels provided.
248 ;;;  `cperl-pod-head-face' introduced. Used for highlighting.
249 ;;;  `imenu' marks pods, +Packages moved to the head.
250
251 ;;;; After 1.17:
252 ;;;  Scan for pods highlights here-docs too.
253 ;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
254 ;;;  Only one here-doc-tag per line is supported, and one in comment
255 ;;;  or a string may break fontification.
256 ;;;  POD headers were supposed to fill one line only.
257
258 ;;;; After 1.18:
259 ;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme
260 ;;;    may  break under XEmacs.
261 ;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
262 ;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
263 ;;;    compatibility with older lazy-lock.el) (older one overfontifies
264 ;;;    something nevertheless :-().
265 ;;;  Will not indent something inside pod and here-documents.
266 ;;;  Fontifies the package name after import/no/bootstrap.
267 ;;;  Added new entry to menu with meta-info about the mode.
268
269 ;;;; After 1.19:
270 ;;;  Prefontification works much better with 19.29. Should be checked
271 ;;;   with 19.30 as well.
272 ;;;  Some misprints in docs corrected.
273 ;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
274 ;;;  Now the pod search is much stricter, so it can help you to find
275 ;;;    pod sections which are broken because of whitespace before =blah
276 ;;;    - just observe the fontification.
277
278 ;;;; After 1.20
279 ;;;  Anonymous subs are indented with respect to the level of
280 ;;;    indentation of `sub' now.
281 ;;;  {} is recognized as hash after `bless' and `return'.
282 ;;;  Anonymous subs are split by `cperl-linefeed' as well.
283 ;;;  Electric parens embrace a region if present.
284 ;;;  To make `cperl-auto-newline' useful,
285 ;;;    `cperl-auto-newline-after-colon' is introduced.
286 ;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
287 ;;;  `cperl-electric-parens-string'.
288 ;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
289 ;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
290 ;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
291 ;;;  Beginning-of-defun-regexp was not anchored.
292
293 ;;;; After 1.21
294 ;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
295 ;;;    after ")".
296 ;;;  {} is recognized as expression after `tr' and friends.
297
298 ;;;; After 1.22
299 ;;;  Entry Hierarchy added to imenu. Very primitive so far.
300 ;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
301 ;;;  Writes its own TAGS files.
302 ;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
303 ;;;  19.31: Problems with scan for PODs corrected.
304 ;;;  First POD header correctly fontified.
305 ;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
306 ;;;  Apparently it makes a lot of hierarchy code obsolete...
307
308 ;;;; After 1.23
309 ;;;  Tags filler now scans *.xs as well.
310 ;;;  The info from *.xs scan is used by the hierarchy viewer.
311 ;;;  Hierarchy viewer documented.
312 ;;;  Bug in 19.31 imenu documented.
313
314 ;;;; After 1.24
315 ;;;  New location for info-files mentioned,
316 ;;;  Electric-; should work better.
317 ;;;  Minor bugs with POD marking.
318
319 ;;;; After 1.25 (probably not...)
320 ;;;  `cperl-info-page' introduced.
321 ;;;  To make `uncomment-region' working, `comment-region' would
322 ;;;  not insert extra space.
323 ;;;  Here documents delimiters better recognized
324 ;;;  (empty one, and non-alphanums in quotes handled). May be wrong with 1<<14?
325 ;;;  `cperl-db' added, used in menu.
326 ;;;  imenu scan removes text-properties, for better debugging
327 ;;;    - but the bug is in 19.31 imenu.
328 ;;;  formats highlighted by font-lock and prescan, embedded comments
329 ;;;  are not treated.
330 ;;;  POD/friends scan merged in one pass.
331 ;;;  Syntax class is not used for analyzing the code, only char-syntax
332 ;;;  may be checked against _ or'ed with w.
333 ;;;  Syntax class of `:' changed to be _.
334 ;;;  `cperl-find-bad-style' added.
335
336 ;;;; After 1.25
337 ;;;  When search for here-documents, we ignore commented << in simplest cases.
338 ;;;  `cperl-get-help' added, available on C-h v and from menu.
339 ;;;  Auto-help added. Default with `cperl-hairy', switchable on/off
340 ;;;   with startup variable `cperl-lazy-help-time' and from
341 ;;;   menu. Requires `run-with-idle-timer'.
342 ;;;  Highlighting of @abc{@efg} was wrong - interchanged two regexps.
343
344 ;;;; After 1.27
345 ;;;  Indentation: At toplevel after a label - fixed.
346 ;;;  1.27 was put to archives in binary mode ===> DOSish :-(
347
348 ;;;; After 1.28
349 ;;;  Thanks to Martin Buchholz <mrb@Eng.Sun.COM>: misprints in
350 ;;;  comments and docstrings corrected, XEmacs support cleaned up.
351 ;;;  The closing parenths would enclose the region into matching
352 ;;;  parens under the same conditions as the opening ones.
353 ;;;  Minor updates to `cperl-short-docs'.
354 ;;;  Will not consider <<= as start of here-doc.
355
356 ;;;; After 1.29
357 ;;;  Added an extra advice to look into Micro-docs. ;-).
358 ;;;  Enclosing of region when you press a closing parenth is regulated by
359 ;;;  `cperl-electric-parens-string'.
360 ;;;  Minor updates to `cperl-short-docs'.
361 ;;;  `initialize-new-tags-table' called only if present (Does this help
362 ;;;     with generation of tags under XEmacs?).
363 ;;;  When creating/updating tag files, new info is written at the old place,
364 ;;;     or at the end (is this a wanted behaviour? I need this in perl build directory).
365
366 ;;;; After 1.30
367 ;;;  All the keywords from keywords.pl included (maybe with dummy explanation).
368 ;;;  No auto-help inside strings, comment, here-docs, formats, and pods.
369 ;;;  Shrinkwrapping of info, regulated by `cperl-max-help-size',
370 ;;;  `cperl-shrink-wrap-info-frame'.
371 ;;;  Info on variables as well.
372 ;;;  Recognision of HERE-DOCS improved yet more.
373 ;;;  Autonewline works on `}' without warnings.
374 ;;;  Autohelp works again on $_[0].
375
376 ;;;; After 1.31
377 ;;;  perl-descr.el found its author - hi, Johan!
378 ;;;  Some support for correct indent after here-docs and friends (may
379 ;;;  be superseeded by eminent change to Emacs internals).
380 ;;;  Should work with older Emaxen as well ( `-style stuff removed).
381
382 ;;;; After 1.32
383
384 ;;;  Started to add support for `syntax-table' property (should work
385 ;;;  with patched Emaxen), controlled by
386 ;;;  `cperl-use-syntax-table-text-property'. Currently recognized:
387 ;;;    All quote-like operators: m, s, y, tr, qq, qw, qx, q,
388 ;;;    // in most frequent context:
389 ;;;          after block or
390 ;;;                    ~ { ( = | & + - * ! , ;
391 ;;;          or
392 ;;;                    while if unless until and or not xor split grep map
393 ;;;    Here-documents, formats, PODs,
394 ;;;    ${...}
395 ;;;    'abc$'
396 ;;;    sub a ($); sub a ($) {}
397 ;;;  (provide 'cperl-mode) was missing!
398 ;;;  `cperl-after-expr-p' is now much smarter after `}'.
399 ;;;  `cperl-praise' added to mini-docs.
400 ;;;  Utilities try to support subs-with-prototypes.
401
402 ;;;; After 1.32.1
403 ;;;  `cperl-after-expr-p' is now much smarter after "() {}" and "word {}":
404 ;;;     if word is "else, map, grep".
405 ;;;  Updated for new values of syntax-table constants.
406 ;;;  Uses `help-char' (at last!) (disabled, does not work?!)
407 ;;;  A couple of regexps where missing _ in character classes.
408 ;;;  -s could be considered as start of regexp, 1../blah/ was not,
409 ;;;  as was not /blah/ at start of file.
410
411 ;;;; After 1.32.2
412 ;;;  "\C-hv" was wrongly "\C-hf"
413 ;;;  C-hv was not working on `[index()]' because of [] in skip-chars-*.
414 ;;;  `__PACKAGE__' supported.
415 ;;;  Thanks for Greg Badros: `cperl-lazy-unstall' is more complete,
416 ;;;  `cperl-get-help' is made compatible with `query-replace'.
417
418 ;;;; As of Apr 15, development version of 19.34 supports
419 ;;;; `syntax-table' text properties. Try setting
420 ;;;; `cperl-use-syntax-table-text-property'.
421
422 ;;;; After 1.32.3
423 ;;;  We scan for s{}[] as well (in simplest situations).
424 ;;;  We scan for $blah'foo as well.
425 ;;;  The default is to use `syntax-table' text property if Emacs is good enough.
426 ;;;  `cperl-lineup' is put on C-M-| (=C-M-S-\\).
427 ;;;  Start of `cperl-beautify-regexp'.
428
429 ;;;; After 1.32.4
430 ;;; `cperl-tags-hier-init' did not work in text-mode.
431 ;;; `cperl-noscan-files-regexp' had a misprint.
432 ;;; Generation of Class Hierarchy was broken due to a bug in `x-popup-menu'
433 ;;;  in 19.34.
434
435 ;;;; After 1.33:
436 ;;; my,local highlight vars after {} too.
437 ;;; TAGS could not be created before imenu was loaded.
438 ;;; `cperl-indent-left-aligned-comments' created.
439 ;;; Logic of `cperl-indent-exp' changed a little bit, should be more
440 ;;;  robust w.r.t. multiline strings.
441 ;;; Recognition of blah'foo takes into account strings.
442 ;;; Added '.al' to the list of Perl extensions.
443 ;;; Class hierarchy is "mostly" sorted (need to rethink algorthm
444 ;;;  of pruning one-root-branch subtrees to get yet better sorting.)
445 ;;; Regeneration of TAGS was busted.
446 ;;; Can use `syntax-table' property when generating TAGS
447 ;;;  (governed by  `cperl-use-syntax-table-text-property-for-tags').
448
449 ;;;; After 1.35:
450 ;;; Can process several =pod/=cut sections one after another.
451 ;;; Knows of `extproc' when under `emx', indents with `__END__' and `__DATA__'.
452 ;;; `cperl-under-as-char' implemented (XEmacs people like broken behaviour).
453 ;;; Beautifier for regexps fixed.
454 ;;; `cperl-beautify-level', `cperl-contract-level' coded
455 ;;;
456 ;;;; Emacs's 20.2 problems:
457 ;;; `imenu.el' has bugs, `imenu-add-to-menubar' does not work.
458 ;;; Couple of others problems with 20.2 were reported, my ability to check/fix
459 ;;; them is very reduced now.
460
461 ;;;; After 1.36:
462 ;;;  'C-M-|' in XEmacs fixed
463
464 ;;;; After 1.37:
465 ;;;  &&s was not recognized as start of regular expression;
466 ;;;  Will "preprocess" the contents of //e part of s///e too;
467 ;;;  What to do with s# blah # foo #e ?
468 ;;;  Should handle s;blah;foo;; better.
469 ;;;  Now the only known problems with regular expression recognition:
470 ;;;;;;;  s<foo>/bar/    - different delimiters (end ignored)
471 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into one chunk)
472 ;;;;;;;  s/foo//        - empty subst (made into one chunk + '/')
473 ;;;;;;;  s/foo/(bar)/   - start-group at start of subst (internal group will not match backwards)
474
475 ;;;; After 1.38:
476 ;;;  We highlight closing / of s/blah/foo/e;
477 ;;;  This handles s# blah # foo #e too;
478 ;;;  s//blah/, s///, s/blah// works again, and s#blah## too, the algorithm
479 ;;;   is much simpler now;
480 ;;;  Next round of changes: s\\\ works, s<blah>/foo/,
481 ;;;   comments between the first and the second part allowed
482 ;;;  Another problem discovered:
483 ;;;;;;;  s[foo] <blah>e - e part delimited by different <> (will not match)
484 ;;;  `cperl-find-pods-heres' somehow maybe called when string-face is undefined
485 ;;;   - put a stupid workaround for 20.1
486
487 ;;;; After 1.39:
488 ;;;  Could indent here-docs for comments;
489 ;;;  These problems fixed:
490 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into two chunk)
491 ;;;;;;;  s[foo] <blah>e - "e" part delimited by "different" <> (will match)
492 ;;;  Matching brackets honor prefices, may expand abbreviations;
493 ;;;  When expanding abbrevs, will remove last char only after
494 ;;;    self-inserted whitespace;
495 ;;;  More convenient "Refress hard constructs" in menu;
496 ;;;  `cperl-add-tags-recurse', `cperl-add-tags-recurse-noxs'
497 ;;;    added (for -batch mode);
498 ;;;  Better handling of errors when scanning for Perl constructs;
499 ;;;;;;;  Possible "problem" with class hierarchy in Perl distribution
500 ;;;;;;;    directory: ./ext duplicates ./lib;
501 ;;;  Write relative paths for generated TAGS;
502
503 ;;;; After 1.40:
504 ;;;  s  /// may be separated by "\n\f" too;
505 ;;;  `s  #blah' recognized as a comment;
506 ;;;  Would highlight s/abc//s wrong;
507 ;;;  Debugging code in `cperl-electric-keywords' was leaking a message;
508
509 ;;;; After 1.41:
510 ;;;  RMS changes for 20.3 merged
511
512 ;;;; 2.0.1.0: RMS mode (has 3 misprints)
513
514 ;;;; After 2.0:
515 ;;;  RMS whitespace changes for 20.3 merged
516
517 ;;;; After 2.1:
518 ;;;  History updated
519
520 ;;;; After 2.2:
521 ;;;  Merge `c-style-alist' since `c-mode' is no more.  (Somebody who
522 ;;;    uses the styles should check that they work OK!)
523 ;;;  All the variable warnings go away, some undef functions too.
524
525 ;;;; After 2.3:
526 ;;;  Added `cperl-perldoc' (thanks to Anthony Foiani <afoiani@uswest.com>)
527 ;;;  Added `cperl-pod-to-manpage' (thanks to Nick Roberts <Nick.Roberts@src.bae.co.uk>)
528 ;;;  All the function warnings go away.
529
530 ;;;; After 2.4:
531 ;;;  `Perl doc', `Regexp' submenus created (latter to allow short displays).
532 ;;;  `cperl-clobber-lisp-bindings' added.
533 ;;;  $a->y() is not y///.
534 ;;;  `cperl-after-block-p' was missing a `save-excursion' => wrong results.
535 ;;;  `cperl-val' was defined too late.
536 ;;;  `cperl-init-faces' was failing.
537 ;;;  Init faces when loading `ps-print'.
538
539 ;;;; After 2.4:
540 ;;;  `cperl-toggle-autohelp' implemented.
541 ;;;  `while SPACE LESS' was buggy.
542 ;;;  `-text' in `[-text => 1]' was not highlighted.
543 ;;;  `cperl-after-block-p' was FALSE after `sub f {}'.
544
545 ;;;; After 2.5:
546 ;;;  `foreachmy', `formy' expanded too.
547 ;;;  Expand `=pod-directive'.
548 ;;;  `cperl-linefeed' behaves reasonable in POD-directive lines.
549 ;;;  `cperl-electric-keyword' prints a message, governed by
550 ;;;    `cperl-message-electric-keyword'.
551
552 ;;;; After 2.6:
553 ;;;  Typing `}' was not checking for being block or not.
554 ;;;  Beautifying levels in RE: Did not know about lookbehind;
555 ;;;                            finding *which* level was not intuitive;
556 ;;;                            `cperl-beautify-levels' added.
557 ;;;  Allow here-docs contain `=head1' and friends (at least for keywords).
558
559 ;;;; After 2.7:
560 ;;;  Fix for broken `font-lock-unfontify-region-function'.  Should
561 ;;;    preserve `syntax-table' properties even with `lazy-lock'.
562
563 ;;;; After 2.8:
564 ;;;  Some more compile time warnings crept in.
565 ;;;  `cperl-indent-region-fix-else' implemented.
566 ;;;  `cperl-fix-line-spacing' implemented.
567 ;;;  `cperl-invert-if-unless' implemented (C-c C-t and in Menu).
568 ;;;  Upgraded hints to mention 20.2's goods/bads.
569 ;;;  Started to use `cperl-extra-newline-before-brace-multiline',
570 ;;;    `cperl-break-one-line-blocks-when-indent',
571 ;;;    `cperl-fix-hanging-brace-when-indent', `cperl-merge-trailing-else'.
572
573 ;;;; After 2.9:
574 ;;;  Workaround for another `font-lock's `syntax-table' text-property bug.
575 ;;;  `zerop' could be applied to nil.
576 ;;;  At last, may work with `font-lock' without setting `cperl-font-lock'.
577 ;;;    (We expect that starting from 19.33, `font-lock' supports keywords
578 ;;;     being a function - what is a correct version?)
579 ;;;  Rename `cperl-indent-region-fix-else' to
580 ;;;    `cperl-indent-region-fix-constructs'.
581 ;;;  `cperl-fix-line-spacing' could be triggered inside strings, would not
582 ;;;     know what to do with BLOCKs of map/printf/etc.
583 ;;;  `cperl-merge-trailing-else' and `cperl-fix-line-spacing' handle
584 ;;;     `continue' too.
585 ;;;  Indentation after {BLOCK} knows about map/printf/etc.
586 ;;;  Finally: treat after-comma lines as continuation lines.
587
588 ;;;; After 2.10:
589 ;;;  `continue' made electric.
590 ;;;  Electric `do' inserts `do/while'.
591 ;;;  Some extra compile-time warnings crept in.
592 ;;;  `font-lock' of 19.33 could not handle font-lock-keywords being a function
593 ;;;      returning a symbol.
594
595 ;;;; After 2.11:
596 ;;;  Changes to make syntaxification to be autoredone via `font-lock'.
597 ;;;    Switched on by `cperl-syntaxify-by-font-lock', off by default so far.
598
599 ;;;; After 2.12:
600 ;;;  Remove some commented out chunks.
601 ;;;  Styles are slightly updated (a lot of work is needed, especially
602 ;;;    with new `cperl-fix-line-spacing').
603
604 ;;;; After 2.13:
605 ;;;  Old value of style is memorized when choosing a new style, may be
606 ;;;    restored from the same menu.
607 ;;;  Mode-documentation added to micro-docs.
608 ;;;  `cperl-praise' updated.
609 ;;;  `cperl-toggle-construct-fix' added on C-c C-w and menu.
610 ;;;  `auto-fill-mode' added on C-c C-f and menu.
611 ;;;  `PerlStyle' style added.
612 ;;;  Message for termination of scan corrected.
613
614 ;;;; After 2.14:
615
616 ;;;  Did not work with -q
617
618 ;;;; After 2.15:
619
620 ;;;  `cperl-speed' hints added.
621 ;;;  Minor style fixes.
622
623 ;;;; After 2.15:
624 ;;;  Make backspace electric after expansion of `else/continue' too.
625
626 ;;;; After 2.16:
627 ;;;  Starting to merge changes to RMS emacs version.
628
629 ;;;; After 2.17:
630 ;;;  Merged custom stuff and darn `font-lock-constant-face'.
631
632 ;;;; After 2.18:
633 ;;;  Bumped the version to 3.1
634
635 ;;;; After 3.1:
636 ;;;  Fixed customization to honor cperl-hairy.
637 ;;;  Created customization groups.  Sent to RMS to include into 2.3.
638
639 ;;;; After 3.2:
640 ;;;  Interaction of `font-lock-hot-pass' and `cperl-syntaxify-by-font-lock'.
641 ;;;  (`cperl-after-block-and-statement-beg'):
642 ;;;  (`cperl-after-block-p'):
643 ;;;  (`cperl-after-expr-p'):    It is BLOCK if we reach lim when backup sexp.
644 ;;;  (`cperl-indent-region'):   Make a marker for END - text added/removed.
645 ;;;  (`cperl-style-alist', `cperl-styles-entries')
646 ;;;             Include `cperl-merge-trailing-else' where the value is clear.
647
648 ;;;; After 3.3:
649 ;;;  (`cperl-tips'):
650 ;;;  (`cperl-problems'):        Improvements to docs.
651
652 ;;;; After 3.4:
653 ;;;  (`cperl-mode'):            Make lazy syntaxification possible.
654 ;;;  (`cperl-find-pods-heres'): Safe a position in buffer where it is safe to
655 ;;;                             restart syntaxification.
656 ;;;  (`cperl-syntaxify-by-font-lock'): Set to t, should be safe now.
657
658 ;;;; After 3.5:
659 ;;;  (`cperl-syntaxify-by-font-lock'): Better default, customizes to
660 ;;;                             `message' too.
661
662 ;;;; After 3.6:
663 ;;;  (`cperl-find-pods-heres'): changed so that -d ?foo? is a RE.
664 ;;;  (`cperl-array-face'): changed name from `font-lock-emphasized-face'.
665 ;;;  (`cperl-hash-face'): changed name from  `font-lock-other-emphasized-face'.
666 ;;;  Use `defface' to define these two extra faces.
667
668 ;;;; After 3.7:
669 ;;;  Can use linear algorithm for indentation if Emacs supports it:
670 ;;;  indenting DB::DB (800+ lines) improved from 69 sec to 11 sec
671 ;;;  (73 vs 15 with imenu).
672 ;;;  (`cperl-emacs-can-parse'): New state.
673 ;;;  (`cperl-indent-line'):     Corrected to use global state.
674 ;;;  (`cperl-calculate-indent'):        Likewise.
675 ;;;  (`cperl-fix-line-spacing'):        Likewise (not used yet).
676
677 ;;;; After 3.8:
678 ;;;  (`cperl-choose-color'):    Converted to a function (to be compilable in text-mode).
679
680 ;;;; After 3.9:
681 ;;;  (`cperl-dark-background '):        Disable without window-system.
682
683 ;;;; After 3.10:
684 ;;;  Do `defface' only if window-system.
685
686 ;;;; After 3.11:
687 ;;;  (`cperl-fix-line-spacing'):        sped up to bail out early.
688 ;;;  (`cperl-indent-region'):   Disable hooks during the call (how to call them later?).
689
690 ;;;  Now indents 820-line-long function in 6.5 sec (including syntaxification) the first time
691 ;;;  (when buffer has few properties), 7.1 sec the second time.
692
693 ;;;Function Name                              Call Count  Elapsed Time  Average Time
694 ;;;=========================================  ==========  ============  ============
695 ;;;cperl-indent-exp                           1           10.039999999  10.039999999
696 ;;;cperl-indent-region                        1           10.0          10.0
697 ;;;cperl-indent-line                          821         6.2100000000  0.0075639464
698 ;;;cperl-calculate-indent                     821         5.0199999999  0.0061144945
699 ;;;cperl-backward-to-noncomment               2856        2.0500000000  0.0007177871
700 ;;;cperl-fontify-syntaxically                 2           1.78          0.8900000000
701 ;;;cperl-find-pods-heres                      2           1.78          0.8900000000
702 ;;;cperl-update-syntaxification               1           1.78          1.78
703 ;;;cperl-fix-line-spacing                     769         1.4800000000  0.0019245773
704 ;;;cperl-after-block-and-statement-beg        163         1.4100000000  0.0086503067
705 ;;;cperl-block-p                              775         1.1800000000  0.0015225806
706 ;;;cperl-to-comment-or-eol                    3652        1.1200000000  0.0003066812
707 ;;;cperl-after-block-p                        165         1.0500000000  0.0063636363
708 ;;;cperl-commentify                           141         0.22          0.0015602836
709 ;;;cperl-get-state                            813         0.16          0.0001968019
710 ;;;cperl-backward-to-start-of-continued-exp   26          0.12          0.0046153846
711 ;;;cperl-delay-update-hook                    2107        0.0899999999  4.271...e-05
712 ;;;cperl-protect-defun-start                  141         0.0700000000  0.0004964539
713 ;;;cperl-after-label                          407         0.0599999999  0.0001474201
714 ;;;cperl-forward-re                           139         0.0299999999  0.0002158273
715 ;;;cperl-comment-indent                       26          0.0299999999  0.0011538461
716 ;;;cperl-use-region-p                         8           0.0           0.0
717 ;;;cperl-lazy-hook                            15          0.0           0.0
718 ;;;cperl-after-expr-p                         8           0.0           0.0
719 ;;;cperl-font-lock-unfontify-region-function  1           0.0           0.0
720
721 ;;;Function Name                              Call Count  Elapsed Time  Average Time
722 ;;;=========================================  ==========  ============  ============
723 ;;;cperl-fix-line-spacing                     769         1.4500000000  0.0018855656
724 ;;;cperl-indent-line                          13          0.3100000000  0.0238461538
725 ;;;cperl-after-block-and-statement-beg        69          0.2700000000  0.0039130434
726 ;;;cperl-after-block-p                        69          0.2099999999  0.0030434782
727 ;;;cperl-calculate-indent                     13          0.1000000000  0.0076923076
728 ;;;cperl-backward-to-noncomment               177         0.0700000000  0.0003954802
729 ;;;cperl-get-state                            13          0.0           0.0
730 ;;;cperl-to-comment-or-eol                    179         0.0           0.0
731 ;;;cperl-get-help-defer                       1           0.0           0.0
732 ;;;cperl-lazy-hook                            11          0.0           0.0
733 ;;;cperl-after-expr-p                         2           0.0           0.0
734 ;;;cperl-block-p                              13          0.0           0.0
735 ;;;cperl-after-label                          5           0.0           0.0
736
737 ;;;; After 3.12:
738 ;;;  (`cperl-find-pods-heres'): do not warn on `=cut' if doing a chunk only.
739
740 ;;;; After 3.13:
741 ;;;  (`cperl-mode'): load pseudo-faces on `cperl-find-pods-heres' (for 19.30).
742 ;;;  (`x-color-defined-p'): was not compiling on XEmacs
743 ;;;  (`cperl-find-pods-heres'): 1 << 6 was OK, but 1<<6 was considered as HERE
744 ;;;                             <file/glob> made into a string.
745
746 ;;;; After 3.14:
747 ;;;  (`cperl-find-pods-heres'): Postpone addition of faces after syntactic step
748 ;;;                             Recognition of <FH> was wrong.
749 ;;;  (`cperl-clobber-lisp-bindings'): if set, C-c variants are the old ones
750 ;;;  (`cperl-unwind-to-safe'):  New function.
751 ;;;  (`cperl-fontify-syntaxically'): Use `cperl-unwind-to-safe' to start at reasonable position.
752
753 ;;;; After 3.15:
754 ;;;  (`cperl-forward-re'):      Highlight the trailing / in s/foo// as string.
755 ;;;                     Highlight the starting // in s//foo/ as function-name.
756
757 ;;;; After 3.16:
758 ;;;  (`cperl-find-pods-heres'): Highlight `gem' in s///gem as a keyword.
759
760 ;;;; After 4.0:
761 ;;;  (`cperl-find-pods-heres'): `qr' added
762 ;;;  (`cperl-electric-keyword'):        Likewise
763 ;;;  (`cperl-electric-else'):           Likewise
764 ;;;  (`cperl-to-comment-or-eol'):       Likewise
765 ;;;  (`cperl-make-regexp-x'):   Likewise
766 ;;;  (`cperl-init-faces'):      Likewise, and `lock' (as overridable?).
767 ;;;  (`cperl-find-pods-heres'): Knows that split// is null-RE.
768 ;;;                             Highlights separators in 3-parts expressions
769 ;;;                             as labels.
770
771 ;;;; After 4.1:
772 ;;;  (`cperl-find-pods-heres'): <> was considered as a glob
773 ;;;  (`cperl-syntaxify-unwind'): New configuration variable
774 ;;;  (`cperl-fontify-m-as-s'):  New configuration variable
775
776 ;;;; After 4.2:
777 ;;;  (`cperl-find-pods-heres'): of the last line being `=head1' fixed.
778
779 ;;;  Handling of a long construct is still buggy if only the part of
780 ;;;  construct touches the updated region (we unwind to the start of
781 ;;;  long construct, but the end may have residual properties).
782
783 ;;;  (`cperl-unwind-to-safe'):  would not go to beginning of buffer.
784 ;;;  (`cperl-electric-pod'):    check for after-expr was performed
785 ;;;                             inside of POD too.
786
787 ;;;; After 4.3:
788 ;;;  (`cperl-backward-to-noncomment'):  better treatment of PODs and HEREs.
789
790 ;;;  Indent-line works good, but indent-region does not - at toplevel...
791 ;;;  (`cperl-unwind-to-safe'):  Signature changed.
792 ;;;  (`x-color-defined-p'):     was defmacro'ed with a tick.  Remove another def.
793 ;;;  (`cperl-clobber-mode-lists'): New configuration variable.
794 ;;;  (`cperl-array-face'): One of definitions was garbled.
795
796 ;;;; After 4.4:
797 ;;;  (`cperl-not-bad-style-regexp'):    Updated.
798 ;;;  (`cperl-make-regexp-x'):   Misprint in a message.
799 ;;;  (`cperl-find-pods-heres'): $a-1 ? foo : bar; was a regexp.
800 ;;;                             `<< (' was considered a start of POD.
801 ;;;  Init:                      `cperl-is-face' was busted.
802 ;;;  (`cperl-make-face'):       New macros.
803 ;;;  (`cperl-force-face'):      New macros.
804 ;;;  (`cperl-init-faces'):      Corrected to use new macros;
805 ;;;                             `if' for copying `reference-face' to
806 ;;;                             `constant-face' was backward.
807 ;;;  (`font-lock-other-type-face'): Done via `defface' too.
808
809 ;;;; After 4.5:
810 ;;;  (`cperl-init-faces-weak'): use `cperl-force-face'.
811 ;;;  (`cperl-after-block-p'):   After END/BEGIN we are a block.
812 ;;;  (`cperl-mode'):            `font-lock-unfontify-region-function'
813 ;;;                             was set to a wrong function.
814 ;;;  (`cperl-comment-indent'):  Commenting __END__ was not working.
815 ;;;  (`cperl-indent-for-comment'):      Likewise.
816 ;;;                             (Indenting is still misbehaving at toplevel.)
817
818 ;;;; After 4.5:
819 ;;;  (`cperl-unwind-to-safe'):  Signature changed, unwinds end too.
820 ;;;  (`cperl-find-pods-heres'): mark qq[]-etc sections as syntax-type=string
821 ;;;  (`cperl-fontify-syntaxically'): Unwinds start and end to go out of
822 ;;;                                  long strings (not very successful).
823
824 ;;;   >>>>  CPerl should be usable in write mode too now <<<<
825
826 ;;;  (`cperl-syntaxify-by-font-lock'): Better default - off in text-mode.
827 ;;;  (`cperl-tips'):            Updated docs.
828 ;;;  (`cperl-problems'):        Updated docs.
829
830 ;;;; After 4.6:
831 ;;;  (`cperl-calculate-indent'):        Did not consider `,' as continuation mark for statements.
832 ;;;  (`cperl-write-tags'):      Correct for XEmacs's `visit-tags-table-buffer'.
833
834 ;;;; After 4.7:
835 ;;;  (`cperl-calculate-indent'): Avoid parse-data optimization at toplevel.
836 ;;;                              Should indent correctly at toplevel too.
837 ;;;  (`cperl-tags-hier-init'):  Gross hack to pretend we work (are we?).
838 ;;;  (`cperl-find-pods-heres'): Was not processing sub protos after a comment ine.
839 ;;;                             Was treating $a++ <= 5 as a glob.
840
841 ;;;; After 4.8:
842 ;;;  (toplevel):                require custom unprotected => failure on 19.28.
843 ;;;  (`cperl-xemacs-p')         defined when compile too
844 ;;;  (`cperl-tags-hier-init'):  Another try to work around XEmacs problems
845 ;;;                             Better progress messages.
846 ;;;  (`cperl-find-tags'):       Was writing line/pos in a wrong order,
847 ;;;                             pos off by 1 and not at beg-of-line.
848 ;;;  (`cperl-etags-snarf-tag'): New macro
849 ;;;  (`cperl-etags-goto-tag-location'): New macro
850 ;;;  (`cperl-write-tags'):      When removing old TAGS info was not
851 ;;;                             relativizing filename
852
853 ;;;; After 4.9:
854 ;;;  (`cperl-version'):         New variable.  New menu entry
855
856 ;;;; After 4.10:
857 ;;;  (`cperl-tips'):            Updated.
858 ;;;  (`cperl-non-problems'):    Updated.
859 ;;;  random:                    References to future 20.3 removed.
860
861 ;;;; After 4.11:
862 ;;;  (`perl-font-lock-keywords'): Would not highlight `sub foo($$);'.
863 ;;;  Docstrings:                Menu was described as `CPerl' instead of `Perl'
864
865 ;;;; After 4.12:
866 ;;;  (`cperl-toggle-construct-fix'): Was toggling to t instead of 1.
867 ;;;  (`cperl-ps-print-init'):   Associate `cperl-array-face', `cperl-hash-face'
868 ;;;                             remove `font-lock-emphasized-face'.
869 ;;;                             remove `font-lock-other-emphasized-face'.
870 ;;;                             remove `font-lock-reference-face'.
871 ;;;                             remove `font-lock-keyword-face'.
872 ;;;                             Use `eval-after-load'.
873 ;;;  (`cperl-init-faces'):      remove init `font-lock-other-emphasized-face'.
874 ;;;                             remove init `font-lock-emphasized-face'.
875 ;;;                             remove init `font-lock-keyword-face'.
876 ;;;  (`cperl-tips-faces'):      New variable and an entry into Mini-docs.
877 ;;;  (`cperl-indent-region'):   Do not indent whitespace lines
878 ;;;  (`cperl-indent-exp'):      Was not processing else-blocks.
879 ;;;  (`cperl-calculate-indent'): Remove another parse-data optimization
880 ;;;                              at toplevel: would indent correctly.
881 ;;;  (`cperl-get-state'):       NOP line removed.
882
883 ;;;; After 4.13:
884 ;;;  (`cperl-ps-print-init'):   Remove not-CPerl-related faces.
885 ;;;  (`cperl-ps-print'):        New function and menu entry.
886 ;;;  (`cperl-ps-print-face-properties'):        New configuration variable.
887 ;;;  (`cperl-invalid-face'):    New configuration variable.
888 ;;;  (`cperl-nonoverridable-face'):     New face.  Renamed from
889 ;;;                                     `font-lock-other-type-face'.
890 ;;;  (`perl-font-lock-keywords'):       Highlight trailing whitespace
891 ;;;  (`cperl-contract-levels'): Documentation corrected.
892 ;;;  (`cperl-contract-level'):  Likewise.
893
894 ;;;; After 4.14:
895 ;;;  (`cperl-ps-print'): `ps-print-face-extension-alist' was not in old Emaxen,
896 ;;;                             same with `ps-extend-face-list'
897 ;;;  (`cperl-ps-extend-face-list'):     New macro.
898
899 ;;;; After 4.15:
900 ;;;  (`cperl-init-faces'):      Interpolate `cperl-invalid-face'.
901 ;;;  (`cperl-forward-re'):      Emit a meaningful error instead of a cryptic
902 ;;;                             one for uncomplete REx near end-of-buffer.
903 ;;;  (`cperl-find-pods-heres'): Tolerate unfinished REx at end-of-buffer.
904
905 ;;;; After 4.16:
906 ;;;  (`cperl-find-pods-heres'): `unwind-protect' was left commented.
907
908 ;;;; After 4.17:
909 ;;;  (`cperl-invalid-face'):    Change to ''underline.
910
911 ;;;; After 4.18:
912 ;;;  (`cperl-find-pods-heres'): / and ? after : start a REx.
913 ;;;  (`cperl-after-expr-p'):    Skip labels when checking
914 ;;;  (`cperl-calculate-indent'): Correct for labels when calculating
915 ;;;                                     indentation of continuations.
916 ;;;                             Docstring updated.
917
918 ;;;; After 4.19:
919 ;;;  Minor (mostly spelling) corrections from 20.3.3 merged.
920
921 ;;;; After 4.20:
922 ;;;  (`cperl-tips'):            Another workaround added.  Sent to RMS for 20.4.
923
924 ;;;; After 4.21:
925 ;;;  (`cperl-praise'):          Mention linear-time indent.
926 ;;;  (`cperl-find-pods-heres'): @if ? a : b was considered a REx.
927
928 ;;;; After 4.22:
929 ;;;  (`cperl-after-expr-p'):    Make true after __END__.
930 ;;;  (`cperl-electric-pod'):    "SYNOPSIS" was misspelled.
931
932 ;;;; After 4.23:
933 ;;;  (`cperl-beautify-regexp-piece'):   Was not allowing for *? after a class.
934 ;;;                                     Allow for POSIX char-classes.
935 ;;;                                     Remove trailing whitespace when
936 ;;;                                     adding new linebreak.
937 ;;;                                     Add a level counter to stop shallow.
938 ;;;                                     Indents unprocessed groups rigidly.
939 ;;;  (`cperl-beautify-regexp'): Add an optional count argument to go that
940 ;;;                             many levels deep.
941 ;;;  (`cperl-beautify-level'):  Likewise
942 ;;;  Menu:                      Add new entries to Regexp menu to do one level
943 ;;;  (`cperl-contract-level'):  Was entering an infinite loop
944 ;;;  (`cperl-find-pods-heres'): Typo (double quoting).
945 ;;;                             Was detecting < $file > as FH instead of glob.
946 ;;;                             Support for comments in RExen (except
947 ;;;                             for m#\#comment#x), governed by
948 ;;;                             `cperl-regexp-scan'.
949 ;;;  (`cperl-regexp-scan'):     New customization variable.
950 ;;;  (`cperl-forward-re'):      Improve logic of resetting syntax table.
951
952 ;;;; After 4.23 and: After 4.24:
953 ;;;  (`cperl-contract-levels'): Restore position.
954 ;;;  (`cperl-beautify-level'):  Likewise.
955 ;;;  (`cperl-beautify-regexp'): Likewise.
956 ;;;  (`cperl-commentify'):      Rudimental support for length=1 runs
957 ;;;  (`cperl-find-pods-heres'): Process 1-char long REx comments too /a#/x
958 ;;;                             Processes REx-comments in #-delimited RExen.
959 ;;;                             MAJOR BUG CORRECTED: after a misparse
960 ;;;                               a body of a subroutine could be corrupted!!!
961 ;;;                               One might need to reeval the function body
962 ;;;                               to fix things.  (A similar bug was
963 ;;;                               present in `cperl-indent-region' eons ago.)
964 ;;; To reproduce:
965 ;;   (defun foo () (let ((a '(t))) (insert (format "%s" a)) (setcar a 'BUG) t))
966 ;;   (foo)
967 ;;   (foo)
968 ;;; C-x C-e the above three lines (at end-of-line).  First evaluation
969 ;;; of `foo' inserts (t), second one inserts (BUG) ?!
970 ;;;
971 ;;; In CPerl it was triggered by inserting then deleting `/' at start of
972 ;;;      /  a (?# asdf  {[(}asdf )ef,/;
973
974 ;;;; After 4.25:
975 ;;; (`cperl-commentify'):       Was recognizing length=2 "strings" as length=1.
976 ;;; (`imenu-example--create-perl-index'):
977 ;;;                             Was not enforcing syntaxification-to-the-end.
978 ;;; (`cperl-invert-if-unless'): Allow `for', `foreach'.
979 ;;; (`cperl-find-pods-heres'):  Quote `cperl-nonoverridable-face'.
980 ;;;                             Mark qw(), m()x as indentable.
981 ;;; (`cperl-init-faces'):       Highlight `sysopen' too.
982 ;;;                             Highlight $var in `for my $var' too.
983 ;;; (`cperl-invert-if-unless'): Was leaving whitespace at end.
984 ;;; (`cperl-linefeed'):         Was splitting $var{$foo} if point after `{'.
985 ;;; (`cperl-calculate-indent'): Remove old commented out code.
986 ;;;                             Support (primitive) indentation of qw(), m()x.
987
988
989 ;;;; After 4.26:
990 ;;; (`cperl-problems'):         Mention `fill-paragraph' on comment. \"" and
991 ;;;                             q [] with intervening newlines.
992 ;;; (`cperl-autoindent-on-semi'):       New customization variable.
993 ;;; (`cperl-electric-semi'):    Use `cperl-autoindent-on-semi'.
994 ;;; (`cperl-tips'):             Mention how to make CPerl the default mode.
995 ;;; (`cperl-mode'):             Support `outline-minor-mode'
996 ;;;                             (Thanks to Mark A. Hershberger).
997 ;;; (`cperl-outline-level'):    New function.
998 ;;; (`cperl-highlight-variables-indiscriminately'):     New customization var.
999 ;;; (`cperl-init-faces'):       Use `cperl-highlight-variables-indiscriminately'.
1000 ;;;                             (Thanks to Sean Kamath <kamath@pogo.wv.tek.com>).
1001 ;;; (`cperl-after-block-p'):    Support CHECK and INIT.
1002 ;;; (`cperl-init-faces'):       Likewise and "our".
1003 ;;;                             (Thanks to Doug MacEachern <dougm@covalent.net>).
1004 ;;; (`cperl-short-docs'):       Likewise and "our".
1005
1006
1007 ;;;; After 4.27:
1008 ;;; (`cperl-find-pods-heres'):  Recognize \"" as a string.
1009 ;;;                             Mark whitespace and comments between q and []
1010 ;;;                               as `syntax-type' => `prestring'.
1011 ;;;                             Allow whitespace between << and "FOO".
1012 ;;; (`cperl-problems'):         Remove \"" and q [] with intervening newlines.
1013 ;;;                             Mention multiple <<EOF as unsupported.
1014 ;;; (`cperl-highlight-variables-indiscriminately'):     Doc misprint fixed.
1015 ;;; (`cperl-indent-parens-as-block'):   New configuration variable.
1016 ;;; (`cperl-calculate-indent'): Merge cases of indenting non-BLOCK groups.
1017 ;;;                             Use `cperl-indent-parens-as-block'.
1018 ;;; (`cperl-find-pods-heres'):  Test for =cut without empty line instead of
1019 ;;;                             complaining about no =cut.
1020 ;;; (`cperl-electric-pod'):     Change the REx for POD from "\n\n=" to "^\n=".
1021 ;;; (`cperl-find-pods-heres'):  Likewise.
1022 ;;; (`cperl-electric-pod'):     Change `forward-sexp' to `forward-word':
1023 ;;;                             POD could've been marked as comment already.
1024 ;;; (`cperl-unwind-to-safe'):   Unwind before start of POD too.
1025
1026 ;;;; After 4.28:
1027 ;;; (`cperl-forward-re'):       Throw an error at proper moment REx unfinished.
1028
1029 ;;;; After 4.29:
1030 ;;; (`x-color-defined-p'):      Make an extra case to peacify the warning.
1031 ;;; Toplevel:                   `defvar' to peacify the warnings.
1032 ;;; (`cperl-find-pods-heres'):  Could access `font-lock-comment-face' in -nw.
1033 ;;;;                            No -nw-compile time warnings now.
1034 ;;; (`cperl-find-tags'):        TAGS file had too short substring-to-search.
1035 ;;;                             Be less verbose in non-interactive mode
1036 ;;; (`imenu-example--create-perl-index'):       Set index-marker after name
1037 ;;; (`cperl-outline-regexp'):   New variable.
1038 ;;; (`cperl-outline-level'):    Made compatible with `cperl-outline-regexp'.
1039 ;;; (`cperl-mode'):             Made use `cperl-outline-regexp'.
1040
1041 ;;;; After 4.30:
1042 ;;; (`cperl-find-pods-heres'):  =cut the last thing, no blank line, was error.
1043 ;;; (`cperl-outline-level'):    Make start-of-file same level as `package'.
1044
1045 ;;;; After 4.31:
1046 ;;; (`cperl-electric-pod'):     `head1' and `over' electric only if empty.
1047 ;;; (`cperl-unreadable-ok'):    New variable.
1048 ;;; (`cperl-find-tags'):        Use `cperl-unreadable-ok', do not fail
1049 ;;;                             on an unreadable file
1050 ;;; (`cperl-write-tags'):       Use `cperl-unreadable-ok', do not fail
1051 ;;;                             on an unreadable directory
1052
1053 ;;;; After 4.32:
1054 ;;;  Syncronized with v1.60 from Emacs 21.3.
1055 ;;;  Mostly docstring and formatting changes, and:
1056
1057 ;;;  (`cperl-noscan-files-regexp'): Do not scan CVS subdirs
1058 ;;;  (`cperl-problems'):        Note that newer XEmacsen may syntaxify too
1059 ;;;  (`imenu-example--create-perl-index'):
1060 ;;;                             Renamed to `cperl-imenu--create-perl-index'
1061 ;;;  (`cperl-mode'):            Replace `make-variable-buffer-local' by `make-local-variable'
1062 ;;;  (`cperl-setup-tmp-buf'):   Likewise
1063 ;;;  (`cperl-fix-line-spacing'): Fix a misprint of "t" for "\t"
1064 ;;;  (`cperl-next-bad-style'):  Fix misprints in character literals
1065
1066 ;;;; After 4.33:
1067 ;;;  (`cperl-font-lock-keywords'): +etc: Aliased to perl-font-lock-keywords.
1068
1069 ;;;; After 4.34:
1070 ;;;  Further updates of whitespace and spelling w.r.t. RMS version.
1071 ;;;  (`cperl-font-lock-keywords'): +etc: Avoid warnings when aliasing.
1072 ;;;  (`cperl-mode'):            Use `normal-auto-fill-function' if present.
1073 ;;;  (`cperl-use-major-mode'):  New variable
1074 ;;;  (`cperl-can-font-lock'):   New variable; replaces `window-system'
1075 ;;;  (`cperl-tags-hier-init'):  use `display-popup-menus-p' (if present)
1076 ;;;                             to choose `x-popup-menu' vs `tmm-prompt'
1077
1078 ;;;; 4.35 has the following differences from version 1.40+ of RMS Emacs:
1079
1080 ;;; New variables `cperl-use-major-mode', `cperl-can-font-lock';
1081 ;;; `cperl-use-major-mode' is (effectively) 'cperl-mode in RMS.
1082 ;;; `cperl-under-as-char'  is nil in RMS.
1083 ;;; Minor differences in docstrings, and `cperl-non-problems'.
1084 ;;; Backward compatibility addressed: (`); (function (lambda ...)); font-lock;
1085 ;;; (:italic t bold t) vs (:slant italic :weight bold) in faces;
1086 ;;; `normal-auto-fill-function'.
1087 ;;; RMS version has wrong logic in `cperl-calculate-indent': $a = { } is
1088 ;;; wrongly indented if the closing brace is on a separate line.
1089 ;;; Different choice of ordering if's for is-x-REx and (eq (char-after b) ?\#)
1090 ;;; in `cperl-find-pods-heres'. [Cosmetic]
1091
1092 ;;;; After 4.35:
1093 ;;;  (`cperl-find-pods-heres'): If no end of HERE-doc found, mark to the end
1094 ;;;                             of buffer.  This enables recognition of end
1095 ;;;                             of HERE-doc "as one types".
1096 ;;;                             Require "\n" after trailing tag of HERE-doc.
1097 ;;;                             \( made non-quoting outside of string/comment
1098 ;;;                             (gdj-contributed).
1099 ;;;                             Likewise for \$.
1100 ;;;                             Remove `here-doc-group' text property at start
1101 ;;;                             (makes this property reliable).
1102 ;;;                             Text property `first-format-line' ==> t.
1103 ;;;                             Do not recognize $opt_s and $opt::s as s///.
1104 ;;;  (`cperl-perldoc'):         Use case-sensitive search (contributed).
1105 ;;;  (`cperl-fix-line-spacing'): Allow "_" in $vars of foreach etc. when
1106 ;;;                             underscore isn't a word char (gdj-contributed).
1107 ;;;  (`defun-prompt-regexp'):   Allow prototypes.
1108 ;;;  (`cperl-vc-header-alist'): Extract numeric version from the Id.
1109 ;;;  Toplevel:                  Put toggle-autohelp into the mode menu.
1110 ;;;                             Better docs for toggle/set/unset autohelp.
1111 ;;;  (`cperl-electric-backspace-untabify'): New customization variable
1112 ;;;  (`cperl-after-expr-p'):    Works after here-docs, formats, and PODs too
1113 ;;;                             (affects many electric constructs).
1114 ;;;  (`cperl-calculate-indent'): Takes into account `first-format-line' ==>
1115 ;;;                             works after format.
1116 ;;;  (`cperl-short-docs'):      Make it work with ... too.
1117 ;;;                             "array context" ==> "list context"
1118 ;;;  (`cperl-electric-keyword'): make $if (etc: "$@%&*") non-electric
1119 ;;;                             '(' after keyword would insert a doubled paren
1120 ;;;  (`cperl-electric-paren'):  documented affected by `cperl-electric-parens'
1121 ;;;  (`cperl-electric-rparen'): Likewise
1122 ;;;  (`cperl-build-manpage'):   New function by Nick Roberts
1123 ;;;  (`cperl-perldoc'):         Make it work in XEmacs too
1124
1125 ;;;; After 4.36:
1126 ;;;  (`cperl-find-pods-heres'): Recognize s => 1 and {s} (as a key or varname),
1127 ;;;                             { s:: } and { s::bar::baz } as varnames.
1128 ;;;  (`cperl-after-expr-p'):    Updates syntaxification before checks
1129 ;;;  (`cperl-calculate-indent'): Likewise
1130 ;;;                             Fix wrong indent of blocks starting with POD
1131 ;;;  (`cperl-after-block-p'):   Optional argument for checking for a pre-block
1132 ;;;                             Recognize `continue' blocks too.
1133 ;;;  (`cperl-electric-brace'):  use `cperl-after-block-p' for detection;
1134 ;;;                             Now works for else/continue/sub blocks
1135 ;;;  (`cperl-short-docs'):      Minor edits; make messages fit 80-column screen
1136
1137 ;;; Code:
1138
1139 \f
1140 (if (fboundp 'eval-when-compile)
1141     (eval-when-compile
1142       (condition-case nil
1143           (require 'custom)
1144         (error nil))
1145       (condition-case nil
1146           (require 'man)
1147         (error nil))
1148       (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1149       (defvar cperl-can-font-lock
1150         (or cperl-xemacs-p
1151             (and (boundp 'emacs-major-version)
1152                  (or window-system
1153                      (> emacs-major-version 20)))))
1154       (if cperl-can-font-lock
1155           (require 'font-lock))
1156       (defvar msb-menu-cond)
1157       (defvar gud-perldb-history)
1158       (defvar font-lock-background-mode) ; not in Emacs
1159       (defvar font-lock-display-type)   ; ditto
1160       (or (fboundp 'defgroup)
1161           (defmacro defgroup (name val doc &rest arr)
1162             nil))
1163       (or (fboundp 'custom-declare-variable)
1164           (defmacro defcustom (name val doc &rest arr)
1165             (` (defvar (, name) (, val) (, doc)))))
1166       (or (and (fboundp 'custom-declare-variable)
1167                (string< "19.31" emacs-version)) ;  Checked with 19.30: defface does not work
1168           (defmacro defface (&rest arr)
1169             nil))
1170       ;; Avoid warning (tmp definitions)
1171       (or (fboundp 'x-color-defined-p)
1172           (defmacro x-color-defined-p (col)
1173             (cond ((fboundp 'color-defined-p) (` (color-defined-p (, col))))
1174                   ;; XEmacs >= 19.12
1175                   ((fboundp 'valid-color-name-p) (` (valid-color-name-p (, col))))
1176                   ;; XEmacs 19.11
1177                   ((fboundp 'x-valid-color-name-p) (` (x-valid-color-name-p (, col))))
1178                   (t '(error "Cannot implement color-defined-p")))))
1179       (defmacro cperl-is-face (arg)     ; Takes quoted arg
1180         (cond ((fboundp 'find-face)
1181                (` (find-face (, arg))))
1182               (;;(and (fboundp 'face-list)
1183                ;;       (face-list))
1184                (fboundp 'face-list)
1185                (` (member (, arg) (and (fboundp 'face-list)
1186                                        (face-list)))))
1187               (t
1188                (` (boundp (, arg))))))
1189       (defmacro cperl-make-face (arg descr) ; Takes unquoted arg
1190         (cond ((fboundp 'make-face)
1191                (` (make-face (quote (, arg)))))
1192               (t
1193                (` (defvar (, arg) (quote (, arg)) (, descr))))))
1194       (defmacro cperl-force-face (arg descr) ; Takes unquoted arg
1195         (` (progn
1196              (or (cperl-is-face (quote (, arg)))
1197                  (cperl-make-face (, arg) (, descr)))
1198              (or (boundp (quote (, arg))) ; We use unquoted variants too
1199                  (defvar (, arg) (quote (, arg)) (, descr))))))
1200       (if cperl-xemacs-p
1201           (defmacro cperl-etags-snarf-tag (file line)
1202             (` (progn
1203                  (beginning-of-line 2)
1204                  (list (, file) (, line)))))
1205         (defmacro cperl-etags-snarf-tag (file line)
1206           (` (etags-snarf-tag))))
1207       (if cperl-xemacs-p
1208           (defmacro cperl-etags-goto-tag-location (elt)
1209             (`;;(progn
1210              ;; (switch-to-buffer (get-file-buffer (elt (, elt) 0)))
1211              ;; (set-buffer (get-file-buffer (elt (, elt) 0)))
1212              ;; Probably will not work due to some save-excursion???
1213              ;; Or save-file-position?
1214              ;; (message "Did I get to line %s?" (elt (, elt) 1))
1215              (goto-line (string-to-int (elt (, elt) 1)))))
1216         ;;)
1217         (defmacro cperl-etags-goto-tag-location (elt)
1218           (` (etags-goto-tag-location (, elt)))))))
1219
1220 (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1221
1222 (defvar cperl-can-font-lock
1223   (or cperl-xemacs-p
1224       (and (boundp 'emacs-major-version)
1225            (or window-system
1226                (> emacs-major-version 20)))))
1227
1228 (condition-case nil
1229     (require 'custom)
1230   (error nil))                          ; Already fixed by eval-when-compile
1231
1232 (defun cperl-choose-color (&rest list)
1233   (let (answer)
1234     (while list
1235       (or answer
1236           (if (or (x-color-defined-p (car list))
1237                   (null (cdr list)))
1238               (setq answer (car list))))
1239       (setq list (cdr list)))
1240     answer))
1241
1242 \f
1243 (defgroup cperl nil
1244   "Major mode for editing Perl code."
1245   :prefix "cperl-"
1246   :group 'languages)
1247
1248 (defgroup cperl-indentation-details nil
1249   "Indentation."
1250   :prefix "cperl-"
1251   :group 'cperl)
1252
1253 (defgroup cperl-affected-by-hairy nil
1254   "Variables affected by `cperl-hairy'."
1255   :prefix "cperl-"
1256   :group 'cperl)
1257
1258 (defgroup cperl-autoinsert-details nil
1259   "Auto-insert tuneup."
1260   :prefix "cperl-"
1261   :group 'cperl)
1262
1263 (defgroup cperl-faces nil
1264   "Fontification colors."
1265   :prefix "cperl-"
1266   :group 'cperl)
1267
1268 (defgroup cperl-speed nil
1269   "Speed vs. validity tuneup."
1270   :prefix "cperl-"
1271   :group 'cperl)
1272
1273 (defgroup cperl-help-system nil
1274   "Help system tuneup."
1275   :prefix "cperl-"
1276   :group 'cperl)
1277
1278 \f
1279 (defcustom cperl-extra-newline-before-brace nil
1280   "*Non-nil means that if, elsif, while, until, else, for, foreach
1281 and do constructs look like:
1282
1283         if ()
1284         {
1285         }
1286
1287 instead of:
1288
1289         if () {
1290         }"
1291   :type 'boolean
1292   :group 'cperl-autoinsert-details)
1293
1294 (defcustom cperl-extra-newline-before-brace-multiline
1295   cperl-extra-newline-before-brace
1296   "*Non-nil means the same as `cperl-extra-newline-before-brace', but
1297 for constructs with multiline if/unless/while/until/for/foreach condition."
1298   :type 'boolean
1299   :group 'cperl-autoinsert-details)
1300
1301 (defcustom cperl-indent-level 2
1302   "*Indentation of CPerl statements with respect to containing block."
1303   :type 'integer
1304   :group 'cperl-indentation-details)
1305
1306 (defcustom cperl-lineup-step nil
1307   "*`cperl-lineup' will always lineup at multiple of this number.
1308 If nil, the value of `cperl-indent-level' will be used."
1309   :type '(choice (const nil) integer)
1310   :group 'cperl-indentation-details)
1311
1312 (defcustom cperl-brace-imaginary-offset 0
1313   "*Imagined indentation of a Perl open brace that actually follows a statement.
1314 An open brace following other text is treated as if it were this far
1315 to the right of the start of its line."
1316   :type 'integer
1317   :group 'cperl-indentation-details)
1318
1319 (defcustom cperl-brace-offset 0
1320   "*Extra indentation for braces, compared with other text in same context."
1321   :type 'integer
1322   :group 'cperl-indentation-details)
1323 (defcustom cperl-label-offset -2
1324   "*Offset of CPerl label lines relative to usual indentation."
1325   :type 'integer
1326   :group 'cperl-indentation-details)
1327 (defcustom cperl-min-label-indent 1
1328   "*Minimal offset of CPerl label lines."
1329   :type 'integer
1330   :group 'cperl-indentation-details)
1331 (defcustom cperl-continued-statement-offset 2
1332   "*Extra indent for lines not starting new statements."
1333   :type 'integer
1334   :group 'cperl-indentation-details)
1335 (defcustom cperl-continued-brace-offset 0
1336   "*Extra indent for substatements that start with open-braces.
1337 This is in addition to cperl-continued-statement-offset."
1338   :type 'integer
1339   :group 'cperl-indentation-details)
1340 (defcustom cperl-close-paren-offset -1
1341   "*Extra indent for substatements that start with close-parenthesis."
1342   :type 'integer
1343   :group 'cperl-indentation-details)
1344
1345 (defcustom cperl-auto-newline nil
1346   "*Non-nil means automatically newline before and after braces,
1347 and after colons and semicolons, inserted in CPerl code.  The following
1348 \\[cperl-electric-backspace] will remove the inserted whitespace.
1349 Insertion after colons requires both this variable and
1350 `cperl-auto-newline-after-colon' set."
1351   :type 'boolean
1352   :group 'cperl-autoinsert-details)
1353
1354 (defcustom cperl-autoindent-on-semi nil
1355   "*Non-nil means automatically indent after insertion of (semi)colon.
1356 Active if `cperl-auto-newline' is false."
1357   :type 'boolean
1358   :group 'cperl-autoinsert-details)
1359
1360 (defcustom cperl-auto-newline-after-colon nil
1361   "*Non-nil means automatically newline even after colons.
1362 Subject to `cperl-auto-newline' setting."
1363   :type 'boolean
1364   :group 'cperl-autoinsert-details)
1365
1366 (defcustom cperl-tab-always-indent t
1367   "*Non-nil means TAB in CPerl mode should always reindent the current line,
1368 regardless of where in the line point is when the TAB command is used."
1369   :type 'boolean
1370   :group 'cperl-indentation-details)
1371
1372 (defcustom cperl-font-lock nil
1373   "*Non-nil (and non-null) means CPerl buffers will use `font-lock-mode'.
1374 Can be overwritten by `cperl-hairy' if nil."
1375   :type '(choice (const null) boolean)
1376   :group 'cperl-affected-by-hairy)
1377
1378 (defcustom cperl-electric-lbrace-space nil
1379   "*Non-nil (and non-null) means { after $ should be preceded by ` '.
1380 Can be overwritten by `cperl-hairy' if nil."
1381   :type '(choice (const null) boolean)
1382   :group 'cperl-affected-by-hairy)
1383
1384 (defcustom cperl-electric-parens-string "({[]})<"
1385   "*String of parentheses that should be electric in CPerl.
1386 Closing ones are electric only if the region is highlighted."
1387   :type 'string
1388   :group 'cperl-affected-by-hairy)
1389
1390 (defcustom cperl-electric-parens nil
1391   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
1392 Can be overwritten by `cperl-hairy' if nil."
1393   :type '(choice (const null) boolean)
1394   :group 'cperl-affected-by-hairy)
1395
1396 (defvar zmacs-regions)                  ; Avoid warning
1397
1398 (defcustom cperl-electric-parens-mark
1399   (and window-system
1400        (or (and (boundp 'transient-mark-mode) ; For Emacs
1401                 transient-mark-mode)
1402            (and (boundp 'zmacs-regions) ; For XEmacs
1403                 zmacs-regions)))
1404   "*Not-nil means that electric parens look for active mark.
1405 Default is yes if there is visual feedback on mark."
1406   :type 'boolean
1407   :group 'cperl-autoinsert-details)
1408
1409 (defcustom cperl-electric-linefeed nil
1410   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
1411 In any case these two mean plain and hairy linefeeds together.
1412 Can be overwritten by `cperl-hairy' if nil."
1413   :type '(choice (const null) boolean)
1414   :group 'cperl-affected-by-hairy)
1415
1416 (defcustom cperl-electric-keywords nil
1417   "*Not-nil (and non-null) means keywords are electric in CPerl.
1418 Can be overwritten by `cperl-hairy' if nil."
1419   :type '(choice (const null) boolean)
1420   :group 'cperl-affected-by-hairy)
1421
1422 (defcustom cperl-electric-backspace-untabify t
1423   "*Not-nil means electric-backspace will untabify in CPerl."
1424   :type 'boolean
1425   :group 'cperl-autoinsert-details)
1426
1427 (defcustom cperl-hairy nil
1428   "*Not-nil means most of the bells and whistles are enabled in CPerl.
1429 Affects: `cperl-font-lock', `cperl-electric-lbrace-space',
1430 `cperl-electric-parens', `cperl-electric-linefeed', `cperl-electric-keywords',
1431 `cperl-info-on-command-no-prompt', `cperl-clobber-lisp-bindings',
1432 `cperl-lazy-help-time'."
1433   :type 'boolean
1434   :group 'cperl-affected-by-hairy)
1435
1436 (defcustom cperl-comment-column 32
1437   "*Column to put comments in CPerl (use \\[cperl-indent] to lineup with code)."
1438   :type 'integer
1439   :group 'cperl-indentation-details)
1440
1441 (defcustom cperl-vc-header-alist '((SCCS "($sccs) = ('%W\%' =~ /(\\d+(\\.\\d+)+)/) ;")
1442                                    (RCS "($rcs) = (' $Id\$ ' =~ /(\\d+(\\.\\d+)+)/) ;"))
1443   "*What to use as `vc-header-alist' in CPerl."
1444   :type '(repeat (list symbol string))
1445   :group 'cperl)
1446
1447 (defcustom cperl-clobber-mode-lists
1448   (not
1449    (and
1450     (boundp 'interpreter-mode-alist)
1451     (assoc "miniperl" interpreter-mode-alist)
1452     (assoc "\\.\\([pP][Llm]\\|al\\)$" auto-mode-alist)))
1453   "*Whether to install us into `interpreter-' and `extension' mode lists."
1454   :type 'boolean
1455   :group 'cperl)
1456
1457 (defcustom cperl-info-on-command-no-prompt nil
1458   "*Not-nil (and non-null) means not to prompt on C-h f.
1459 The opposite behaviour is always available if prefixed with C-c.
1460 Can be overwritten by `cperl-hairy' if nil."
1461   :type '(choice (const null) boolean)
1462   :group 'cperl-affected-by-hairy)
1463
1464 (defcustom cperl-clobber-lisp-bindings nil
1465   "*Not-nil (and non-null) means not overwrite C-h f.
1466 The function is available on \\[cperl-info-on-command], \\[cperl-get-help].
1467 Can be overwritten by `cperl-hairy' if nil."
1468   :type '(choice (const null) boolean)
1469   :group 'cperl-affected-by-hairy)
1470
1471 (defcustom cperl-lazy-help-time nil
1472   "*Not-nil (and non-null) means to show lazy help after given idle time.
1473 Can be overwritten by `cperl-hairy' to be 5 sec if nil."
1474   :type '(choice (const null) (const nil) integer)
1475   :group 'cperl-affected-by-hairy)
1476
1477 (defcustom cperl-pod-face 'font-lock-comment-face
1478   "*The result of evaluation of this expression is used for POD highlighting."
1479   :type 'face
1480   :group 'cperl-faces)
1481
1482 (defcustom cperl-pod-head-face 'font-lock-variable-name-face
1483   "*The result of evaluation of this expression is used for POD highlighting.
1484 Font for POD headers."
1485   :type 'face
1486   :group 'cperl-faces)
1487
1488 (defcustom cperl-here-face 'font-lock-string-face
1489   "*The result of evaluation of this expression is used for here-docs highlighting."
1490   :type 'face
1491   :group 'cperl-faces)
1492
1493 (defcustom cperl-invalid-face ''underline ; later evaluated by `font-lock'
1494   "*The result of evaluation of this expression highlights trailing whitespace."
1495   :type 'face
1496   :group 'cperl-faces)
1497
1498 (defcustom cperl-pod-here-fontify '(featurep 'font-lock)
1499   "*Not-nil after evaluation means to highlight POD and here-docs sections."
1500   :type 'boolean
1501   :group 'cperl-faces)
1502
1503 (defcustom cperl-fontify-m-as-s t
1504   "*Not-nil means highlight 1arg regular expressions operators same as 2arg."
1505   :type 'boolean
1506   :group 'cperl-faces)
1507
1508 (defcustom cperl-highlight-variables-indiscriminately nil
1509   "*Non-nil means perform additional highlighting on variables.
1510 Currently only changes how scalar variables are highlighted.
1511 Note that that variable is only read at initialization time for
1512 the variable `perl-font-lock-keywords-2', so changing it after you've
1513 entered CPerl mode the first time will have no effect."
1514   :type 'boolean
1515   :group 'cperl)
1516
1517 (defcustom cperl-pod-here-scan t
1518   "*Not-nil means look for POD and here-docs sections during startup.
1519 You can always make lookup from menu or using \\[cperl-find-pods-heres]."
1520   :type 'boolean
1521   :group 'cperl-speed)
1522
1523 (defcustom cperl-regexp-scan t
1524   "*Not-nil means make marking of regular expression more thorough.
1525 Effective only with `cperl-pod-here-scan'.  Not implemented yet."
1526   :type 'boolean
1527   :group 'cperl-speed)
1528
1529 (defcustom cperl-imenu-addback nil
1530   "*Not-nil means add backreferences to generated `imenu's.
1531 May require patched `imenu' and `imenu-go'.  Obsolete."
1532   :type 'boolean
1533   :group 'cperl-help-system)
1534
1535 (defcustom cperl-max-help-size 66
1536   "*Non-nil means shrink-wrapping of info-buffer allowed up to these percents."
1537   :type '(choice integer (const nil))
1538   :group 'cperl-help-system)
1539
1540 (defcustom cperl-shrink-wrap-info-frame t
1541   "*Non-nil means shrink-wrapping of info-buffer-frame allowed."
1542   :type 'boolean
1543   :group 'cperl-help-system)
1544
1545 (defcustom cperl-info-page "perl"
1546   "*Name of the info page containing perl docs.
1547 Older version of this page was called `perl5', newer `perl'."
1548   :type 'string
1549   :group 'cperl-help-system)
1550
1551 (defcustom cperl-use-syntax-table-text-property
1552   (boundp 'parse-sexp-lookup-properties)
1553   "*Non-nil means CPerl sets up and uses `syntax-table' text property."
1554   :type 'boolean
1555   :group 'cperl-speed)
1556
1557 (defcustom cperl-use-syntax-table-text-property-for-tags
1558   cperl-use-syntax-table-text-property
1559   "*Non-nil means: set up and use `syntax-table' text property generating TAGS."
1560   :type 'boolean
1561   :group 'cperl-speed)
1562
1563 (defcustom cperl-scan-files-regexp "\\.\\([pP][Llm]\\|xs\\)$"
1564   "*Regexp to match files to scan when generating TAGS."
1565   :type 'regexp
1566   :group 'cperl)
1567
1568 (defcustom cperl-noscan-files-regexp
1569   "/\\(\\.\\.?\\|SCCS\\|RCS\\|CVS\\|blib\\)$"
1570   "*Regexp to match files/dirs to skip when generating TAGS."
1571   :type 'regexp
1572   :group 'cperl)
1573
1574 (defcustom cperl-regexp-indent-step nil
1575   "*Indentation used when beautifying regexps.
1576 If nil, the value of `cperl-indent-level' will be used."
1577   :type '(choice integer (const nil))
1578   :group 'cperl-indentation-details)
1579
1580 (defcustom cperl-indent-left-aligned-comments t
1581   "*Non-nil means that the comment starting in leftmost column should indent."
1582   :type 'boolean
1583   :group 'cperl-indentation-details)
1584
1585 (defcustom cperl-under-as-char t
1586   "*Non-nil means that the _ (underline) should be treated as word char."
1587   :type 'boolean
1588   :group 'cperl)
1589
1590 (defcustom cperl-extra-perl-args ""
1591   "*Extra arguments to use when starting Perl.
1592 Currently used with `cperl-check-syntax' only."
1593   :type 'string
1594   :group 'cperl)
1595
1596 (defcustom cperl-message-electric-keyword t
1597   "*Non-nil means that the `cperl-electric-keyword' prints a help message."
1598   :type 'boolean
1599   :group 'cperl-help-system)
1600
1601 (defcustom cperl-indent-region-fix-constructs 1
1602   "*Amount of space to insert between `}' and `else' or `elsif'
1603 in `cperl-indent-region'.  Set to nil to leave as is.  Values other
1604 than 1 and nil will probably not work."
1605   :type '(choice (const nil) (const 1))
1606   :group 'cperl-indentation-details)
1607
1608 (defcustom cperl-break-one-line-blocks-when-indent t
1609   "*Non-nil means that one-line if/unless/while/until/for/foreach BLOCKs
1610 need to be reformatted into multiline ones when indenting a region."
1611   :type 'boolean
1612   :group 'cperl-indentation-details)
1613
1614 (defcustom cperl-fix-hanging-brace-when-indent t
1615   "*Non-nil means that BLOCK-end `}' may be put on a separate line
1616 when indenting a region.
1617 Braces followed by else/elsif/while/until are excepted."
1618   :type 'boolean
1619   :group 'cperl-indentation-details)
1620
1621 (defcustom cperl-merge-trailing-else t
1622   "*Non-nil means that BLOCK-end `}' followed by else/elsif/continue
1623 may be merged to be on the same line when indenting a region."
1624   :type 'boolean
1625   :group 'cperl-indentation-details)
1626
1627 (defcustom cperl-indent-parens-as-block nil
1628   "*Non-nil means that non-block ()-, {}- and []-groups are indented as blocks,
1629 but for trailing \",\" inside the group, which won't increase indentation.
1630 One should tune up `cperl-close-paren-offset' as well."
1631   :type 'boolean
1632   :group 'cperl-indentation-details)
1633
1634 (defcustom cperl-syntaxify-by-font-lock
1635   (and cperl-can-font-lock
1636        (boundp 'parse-sexp-lookup-properties))
1637   "*Non-nil means that CPerl uses `font-lock's routines for syntaxification."
1638   :type '(choice (const message) boolean)
1639   :group 'cperl-speed)
1640
1641 (defcustom cperl-syntaxify-unwind
1642   t
1643   "*Non-nil means that CPerl unwinds to a start of a long construction
1644 when syntaxifying a chunk of buffer."
1645   :type 'boolean
1646   :group 'cperl-speed)
1647
1648 (defcustom cperl-ps-print-face-properties
1649   '((font-lock-keyword-face             nil nil         bold shadow)
1650     (font-lock-variable-name-face       nil nil         bold)
1651     (font-lock-function-name-face       nil nil         bold italic box)
1652     (font-lock-constant-face            nil "LightGray" bold)
1653     (cperl-array-face                   nil "LightGray" bold underline)
1654     (cperl-hash-face                    nil "LightGray" bold italic underline)
1655     (font-lock-comment-face             nil "LightGray" italic)
1656     (font-lock-string-face              nil nil         italic underline)
1657     (cperl-nonoverridable-face          nil nil         italic underline)
1658     (font-lock-type-face                nil nil         underline)
1659     (underline                          nil "LightGray" strikeout))
1660   "List given as an argument to `ps-extend-face-list' in `cperl-ps-print'."
1661   :type '(repeat (cons symbol
1662                        (cons (choice (const nil) string)
1663                              (cons (choice (const nil) string)
1664                                    (repeat symbol)))))
1665   :group 'cperl-faces)
1666
1667 (if cperl-can-font-lock
1668     (progn
1669       (defvar cperl-dark-background
1670         (cperl-choose-color "navy" "os2blue" "darkgreen"))
1671       (defvar cperl-dark-foreground
1672         (cperl-choose-color "orchid1" "orange"))
1673
1674       (defface cperl-nonoverridable-face
1675         (` ((((class grayscale) (background light))
1676              (:background "Gray90" :italic t :underline t))
1677             (((class grayscale) (background dark))
1678              (:foreground "Gray80" :italic t :underline t :bold t))
1679             (((class color) (background light))
1680              (:foreground "chartreuse3"))
1681             (((class color) (background dark))
1682              (:foreground (, cperl-dark-foreground)))
1683             (t (:bold t :underline t))))
1684         "Font Lock mode face used to highlight array names."
1685         :group 'cperl-faces)
1686
1687       (defface cperl-array-face
1688         (` ((((class grayscale) (background light))
1689              (:background "Gray90" :bold t))
1690             (((class grayscale) (background dark))
1691              (:foreground "Gray80" :bold t))
1692             (((class color) (background light))
1693              (:foreground "Blue" :background "lightyellow2" :bold t))
1694             (((class color) (background dark))
1695              (:foreground "yellow" :background (, cperl-dark-background) :bold t))
1696             (t (:bold t))))
1697         "Font Lock mode face used to highlight array names."
1698         :group 'cperl-faces)
1699
1700       (defface cperl-hash-face
1701         (` ((((class grayscale) (background light))
1702              (:background "Gray90" :bold t :italic t))
1703             (((class grayscale) (background dark))
1704              (:foreground "Gray80" :bold t :italic t))
1705             (((class color) (background light))
1706              (:foreground "Red" :background "lightyellow2" :bold t :italic t))
1707             (((class color) (background dark))
1708              (:foreground "Red" :background (, cperl-dark-background) :bold t :italic t))
1709             (t (:bold t :italic t))))
1710         "Font Lock mode face used to highlight hash names."
1711         :group 'cperl-faces)))
1712
1713 \f
1714
1715 ;;; Short extra-docs.
1716
1717 (defvar cperl-tips 'please-ignore-this-line
1718   "Get maybe newer version of this package from
1719   ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
1720 and/or
1721   ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
1722 Subdirectory `cperl-mode' may contain yet newer development releases and/or
1723 patches to related files.
1724
1725 For best results apply to an older Emacs the patches from
1726   ftp://ftp.math.ohio-state.edu/pub/users/ilya/cperl-mode/patches
1727 \(this upgrades syntax-parsing abilities of RMS Emaxen v19.34 and 
1728 v20.2 up to the level of RMS Emacs v20.3 - a must for a good Perl
1729 mode.)  As of beginning of 2003, XEmacs may provide a similar ability.
1730
1731 Get support packages choose-color.el (or font-lock-extra.el before
1732 19.30), imenu-go.el from the same place.  \(Look for other files there
1733 too... ;-).  Get a patch for imenu.el in 19.29.  Note that for 19.30 and
1734 later you should use choose-color.el *instead* of font-lock-extra.el
1735 \(and you will not get smart highlighting in C :-().
1736
1737 Note that to enable Compile choices in the menu you need to install
1738 mode-compile.el.
1739
1740 If your Emacs does not default to `cperl-mode' on Perl files, and you
1741 want it to: put the following into your .emacs file:
1742
1743   (autoload 'perl-mode \"cperl-mode\" \"alternate mode for editing Perl programs\" t)
1744
1745 or
1746
1747   (defalias 'perl-mode 'cperl-mode)
1748
1749 Get perl5-info from
1750   $CPAN/doc/manual/info/perl-info.tar.gz
1751 older version was on
1752   http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz
1753
1754 If you use imenu-go, run imenu on perl5-info buffer (you can do it
1755 from Perl menu).  If many files are related, generate TAGS files from
1756 Tools/Tags submenu in Perl menu.
1757
1758 If some class structure is too complicated, use Tools/Hierarchy-view
1759 from Perl menu, or hierarchic view of imenu.  The second one uses the
1760 current buffer only, the first one requires generation of TAGS from
1761 Perl/Tools/Tags menu beforehand.
1762
1763 Run Perl/Tools/Insert-spaces-if-needed to fix your lazy typing.
1764
1765 Switch auto-help on/off with Perl/Tools/Auto-help.
1766
1767 Though with contemporary Emaxen CPerl mode should maintain the correct
1768 parsing of Perl even when editing, sometimes it may be lost.  Fix this by
1769
1770   M-x norm RET
1771
1772 or
1773
1774   \\[normal-mode]
1775
1776 In cases of more severe confusion sometimes it is helpful to do
1777
1778   M-x load-l RET cperl-mode RET
1779   M-x norm RET
1780
1781 or
1782
1783   \\[load-library] cperl-mode RET
1784   \\[normal-mode]
1785
1786 Before reporting (non-)problems look in the problem section of online
1787 micro-docs on what I know about CPerl problems.")
1788
1789 (defvar cperl-problems 'please-ignore-this-line
1790   "Description of problems in CPerl mode.
1791 Some faces will not be shown on some versions of Emacs unless you
1792 install choose-color.el, available from
1793    ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs/
1794
1795 `fill-paragraph' on a comment may leave the point behind the
1796 paragraph.  Parsing of lines with several <<EOF is not implemented
1797 yet.
1798
1799 Emacs had a _very_ restricted syntax parsing engine until RMS's Emacs
1800 20.1.  Most problems below are corrected starting from this version of
1801 Emacs, and all of them should be fixed in RMS's version 20.3.  (Or apply
1802 patches to Emacs 19.33/34 - see tips.)  XEmacs was very backward in
1803 this respect (until 2003).
1804
1805 Note that even with newer Emacsen in some very rare cases the details
1806 of interaction of `font-lock' and syntaxification may be not cleaned
1807 up yet.  You may get slightly different colors basing on the order of
1808 fontification and syntaxification.  Say, the initial faces is correct,
1809 but editing the buffer breaks this.
1810
1811 Even with older Emacsen CPerl mode tries to corrects some Emacs
1812 misunderstandings, however, for efficiency reasons the degree of
1813 correction is different for different operations.  The partially
1814 corrected problems are: POD sections, here-documents, regexps.  The
1815 operations are: highlighting, indentation, electric keywords, electric
1816 braces.
1817
1818 This may be confusing, since the regexp s#//#/#\; may be highlighted
1819 as a comment, but it will be recognized as a regexp by the indentation
1820 code.  Or the opposite case, when a POD section is highlighted, but
1821 may break the indentation of the following code (though indentation
1822 should work if the balance of delimiters is not broken by POD).
1823
1824 The main trick (to make $ a \"backslash\") makes constructions like
1825 ${aaa} look like unbalanced braces.  The only trick I can think of is
1826 to insert it as $ {aaa} (legal in perl5, not in perl4).
1827
1828 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
1829 as /($|\\s)/.  Note that such a transposition is not always possible.
1830
1831 The solution is to upgrade your Emacs or patch an older one.  Note
1832 that RMS's 20.2 has some bugs related to `syntax-table' text
1833 properties.  Patches are available on the main CPerl download site,
1834 and on CPAN.
1835
1836 If these bugs cannot be fixed on your machine (say, you have an inferior
1837 environment and cannot recompile), you may still disable all the fancy stuff
1838 via `cperl-use-syntax-table-text-property'.")
1839
1840 (defvar cperl-non-problems 'please-ignore-this-line
1841 "As you know from `problems' section, Perl syntax is too hard for CPerl on 
1842 older Emacsen.  Here is what you can do if you cannot upgrade, or if
1843 you want to switch off these capabilities on RMS Emacs 20.2 (+patches) or 20.3
1844 or better.  Please skip this docs if you run a capable Emacs already.
1845
1846 Most of the time, if you write your own code, you may find an equivalent
1847 \(and almost as readable) expression (what is discussed below is usually
1848 not relevant on newer Emacsen, since they can do it automatically).
1849
1850 Try to help CPerl: add comments with embedded quotes to fix CPerl
1851 misunderstandings about the end of quotation:
1852
1853 $a='500$';      # ';
1854
1855 You won't need it too often.  The reason: $ \"quotes\" the following
1856 character (this saves a life a lot of times in CPerl), thus due to
1857 Emacs parsing rules it does not consider tick (i.e., ' ) after a
1858 dollar as a closing one, but as a usual character.  This is usually
1859 correct, but not in the above context.
1860
1861 Even with older Emacsen the indentation code is pretty wise.  The only
1862 drawback is that it relied on Emacs parsing to find matching
1863 parentheses.  And Emacs *could not* match parentheses in Perl 100%
1864 correctly.  So
1865         1 if s#//#/#;
1866 would not break indentation, but
1867         1 if ( s#//#/# );
1868 would.  Upgrade.
1869
1870 By similar reasons
1871         s\"abc\"def\";
1872 could confuse CPerl a lot.
1873
1874 If you still get wrong indentation in situation that you think the
1875 code should be able to parse, try:
1876
1877 a) Check what Emacs thinks about balance of your parentheses.
1878 b) Supply the code to me (IZ).
1879
1880 Pods were treated _very_ rudimentally.  Here-documents were not
1881 treated at all (except highlighting and inhibiting indentation).  Upgrade.
1882
1883 To speed up coloring the following compromises exist:
1884    a) sub in $mypackage::sub may be highlighted.
1885    b) -z in [a-z] may be highlighted.
1886    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
1887
1888
1889 Imenu in 19.31 is broken.  Set `imenu-use-keymap-menu' to t, and remove
1890 `car' before `imenu-choose-buffer-index' in `imenu'.
1891 `imenu-add-to-menubar' in 20.2 is broken.  
1892 A lot of things on XEmacs may be broken too, judging by bug reports I
1893 receive.  Note that some releases of XEmacs are better than the others
1894 as far as bugs reports I see are concerned.")
1895
1896 (defvar cperl-praise 'please-ignore-this-line
1897   "Advantages of CPerl mode.
1898
1899 0) It uses the newest `syntax-table' property ;-);
1900
1901 1) It does 99% of Perl syntax correct (as opposed to 80-90% in Perl
1902 mode - but the latter number may have improved too in last years) even
1903 with old Emaxen which do not support `syntax-table' property.
1904
1905 When using `syntax-table' property for syntax assist hints, it should
1906 handle 99.995% of lines correct - or somesuch.  It automatically
1907 updates syntax assist hints when you edit your script.
1908
1909 2) It is generally believed to be \"the most user-friendly Emacs
1910 package\" whatever it may mean (I doubt that the people who say similar
1911 things tried _all_ the rest of Emacs ;-), but this was not a lonely
1912 voice);
1913
1914 3) Everything is customizable, one-by-one or in a big sweep;
1915
1916 4) It has many easily-accessable \"tools\":
1917         a) Can run program, check syntax, start debugger;
1918         b) Can lineup vertically \"middles\" of rows, like `=' in
1919                 a  = b;
1920                 cc = d;
1921         c) Can insert spaces where this impoves readability (in one
1922                 interactive sweep over the buffer);
1923         d) Has support for imenu, including:
1924                 1) Separate unordered list of \"interesting places\";
1925                 2) Separate TOC of POD sections;
1926                 3) Separate list of packages;
1927                 4) Hierarchical view of methods in (sub)packages;
1928                 5) and functions (by the full name - with package);
1929         e) Has an interface to INFO docs for Perl; The interface is
1930                 very flexible, including shrink-wrapping of
1931                 documentation buffer/frame;
1932         f) Has a builtin list of one-line explanations for perl constructs.
1933         g) Can show these explanations if you stay long enough at the
1934                 corresponding place (or on demand);
1935         h) Has an enhanced fontification (using 3 or 4 additional faces
1936                 comparing to font-lock - basically, different
1937                 namespaces in Perl have different colors);
1938         i) Can construct TAGS basing on its knowledge of Perl syntax,
1939                 the standard menu has 6 different way to generate
1940                 TAGS (if \"by directory\", .xs files - with C-language
1941                 bindings - are included in the scan);
1942         j) Can build a hierarchical view of classes (via imenu) basing
1943                 on generated TAGS file;
1944         k) Has electric parentheses, electric newlines, uses Abbrev
1945                 for electric logical constructs
1946                         while () {}
1947                 with different styles of expansion (context sensitive
1948                 to be not so bothering).  Electric parentheses behave
1949                 \"as they should\" in a presence of a visible region.
1950         l) Changes msb.el \"on the fly\" to insert a group \"Perl files\";
1951         m) Can convert from
1952                 if (A) { B }
1953            to
1954                 B if A;
1955
1956         n) Highlights (by user-choice) either 3-delimiters constructs
1957            (such as tr/a/b/), or regular expressions and `y/tr';
1958         o) Highlights trailing whitespace;
1959         p) Is able to manipulate Perl Regular Expressions to ease
1960            conversion to a more readable form.
1961
1962 5) The indentation engine was very smart, but most of tricks may be
1963 not needed anymore with the support for `syntax-table' property.  Has
1964 progress indicator for indentation (with `imenu' loaded).
1965
1966 6) Indent-region improves inline-comments as well; also corrects
1967 whitespace *inside* the conditional/loop constructs.
1968
1969 7) Fill-paragraph correctly handles multi-line comments;
1970
1971 8) Can switch to different indentation styles by one command, and restore
1972 the settings present before the switch.
1973
1974 9) When doing indentation of control constructs, may correct
1975 line-breaks/spacing between elements of the construct.
1976
1977 10) Uses a linear-time algorith for indentation of regions (on Emaxen with
1978 capable syntax engines).")
1979
1980 (defvar cperl-speed 'please-ignore-this-line
1981   "This is an incomplete compendium of what is available in other parts
1982 of CPerl documentation.  (Please inform me if I skept anything.)
1983
1984 There is a perception that CPerl is slower than alternatives.  This part
1985 of documentation is designed to overcome this misconception.
1986
1987 *By default* CPerl tries to enable the most comfortable settings.
1988 From most points of view, correctly working package is infinitely more
1989 comfortable than a non-correctly working one, thus by default CPerl
1990 prefers correctness over speed.  Below is the guide how to change
1991 settings if your preferences are different.
1992
1993 A)  Speed of loading the file.  When loading file, CPerl may perform a
1994 scan which indicates places which cannot be parsed by primitive Emacs
1995 syntax-parsing routines, and marks them up so that either
1996
1997     A1) CPerl may work around these deficiencies (for big chunks, mostly
1998         PODs and HERE-documents), or
1999     A2) On capable Emaxen CPerl will use improved syntax-handlings
2000         which reads mark-up hints directly.
2001
2002     The scan in case A2 is much more comprehensive, thus may be slower.
2003
2004     User can disable syntax-engine-helping scan of A2 by setting
2005        `cperl-use-syntax-table-text-property'
2006     variable to nil (if it is set to t).
2007
2008     One can disable the scan altogether (both A1 and A2) by setting
2009        `cperl-pod-here-scan'
2010     to nil.
2011
2012 B) Speed of editing operations.
2013
2014     One can add a (minor) speedup to editing operations by setting
2015        `cperl-use-syntax-table-text-property'
2016     variable to nil (if it is set to t).  This will disable
2017     syntax-engine-helping scan, thus will make many more Perl
2018     constructs be wrongly recognized by CPerl, thus may lead to
2019     wrongly matched parentheses, wrong indentation, etc.
2020
2021     One can unset `cperl-syntaxify-unwind'.  This might speed up editing
2022     of, say, long POD sections.")
2023
2024 (defvar cperl-tips-faces 'please-ignore-this-line
2025   "CPerl mode uses following faces for highlighting:
2026
2027   `cperl-array-face'            Array names
2028   `cperl-hash-face'             Hash names
2029   `font-lock-comment-face'      Comments, PODs and whatever is considered
2030                                 syntaxically to be not code
2031   `font-lock-constant-face'     HERE-doc delimiters, labels, delimiters of
2032                                 2-arg operators s/y/tr/ or of RExen,
2033   `font-lock-function-name-face' Special-cased m// and s//foo/, _ as
2034                                 a target of a file tests, file tests,
2035                                 subroutine names at the moment of definition
2036                                 (except those conflicting with Perl operators),
2037                                 package names (when recognized), format names
2038   `font-lock-keyword-face'      Control flow switch constructs, declarators
2039   `cperl-nonoverridable-face'   Non-overridable keywords, modifiers of RExen
2040   `font-lock-string-face'       Strings, qw() constructs, RExen, POD sections,
2041                                 literal parts and the terminator of formats
2042                                 and whatever is syntaxically considered
2043                                 as string literals
2044   `font-lock-type-face'         Overridable keywords
2045   `font-lock-variable-name-face' Variable declarations, indirect array and
2046                                 hash names, POD headers/item names
2047   `cperl-invalid-face'          Trailing whitespace
2048
2049 Note that in several situations the highlighting tries to inform about
2050 possible confusion, such as different colors for function names in
2051 declarations depending on what they (do not) override, or special cases
2052 m// and s/// which do not do what one would expect them to do.
2053
2054 Help with best setup of these faces for printout requested (for each of
2055 the faces: please specify bold, italic, underline, shadow and box.)
2056
2057 \(Not finished.)")
2058
2059 \f
2060
2061 ;;; Portability stuff:
2062
2063 (defmacro cperl-define-key (emacs-key definition &optional xemacs-key)
2064   (` (define-key cperl-mode-map
2065        (, (if xemacs-key
2066               (` (if cperl-xemacs-p (, xemacs-key) (, emacs-key)))
2067             emacs-key))
2068        (, definition))))
2069
2070 (defvar cperl-del-back-ch
2071   (car (append (where-is-internal 'delete-backward-char)
2072                (where-is-internal 'backward-delete-char-untabify)))
2073   "Character generated by key bound to `delete-backward-char'.")
2074
2075 (and (vectorp cperl-del-back-ch) (= (length cperl-del-back-ch) 1)
2076      (setq cperl-del-back-ch (aref cperl-del-back-ch 0)))
2077
2078 (defun cperl-mark-active () (mark))     ; Avoid undefined warning
2079 (if cperl-xemacs-p
2080     (progn
2081       ;; "Active regions" are on: use region only if active
2082       ;; "Active regions" are off: use region unconditionally
2083       (defun cperl-use-region-p ()
2084         (if zmacs-regions (mark) t)))
2085   (defun cperl-use-region-p ()
2086     (if transient-mark-mode mark-active t))
2087   (defun cperl-mark-active () mark-active))
2088
2089 (defsubst cperl-enable-font-lock ()
2090   cperl-can-font-lock)
2091
2092 (defun cperl-putback-char (c)           ; Emacs 19
2093   (set 'unread-command-events (list c))) ; Avoid undefined warning
2094
2095 (if (boundp 'unread-command-events)
2096     (if cperl-xemacs-p
2097         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
2098           (setq unread-command-events (list (eval '(character-to-event c))))))
2099   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
2100     (set 'unread-command-event (eval '(character-to-event c))))) ; Avoid warnings
2101
2102 (or (fboundp 'uncomment-region)
2103     (defun uncomment-region (beg end)
2104       (interactive "r")
2105       (comment-region beg end -1)))
2106
2107 (defvar cperl-do-not-fontify
2108   (if (string< emacs-version "19.30")
2109       'fontified
2110     'lazy-lock)
2111   "Text property which inhibits refontification.")
2112
2113 (defsubst cperl-put-do-not-fontify (from to &optional post)
2114   ;; If POST, do not do it with postponed fontification
2115   (if (and post cperl-syntaxify-by-font-lock)
2116       nil
2117     (put-text-property (max (point-min) (1- from))
2118                        to cperl-do-not-fontify t)))
2119
2120 (defcustom cperl-mode-hook nil
2121   "Hook run by CPerl mode."
2122   :type 'hook
2123   :group 'cperl)
2124
2125 (defvar cperl-syntax-state nil)
2126 (defvar cperl-syntax-done-to nil)
2127 (defvar cperl-emacs-can-parse (> (length (save-excursion
2128                                            (parse-partial-sexp (point) (point)))) 9))
2129 \f
2130 ;; Make customization possible "in reverse"
2131 (defsubst cperl-val (symbol &optional default hairy)
2132   (cond
2133    ((eq (symbol-value symbol) 'null) default)
2134    (cperl-hairy (or hairy t))
2135    (t (symbol-value symbol))))
2136 \f
2137 ;;; Probably it is too late to set these guys already, but it can help later:
2138
2139 (and cperl-clobber-mode-lists
2140      (setq auto-mode-alist
2141       (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
2142      (and (boundp 'interpreter-mode-alist)
2143           (setq interpreter-mode-alist (append interpreter-mode-alist
2144                                                '(("miniperl" . perl-mode))))))
2145 (if (fboundp 'eval-when-compile)
2146     (eval-when-compile
2147       (mapcar (lambda (p)
2148                 (condition-case nil
2149                     (require p)
2150                   (error nil)))
2151               '(imenu easymenu etags timer man info))
2152       (if (fboundp 'ps-extend-face-list)
2153           (defmacro cperl-ps-extend-face-list (arg)
2154             (` (ps-extend-face-list (, arg))))
2155         (defmacro cperl-ps-extend-face-list (arg)
2156           (` (error "This version of Emacs has no `ps-extend-face-list'"))))
2157       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
2158       ;; macros instead of defsubsts don't work on Emacs, so we do the
2159       ;; expansion manually.  Any other suggestions?
2160       (if cperl-can-font-lock
2161           (require 'font-lock))
2162       (require 'cl)))
2163
2164 (defvar cperl-mode-abbrev-table nil
2165   "Abbrev table in use in CPerl mode buffers.")
2166
2167 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
2168
2169 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
2170
2171 (if cperl-mode-map nil
2172   (setq cperl-mode-map (make-sparse-keymap))
2173   (cperl-define-key "{" 'cperl-electric-lbrace)
2174   (cperl-define-key "[" 'cperl-electric-paren)
2175   (cperl-define-key "(" 'cperl-electric-paren)
2176   (cperl-define-key "<" 'cperl-electric-paren)
2177   (cperl-define-key "}" 'cperl-electric-brace)
2178   (cperl-define-key "]" 'cperl-electric-rparen)
2179   (cperl-define-key ")" 'cperl-electric-rparen)
2180   (cperl-define-key ";" 'cperl-electric-semi)
2181   (cperl-define-key ":" 'cperl-electric-terminator)
2182   (cperl-define-key "\C-j" 'newline-and-indent)
2183   (cperl-define-key "\C-c\C-j" 'cperl-linefeed)
2184   (cperl-define-key "\C-c\C-t" 'cperl-invert-if-unless)
2185   (cperl-define-key "\C-c\C-a" 'cperl-toggle-auto-newline)
2186   (cperl-define-key "\C-c\C-k" 'cperl-toggle-abbrev)
2187   (cperl-define-key "\C-c\C-w" 'cperl-toggle-construct-fix)
2188   (cperl-define-key "\C-c\C-f" 'auto-fill-mode)
2189   (cperl-define-key "\C-c\C-e" 'cperl-toggle-electric)
2190   (cperl-define-key "\C-c\C-ha" 'cperl-toggle-autohelp)
2191   (cperl-define-key "\e\C-q" 'cperl-indent-exp) ; Usually not bound
2192   (cperl-define-key [?\C-\M-\|] 'cperl-lineup
2193                     [(control meta |)])
2194   ;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
2195   ;;(cperl-define-key "\e;" 'cperl-indent-for-comment)
2196   (cperl-define-key "\177" 'cperl-electric-backspace)
2197   (cperl-define-key "\t" 'cperl-indent-command)
2198   ;; don't clobber the backspace binding:
2199   (cperl-define-key "\C-c\C-hF" 'cperl-info-on-command
2200                     [(control c) (control h) F])
2201   (if (cperl-val 'cperl-clobber-lisp-bindings)
2202       (progn
2203         (cperl-define-key "\C-hf"
2204                           ;;(concat (char-to-string help-char) "f") ; does not work
2205                           'cperl-info-on-command
2206                           [(control h) f])
2207         (cperl-define-key "\C-hv"
2208                           ;;(concat (char-to-string help-char) "v") ; does not work
2209                           'cperl-get-help
2210                           [(control h) v])
2211         (cperl-define-key "\C-c\C-hf"
2212                           ;;(concat (char-to-string help-char) "f") ; does not work
2213                           (key-binding "\C-hf")
2214                           [(control c) (control h) f])
2215         (cperl-define-key "\C-c\C-hv"
2216                           ;;(concat (char-to-string help-char) "v") ; does not work
2217                           (key-binding "\C-hv")
2218                           [(control c) (control h) v]))
2219     (cperl-define-key "\C-c\C-hf" 'cperl-info-on-current-command
2220                       [(control c) (control h) f])
2221     (cperl-define-key "\C-c\C-hv"
2222                       ;;(concat (char-to-string help-char) "v") ; does not work
2223                       'cperl-get-help
2224                       [(control c) (control h) v]))
2225   (if (and cperl-xemacs-p
2226            (<= emacs-minor-version 11) (<= emacs-major-version 19))
2227       (progn
2228         ;; substitute-key-definition is usefulness-deenhanced...
2229         (cperl-define-key "\M-q" 'cperl-fill-paragraph)
2230         (cperl-define-key "\e;" 'cperl-indent-for-comment)
2231         (cperl-define-key "\e\C-\\" 'cperl-indent-region))
2232     (substitute-key-definition
2233      'indent-sexp 'cperl-indent-exp
2234      cperl-mode-map global-map)
2235     (substitute-key-definition
2236      'fill-paragraph 'cperl-fill-paragraph
2237      cperl-mode-map global-map)
2238     (substitute-key-definition
2239      'indent-region 'cperl-indent-region
2240      cperl-mode-map global-map)
2241     (substitute-key-definition
2242      'indent-for-comment 'cperl-indent-for-comment
2243      cperl-mode-map global-map)))
2244
2245 (defvar cperl-menu)
2246 (defvar cperl-lazy-installed)
2247 (defvar cperl-old-style nil)
2248 (condition-case nil
2249     (progn
2250       (require 'easymenu)
2251       (easy-menu-define
2252        cperl-menu cperl-mode-map "Menu for CPerl mode"
2253        '("Perl"
2254          ["Beginning of function" beginning-of-defun t]
2255          ["End of function" end-of-defun t]
2256          ["Mark function" mark-defun t]
2257          ["Indent expression" cperl-indent-exp t]
2258          ["Fill paragraph/comment" cperl-fill-paragraph t]
2259          "----"
2260          ["Line up a construction" cperl-lineup (cperl-use-region-p)]
2261          ["Invert if/unless/while etc" cperl-invert-if-unless t]
2262          ("Regexp"
2263           ["Beautify" cperl-beautify-regexp
2264            cperl-use-syntax-table-text-property]
2265           ["Beautify one level deep" (cperl-beautify-regexp 1)
2266            cperl-use-syntax-table-text-property]
2267           ["Beautify a group" cperl-beautify-level
2268            cperl-use-syntax-table-text-property]
2269           ["Beautify a group one level deep" (cperl-beautify-level 1)
2270            cperl-use-syntax-table-text-property]
2271           ["Contract a group" cperl-contract-level
2272            cperl-use-syntax-table-text-property]
2273           ["Contract groups" cperl-contract-levels
2274            cperl-use-syntax-table-text-property])
2275          ["Refresh \"hard\" constructions" cperl-find-pods-heres t]
2276          "----"
2277          ["Indent region" cperl-indent-region (cperl-use-region-p)]
2278          ["Comment region" cperl-comment-region (cperl-use-region-p)]
2279          ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
2280          "----"
2281          ["Run" mode-compile (fboundp 'mode-compile)]
2282          ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
2283                                         (get-buffer "*compilation*"))]
2284          ["Next error" next-error (get-buffer "*compilation*")]
2285          ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
2286          "----"
2287          ["Debugger" cperl-db t]
2288          "----"
2289          ("Tools"
2290           ["Imenu" imenu (fboundp 'imenu)]
2291           ["Insert spaces if needed" cperl-find-bad-style t]
2292           ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
2293           ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
2294           ["CPerl pretty print (exprmntl)" cperl-ps-print 
2295            (fboundp 'ps-extend-face-list)]
2296           ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
2297           ("Tags"
2298 ;;;          ["Create tags for current file" cperl-etags t]
2299 ;;;          ["Add tags for current file" (cperl-etags t) t]
2300 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
2301 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
2302 ;;;          ["Create tags for Perl files in (sub)directories"
2303 ;;;           (cperl-etags nil 'recursive) t]
2304 ;;;          ["Add tags for Perl files in (sub)directories"
2305 ;;;           (cperl-etags t 'recursive) t])
2306 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
2307            ["Create tags for current file" (cperl-write-tags nil t) t]
2308            ["Add tags for current file" (cperl-write-tags) t]
2309            ["Create tags for Perl files in directory"
2310             (cperl-write-tags nil t nil t) t]
2311            ["Add tags for Perl files in directory"
2312             (cperl-write-tags nil nil nil t) t]
2313            ["Create tags for Perl files in (sub)directories"
2314             (cperl-write-tags nil t t t) t]
2315            ["Add tags for Perl files in (sub)directories"
2316             (cperl-write-tags nil nil t t) t]))
2317          ("Perl docs"
2318           ["Define word at point" imenu-go-find-at-position 
2319            (fboundp 'imenu-go-find-at-position)]
2320           ["Help on function" cperl-info-on-command t]
2321           ["Help on function at point" cperl-info-on-current-command t]
2322           ["Help on symbol at point" cperl-get-help t]
2323           ["Perldoc" cperl-perldoc t]
2324           ["Perldoc on word at point" cperl-perldoc-at-point t]
2325           ["View manpage of POD in this file" cperl-build-manpage t]
2326           ["Auto-help on" cperl-lazy-install 
2327            (and (fboundp 'run-with-idle-timer)
2328                 (not cperl-lazy-installed))]
2329           ["Auto-help off" cperl-lazy-unstall
2330            (and (fboundp 'run-with-idle-timer)
2331                 cperl-lazy-installed)])
2332          ("Toggle..."
2333           ["Auto newline" cperl-toggle-auto-newline t]
2334           ["Electric parens" cperl-toggle-electric t]
2335           ["Electric keywords" cperl-toggle-abbrev t]
2336           ["Fix whitespace on indent" cperl-toggle-construct-fix t]
2337           ["Auto-help on Perl constructs" cperl-toggle-autohelp t]
2338           ["Auto fill" auto-fill-mode t]) 
2339          ("Indent styles..."
2340           ["CPerl" (cperl-set-style "CPerl") t]
2341           ["PerlStyle" (cperl-set-style "PerlStyle") t]
2342           ["GNU" (cperl-set-style "GNU") t]
2343           ["C++" (cperl-set-style "C++") t]
2344           ["FSF" (cperl-set-style "FSF") t]
2345           ["BSD" (cperl-set-style "BSD") t]
2346           ["Whitesmith" (cperl-set-style "Whitesmith") t]
2347           ["Current" (cperl-set-style "Current") t]
2348           ["Memorized" (cperl-set-style-back) cperl-old-style])
2349          ("Micro-docs"
2350           ["Tips" (describe-variable 'cperl-tips) t]
2351           ["Problems" (describe-variable 'cperl-problems) t]
2352           ["Non-problems" (describe-variable 'cperl-non-problems) t]
2353           ["Speed" (describe-variable 'cperl-speed) t]
2354           ["Praise" (describe-variable 'cperl-praise) t]
2355           ["Faces" (describe-variable 'cperl-tips-faces) t]
2356           ["CPerl mode" (describe-function 'cperl-mode) t]
2357           ["CPerl version" 
2358            (message "The version of master-file for this CPerl is %s" 
2359                     cperl-version) t]))))
2360   (error nil))
2361
2362 (autoload 'c-macro-expand "cmacexp"
2363   "Display the result of expanding all C macros occurring in the region.
2364 The expansion is entirely correct because it uses the C preprocessor."
2365   t)
2366
2367 (defvar cperl-imenu--function-name-regexp-perl
2368   (concat
2369    "^\\("
2370         "[ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*\\(([^()]*)[ \t]*\\)?"
2371    "\\|"
2372         "=head\\([12]\\)[ \t]+\\([^\n]+\\)$"
2373    "\\)"))
2374
2375 (defvar cperl-outline-regexp
2376   (concat cperl-imenu--function-name-regexp-perl "\\|" "\\`"))
2377
2378 (defvar cperl-mode-syntax-table nil
2379   "Syntax table in use in CPerl mode buffers.")
2380
2381 (defvar cperl-string-syntax-table nil
2382   "Syntax table in use in CPerl mode string-like chunks.")
2383
2384 (if cperl-mode-syntax-table
2385     ()
2386   (setq cperl-mode-syntax-table (make-syntax-table))
2387   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
2388   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
2389   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
2390   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
2391   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
2392   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
2393   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
2394   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
2395   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
2396   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
2397   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
2398   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
2399   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
2400   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
2401   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
2402   (if cperl-under-as-char
2403       (modify-syntax-entry ?_ "w" cperl-mode-syntax-table))
2404   (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
2405   (modify-syntax-entry ?| "." cperl-mode-syntax-table)
2406   (setq cperl-string-syntax-table (copy-syntax-table cperl-mode-syntax-table))
2407   (modify-syntax-entry ?$ "." cperl-string-syntax-table)
2408   (modify-syntax-entry ?# "." cperl-string-syntax-table)) ; (?# comment )
2409
2410
2411 \f
2412 ;; provide an alias for working with emacs 19.  the perl-mode that comes
2413 ;; with it is really bad, and this lets us seamlessly replace it.
2414 ;;;###autoload
2415 (fset 'perl-mode 'cperl-mode)
2416 (defvar cperl-faces-init nil)
2417 ;; Fix for msb.el
2418 (defvar cperl-msb-fixed nil)
2419 (defvar font-lock-syntactic-keywords)
2420 (defvar perl-font-lock-keywords)
2421 (defvar perl-font-lock-keywords-1)
2422 (defvar perl-font-lock-keywords-2)
2423 (defvar outline-level)
2424 (if (fboundp 'defvaralias)
2425     (let ((f 'defvaralias)) ; Some functions deduce stuff from the mode name...
2426       (funcall f 'cperl-font-lock-keywords   'perl-font-lock-keywords)
2427       (funcall f 'cperl-font-lock-keywords-1 'perl-font-lock-keywords-1)
2428       (funcall f 'cperl-font-lock-keywords-2 'perl-font-lock-keywords-2)))
2429
2430 (defvar cperl-use-major-mode 'perl-mode)
2431
2432 ;;;###autoload
2433 (defun cperl-mode ()
2434   "Major mode for editing Perl code.
2435 Expression and list commands understand all C brackets.
2436 Tab indents for Perl code.
2437 Paragraphs are separated by blank lines only.
2438 Delete converts tabs to spaces as it moves back.
2439
2440 Various characters in Perl almost always come in pairs: {}, (), [],
2441 sometimes <>.  When the user types the first, she gets the second as
2442 well, with optional special formatting done on {}.  (Disabled by
2443 default.)  You can always quote (with \\[quoted-insert]) the left
2444 \"paren\" to avoid the expansion.  The processing of < is special,
2445 since most the time you mean \"less\".  CPerl mode tries to guess
2446 whether you want to type pair <>, and inserts is if it
2447 appropriate.  You can set `cperl-electric-parens-string' to the string that
2448 contains the parenths from the above list you want to be electrical.
2449 Electricity of parenths is controlled by `cperl-electric-parens'.
2450 You may also set `cperl-electric-parens-mark' to have electric parens
2451 look for active mark and \"embrace\" a region if possible.'
2452
2453 CPerl mode provides expansion of the Perl control constructs:
2454
2455    if, else, elsif, unless, while, until, continue, do,
2456    for, foreach, formy and foreachmy.
2457
2458 and POD directives (Disabled by default, see `cperl-electric-keywords'.)
2459
2460 The user types the keyword immediately followed by a space, which
2461 causes the construct to be expanded, and the point is positioned where
2462 she is most likely to want to be.  eg. when the user types a space
2463 following \"if\" the following appears in the buffer: if () { or if ()
2464 } { } and the cursor is between the parentheses.  The user can then
2465 type some boolean expression within the parens.  Having done that,
2466 typing \\[cperl-linefeed] places you - appropriately indented - on a
2467 new line between the braces (if you typed \\[cperl-linefeed] in a POD
2468 directive line, then appropriate number of new lines is inserted).
2469
2470 If CPerl decides that you want to insert \"English\" style construct like
2471
2472             bite if angry;
2473
2474 it will not do any expansion.  See also help on variable
2475 `cperl-extra-newline-before-brace'.  (Note that one can switch the
2476 help message on expansion by setting `cperl-message-electric-keyword'
2477 to nil.)
2478
2479 \\[cperl-linefeed] is a convenience replacement for typing carriage
2480 return.  It places you in the next line with proper indentation, or if
2481 you type it inside the inline block of control construct, like
2482
2483             foreach (@lines) {print; print}
2484
2485 and you are on a boundary of a statement inside braces, it will
2486 transform the construct into a multiline and will place you into an
2487 appropriately indented blank line.  If you need a usual
2488 `newline-and-indent' behaviour, it is on \\[newline-and-indent],
2489 see documentation on `cperl-electric-linefeed'.
2490
2491 Use \\[cperl-invert-if-unless] to change a construction of the form
2492
2493             if (A) { B }
2494
2495 into
2496
2497             B if A;
2498
2499 \\{cperl-mode-map}
2500
2501 Setting the variable `cperl-font-lock' to t switches on font-lock-mode
2502 \(even with older Emacsen), `cperl-electric-lbrace-space' to t switches
2503 on electric space between $ and {, `cperl-electric-parens-string' is
2504 the string that contains parentheses that should be electric in CPerl
2505 \(see also `cperl-electric-parens-mark' and `cperl-electric-parens'),
2506 setting `cperl-electric-keywords' enables electric expansion of
2507 control structures in CPerl.  `cperl-electric-linefeed' governs which
2508 one of two linefeed behavior is preferable.  You can enable all these
2509 options simultaneously (recommended mode of use) by setting
2510 `cperl-hairy' to t.  In this case you can switch separate options off
2511 by setting them to `null'.  Note that one may undo the extra
2512 whitespace inserted by semis and braces in `auto-newline'-mode by
2513 consequent \\[cperl-electric-backspace].
2514
2515 If your site has perl5 documentation in info format, you can use commands
2516 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
2517 These keys run commands `cperl-info-on-current-command' and
2518 `cperl-info-on-command', which one is which is controlled by variable
2519 `cperl-info-on-command-no-prompt' and `cperl-clobber-lisp-bindings'
2520 \(in turn affected by `cperl-hairy').
2521
2522 Even if you have no info-format documentation, short one-liner-style
2523 help is available on \\[cperl-get-help], and one can run perldoc or
2524 man via menu.
2525
2526 It is possible to show this help automatically after some idle time.
2527 This is regulated by variable `cperl-lazy-help-time'.  Default with
2528 `cperl-hairy' (if the value of `cperl-lazy-help-time' is nil) is 5
2529 secs idle time .  It is also possible to switch this on/off from the
2530 menu, or via \\[cperl-toggle-autohelp].  Requires `run-with-idle-timer'.
2531
2532 Use \\[cperl-lineup] to vertically lineup some construction - put the
2533 beginning of the region at the start of construction, and make region
2534 span the needed amount of lines.
2535
2536 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
2537 `cperl-pod-face', `cperl-pod-head-face' control processing of POD and
2538 here-docs sections.  With capable Emaxen results of scan are used
2539 for indentation too, otherwise they are used for highlighting only.
2540
2541 Variables controlling indentation style:
2542  `cperl-tab-always-indent'
2543     Non-nil means TAB in CPerl mode should always reindent the current line,
2544     regardless of where in the line point is when the TAB command is used.
2545  `cperl-indent-left-aligned-comments'
2546     Non-nil means that the comment starting in leftmost column should indent.
2547  `cperl-auto-newline'
2548     Non-nil means automatically newline before and after braces,
2549     and after colons and semicolons, inserted in Perl code.  The following
2550     \\[cperl-electric-backspace] will remove the inserted whitespace.
2551     Insertion after colons requires both this variable and
2552     `cperl-auto-newline-after-colon' set.
2553  `cperl-auto-newline-after-colon'
2554     Non-nil means automatically newline even after colons.
2555     Subject to `cperl-auto-newline' setting.
2556  `cperl-indent-level'
2557     Indentation of Perl statements within surrounding block.
2558     The surrounding block's indentation is the indentation
2559     of the line on which the open-brace appears.
2560  `cperl-continued-statement-offset'
2561     Extra indentation given to a substatement, such as the
2562     then-clause of an if, or body of a while, or just a statement continuation.
2563  `cperl-continued-brace-offset'
2564     Extra indentation given to a brace that starts a substatement.
2565     This is in addition to `cperl-continued-statement-offset'.
2566  `cperl-brace-offset'
2567     Extra indentation for line if it starts with an open brace.
2568  `cperl-brace-imaginary-offset'
2569     An open brace following other text is treated as if it the line started
2570     this far to the right of the actual line indentation.
2571  `cperl-label-offset'
2572     Extra indentation for line that is a label.
2573  `cperl-min-label-indent'
2574     Minimal indentation for line that is a label.
2575
2576 Settings for K&R and BSD indentation styles are
2577   `cperl-indent-level'                5    8
2578   `cperl-continued-statement-offset'  5    8
2579   `cperl-brace-offset'               -5   -8
2580   `cperl-label-offset'               -5   -8
2581
2582 CPerl knows several indentation styles, and may bulk set the
2583 corresponding variables.  Use \\[cperl-set-style] to do this.  Use
2584 \\[cperl-set-style-back] to restore the memorized preexisting values
2585 \(both available from menu).
2586
2587 If `cperl-indent-level' is 0, the statement after opening brace in
2588 column 0 is indented on
2589 `cperl-brace-offset'+`cperl-continued-statement-offset'.
2590
2591 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
2592 with no args.
2593
2594 DO NOT FORGET to read micro-docs (available from `Perl' menu)
2595 or as help on variables `cperl-tips', `cperl-problems',
2596 `cperl-non-problems', `cperl-praise', `cperl-speed'."
2597   (interactive)
2598   (kill-all-local-variables)
2599   (use-local-map cperl-mode-map)
2600   (if (cperl-val 'cperl-electric-linefeed)
2601       (progn
2602         (local-set-key "\C-J" 'cperl-linefeed)
2603         (local-set-key "\C-C\C-J" 'newline-and-indent)))
2604   (if (and
2605        (cperl-val 'cperl-clobber-lisp-bindings)
2606        (cperl-val 'cperl-info-on-command-no-prompt))
2607       (progn
2608         ;; don't clobber the backspace binding:
2609         (cperl-define-key "\C-hf" 'cperl-info-on-current-command [(control h) f])
2610         (cperl-define-key "\C-c\C-hf" 'cperl-info-on-command
2611                           [(control c) (control h) f])))
2612   (setq major-mode cperl-use-major-mode)
2613   (setq mode-name "CPerl")
2614   (if (not cperl-mode-abbrev-table)
2615       (let ((prev-a-c abbrevs-changed))
2616         (define-abbrev-table 'cperl-mode-abbrev-table '(
2617                 ("if" "if" cperl-electric-keyword 0)
2618                 ("elsif" "elsif" cperl-electric-keyword 0)
2619                 ("while" "while" cperl-electric-keyword 0)
2620                 ("until" "until" cperl-electric-keyword 0)
2621                 ("unless" "unless" cperl-electric-keyword 0)
2622                 ("else" "else" cperl-electric-else 0)
2623                 ("continue" "continue" cperl-electric-else 0)
2624                 ("for" "for" cperl-electric-keyword 0)
2625                 ("foreach" "foreach" cperl-electric-keyword 0)
2626                 ("formy" "formy" cperl-electric-keyword 0)
2627                 ("foreachmy" "foreachmy" cperl-electric-keyword 0)
2628                 ("do" "do" cperl-electric-keyword 0)
2629                 ("=pod" "=pod" cperl-electric-pod 0)
2630                 ("=over" "=over" cperl-electric-pod 0)
2631                 ("=head1" "=head1" cperl-electric-pod 0)
2632                 ("=head2" "=head2" cperl-electric-pod 0)
2633                 ("pod" "pod" cperl-electric-pod 0)
2634                 ("over" "over" cperl-electric-pod 0)
2635                 ("head1" "head1" cperl-electric-pod 0)
2636                 ("head2" "head2" cperl-electric-pod 0)))
2637         (setq abbrevs-changed prev-a-c)))
2638   (setq local-abbrev-table cperl-mode-abbrev-table)
2639   (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
2640   (set-syntax-table cperl-mode-syntax-table)
2641   (make-local-variable 'outline-regexp)
2642   ;; (setq outline-regexp imenu-example--function-name-regexp-perl)
2643   (setq outline-regexp cperl-outline-regexp)
2644   (make-local-variable 'outline-level)
2645   (setq outline-level 'cperl-outline-level)
2646   (make-local-variable 'paragraph-start)
2647   (setq paragraph-start (concat "^$\\|" page-delimiter))
2648   (make-local-variable 'paragraph-separate)
2649   (setq paragraph-separate paragraph-start)
2650   (make-local-variable 'paragraph-ignore-fill-prefix)
2651   (setq paragraph-ignore-fill-prefix t)
2652   (make-local-variable 'indent-line-function)
2653   (setq indent-line-function 'cperl-indent-line)
2654   (make-local-variable 'require-final-newline)
2655   (setq require-final-newline t)
2656   (make-local-variable 'comment-start)
2657   (setq comment-start "# ")
2658   (make-local-variable 'comment-end)
2659   (setq comment-end "")
2660   (make-local-variable 'comment-column)
2661   (setq comment-column cperl-comment-column)
2662   (make-local-variable 'comment-start-skip)
2663   (setq comment-start-skip "#+ *")
2664   (make-local-variable 'defun-prompt-regexp)
2665   (setq defun-prompt-regexp "^[ \t]*sub[ \t]+\\([^ \t\n{(;]+\\)\\([ \t]*([^()]*)[ \t]*\\)?[ \t]*")
2666   (make-local-variable 'comment-indent-function)
2667   (setq comment-indent-function 'cperl-comment-indent)
2668   (make-local-variable 'parse-sexp-ignore-comments)
2669   (setq parse-sexp-ignore-comments t)
2670   (make-local-variable 'indent-region-function)
2671   (setq indent-region-function 'cperl-indent-region)
2672   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
2673   (make-local-variable 'imenu-create-index-function)
2674   (setq imenu-create-index-function
2675         (function cperl-imenu--create-perl-index))
2676   (make-local-variable 'imenu-sort-function)
2677   (setq imenu-sort-function nil)
2678   (make-local-variable 'vc-header-alist)
2679   (set 'vc-header-alist cperl-vc-header-alist) ; Avoid warning
2680   (make-local-variable 'font-lock-defaults)
2681   (setq font-lock-defaults
2682         (cond
2683          ((string< emacs-version "19.30")
2684           '(perl-font-lock-keywords-2))
2685          ((string< emacs-version "19.33") ; Which one to use?
2686           '((perl-font-lock-keywords
2687              perl-font-lock-keywords-1
2688              perl-font-lock-keywords-2)))
2689          (t
2690           '((cperl-load-font-lock-keywords
2691              cperl-load-font-lock-keywords-1
2692              cperl-load-font-lock-keywords-2)))))
2693   (make-local-variable 'cperl-syntax-state)
2694   (if cperl-use-syntax-table-text-property
2695       (progn
2696         (make-local-variable 'parse-sexp-lookup-properties)
2697         ;; Do not introduce variable if not needed, we check it!
2698         (set 'parse-sexp-lookup-properties t)
2699         ;; Fix broken font-lock:
2700         (or (boundp 'font-lock-unfontify-region-function)
2701             (set 'font-lock-unfontify-region-function
2702                  'font-lock-default-unfontify-region))
2703         (make-local-variable 'font-lock-unfontify-region-function)
2704         (set 'font-lock-unfontify-region-function ; not present with old Emacs
2705               'cperl-font-lock-unfontify-region-function)
2706         (make-local-variable 'cperl-syntax-done-to)
2707         ;; Another bug: unless font-lock-syntactic-keywords, font-lock
2708         ;;  ignores syntax-table text-property.  (t) is a hack
2709         ;;  to make font-lock think that font-lock-syntactic-keywords
2710         ;;  are defined
2711         (make-local-variable 'font-lock-syntactic-keywords)
2712         (setq font-lock-syntactic-keywords
2713               (if cperl-syntaxify-by-font-lock
2714                   '(t (cperl-fontify-syntaxically))
2715                 '(t)))))
2716   (make-local-variable 'cperl-old-style)
2717   (if (boundp 'normal-auto-fill-function) ; 19.33 and later
2718       (set (make-local-variable 'normal-auto-fill-function)
2719            'cperl-do-auto-fill)       ; RMS has it as #'cperl-do-auto-fill ???
2720     (or (fboundp 'cperl-old-auto-fill-mode)
2721         (progn
2722           (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
2723           (defun auto-fill-mode (&optional arg)
2724             (interactive "P")
2725             (eval '(cperl-old-auto-fill-mode arg)) ; Avoid a warning
2726             (and auto-fill-function (memq major-mode '(perl-mode cperl-mode))
2727                  (setq auto-fill-function 'cperl-do-auto-fill))))))
2728   (if (cperl-enable-font-lock)
2729       (if (cperl-val 'cperl-font-lock)
2730           (progn (or cperl-faces-init (cperl-init-faces))
2731                  (font-lock-mode 1))))
2732   (and (boundp 'msb-menu-cond)
2733        (not cperl-msb-fixed)
2734        (cperl-msb-fix))
2735   (if (featurep 'easymenu)
2736       (easy-menu-add cperl-menu))       ; A NOP in RMS Emacs.
2737   (run-hooks 'cperl-mode-hook)
2738   ;; After hooks since fontification will break this
2739   (if cperl-pod-here-scan
2740       (or cperl-syntaxify-by-font-lock
2741        (progn (or cperl-faces-init (cperl-init-faces-weak))
2742               (cperl-find-pods-heres)))))
2743 \f
2744 ;; Fix for perldb - make default reasonable
2745 (defun cperl-db ()
2746   (interactive)
2747   (require 'gud)
2748   (perldb (read-from-minibuffer "Run perldb (like this): "
2749                                 (if (consp gud-perldb-history)
2750                                     (car gud-perldb-history)
2751                                   (concat "perl " ;;(file-name-nondirectory
2752                                           ;; I have problems
2753                                           ;; in OS/2
2754                                           ;; otherwise
2755                                           (buffer-file-name)))
2756                                 nil nil
2757                                 '(gud-perldb-history . 1))))
2758 \f
2759 (defun cperl-msb-fix ()
2760   ;; Adds perl files to msb menu, supposes that msb is already loaded
2761   (setq cperl-msb-fixed t)
2762   (let* ((l (length msb-menu-cond))
2763          (last (nth (1- l) msb-menu-cond))
2764          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
2765          (handle (1- (nth 1 last))))
2766     (setcdr precdr (list
2767                     (list
2768                      '(memq major-mode '(cperl-mode perl-mode))
2769                      handle
2770                      "Perl Files (%d)")
2771                     last))))
2772 \f
2773 ;; This is used by indent-for-comment
2774 ;; to decide how much to indent a comment in CPerl code
2775 ;; based on its context.  Do fallback if comment is found wrong.
2776
2777 (defvar cperl-wrong-comment)
2778 (defvar cperl-st-cfence '(14))          ; Comment-fence
2779 (defvar cperl-st-sfence '(15))          ; String-fence
2780 (defvar cperl-st-punct '(1))
2781 (defvar cperl-st-word '(2))
2782 (defvar cperl-st-bra '(4 . ?\>))
2783 (defvar cperl-st-ket '(5 . ?\<))
2784
2785
2786 (defun cperl-comment-indent ()
2787   (let ((p (point)) (c (current-column)) was phony)
2788     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
2789       ;; Wrong comment found
2790       (save-excursion
2791         (setq was (cperl-to-comment-or-eol)
2792               phony (eq (get-text-property (point) 'syntax-table)
2793                         cperl-st-cfence))
2794         (if phony
2795             (progn
2796               (re-search-forward "#\\|$") ; Hmm, what about embedded #?
2797               (if (eq (preceding-char) ?\#)
2798                   (forward-char -1))
2799               (setq was nil)))
2800         (if (= (point) p)
2801             (progn
2802               (skip-chars-backward " \t")
2803               (max (1+ (current-column)) ; Else indent at comment column
2804                    comment-column))
2805           (if was nil
2806             (insert comment-start)
2807             (backward-char (length comment-start)))
2808           (setq cperl-wrong-comment t)
2809           (indent-to comment-column 1)  ; Indent minimum 1
2810           c)))))                        ; except leave at least one space.
2811
2812 ;;;(defun cperl-comment-indent-fallback ()
2813 ;;;  "Is called if the standard comment-search procedure fails.
2814 ;;;Point is at start of real comment."
2815 ;;;  (let ((c (current-column)) target cnt prevc)
2816 ;;;    (if (= c comment-column) nil
2817 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
2818 ;;;      (setq target (max (1+ (setq prevc
2819 ;;;                          (current-column))) ; Else indent at comment column
2820 ;;;                comment-column))
2821 ;;;      (if (= c comment-column) nil
2822 ;;;     (delete-backward-char cnt)
2823 ;;;     (while (< prevc target)
2824 ;;;       (insert "\t")
2825 ;;;       (setq prevc (current-column)))
2826 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
2827 ;;;     (while (< prevc target)
2828 ;;;       (insert " ")
2829 ;;;       (setq prevc (current-column)))))))
2830
2831 (defun cperl-indent-for-comment ()
2832   "Substitute for `indent-for-comment' in CPerl."
2833   (interactive)
2834   (let (cperl-wrong-comment)
2835     (indent-for-comment)
2836     (if cperl-wrong-comment
2837         (progn (cperl-to-comment-or-eol)
2838                (forward-char (length comment-start))))))
2839
2840 (defun cperl-comment-region (b e arg)
2841   "Comment or uncomment each line in the region in CPerl mode.
2842 See `comment-region'."
2843   (interactive "r\np")
2844   (let ((comment-start "#"))
2845     (comment-region b e arg)))
2846
2847 (defun cperl-uncomment-region (b e arg)
2848   "Uncomment or comment each line in the region in CPerl mode.
2849 See `comment-region'."
2850   (interactive "r\np")
2851   (let ((comment-start "#"))
2852     (comment-region b e (- arg))))
2853
2854 (defvar cperl-brace-recursing nil)
2855
2856 (defun cperl-electric-brace (arg &optional only-before)
2857   "Insert character and correct line's indentation.
2858 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
2859 place (even in empty line), but not after.  If after \")\" and the inserted
2860 char is \"{\", insert extra newline before only if
2861 `cperl-extra-newline-before-brace'."
2862   (interactive "P")
2863   (let (insertpos
2864         (other-end (if (and cperl-electric-parens-mark
2865                             (cperl-mark-active)
2866                             (< (mark) (point)))
2867                        (mark)
2868                      nil)))
2869     (if (and other-end
2870              (not cperl-brace-recursing)
2871              (cperl-val 'cperl-electric-parens)
2872              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point)))
2873         ;; Need to insert a matching pair
2874         (progn
2875           (save-excursion
2876             (setq insertpos (point-marker))
2877             (goto-char other-end)
2878             (setq last-command-char ?\{)
2879             (cperl-electric-lbrace arg insertpos))
2880           (forward-char 1))
2881       ;; Check whether we close something "usual" with `}'
2882       (if (and (eq last-command-char ?\})
2883                (not
2884                 (condition-case nil
2885                     (save-excursion
2886                       (up-list (- (prefix-numeric-value arg)))
2887                       ;;(cperl-after-block-p (point-min))
2888                       (or (cperl-after-expr-p nil "{;)")
2889                           ;; after sub, else, continue
2890                           (cperl-after-block-p nil 'pre)))
2891                   (error nil))))
2892           ;; Just insert the guy
2893           (self-insert-command (prefix-numeric-value arg))
2894         (if (and (not arg)              ; No args, end (of empty line or auto)
2895                  (eolp)
2896                  (or (and (null only-before)
2897                           (save-excursion
2898                             (skip-chars-backward " \t")
2899                             (bolp)))
2900                      (and (eq last-command-char ?\{) ; Do not insert newline
2901                           ;; if after ")" and `cperl-extra-newline-before-brace'
2902                           ;; is nil, do not insert extra newline.
2903                           (not cperl-extra-newline-before-brace)
2904                           (save-excursion
2905                             (skip-chars-backward " \t")
2906                             (eq (preceding-char) ?\))))
2907                      (if cperl-auto-newline
2908                          (progn (cperl-indent-line) (newline) t) nil)))
2909             (progn
2910               (self-insert-command (prefix-numeric-value arg))
2911               (cperl-indent-line)
2912               (if cperl-auto-newline
2913                   (setq insertpos (1- (point))))
2914               (if (and cperl-auto-newline (null only-before))
2915                   (progn
2916                     (newline)
2917                     (cperl-indent-line)))
2918               (save-excursion
2919                 (if insertpos (progn (goto-char insertpos)
2920                                      (search-forward (make-string
2921                                                       1 last-command-char))
2922                                      (setq insertpos (1- (point)))))
2923                 (delete-char -1))))
2924         (if insertpos
2925             (save-excursion
2926               (goto-char insertpos)
2927               (self-insert-command (prefix-numeric-value arg)))
2928           (self-insert-command (prefix-numeric-value arg)))))))
2929
2930 (defun cperl-electric-lbrace (arg &optional end)
2931   "Insert character, correct line's indentation, correct quoting by space."
2932   (interactive "P")
2933   (let ((cperl-brace-recursing t)
2934         (cperl-auto-newline cperl-auto-newline)
2935         (other-end (or end
2936                        (if (and cperl-electric-parens-mark
2937                                 (cperl-mark-active)
2938                                 (> (mark) (point)))
2939                            (save-excursion
2940                              (goto-char (mark))
2941                              (point-marker))
2942                          nil)))
2943         pos after)
2944     (and (cperl-val 'cperl-electric-lbrace-space)
2945          (eq (preceding-char) ?$)
2946          (save-excursion
2947            (skip-chars-backward "$")
2948            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
2949          (insert ?\ ))
2950     ;; Check whether we are in comment
2951     (if (and
2952          (save-excursion
2953            (beginning-of-line)
2954            (not (looking-at "[ \t]*#")))
2955          (cperl-after-expr-p nil "{;)"))
2956         nil
2957       (setq cperl-auto-newline nil))
2958     (cperl-electric-brace arg)
2959     (and (cperl-val 'cperl-electric-parens)
2960          (eq last-command-char ?{)
2961          (memq last-command-char
2962                (append cperl-electric-parens-string nil))
2963          (or (if other-end (goto-char (marker-position other-end)))
2964              t)
2965          (setq last-command-char ?} pos (point))
2966          (progn (cperl-electric-brace arg t)
2967                 (goto-char pos)))))
2968
2969 (defun cperl-electric-paren (arg)
2970   "Insert an opening parenthesis or a matching pair of parentheses.
2971 See `cperl-electric-parens'."
2972   (interactive "P")
2973   (let ((beg (save-excursion (beginning-of-line) (point)))
2974         (other-end (if (and cperl-electric-parens-mark
2975                             (cperl-mark-active)
2976                             (> (mark) (point)))
2977                        (save-excursion
2978                          (goto-char (mark))
2979                          (point-marker))
2980                      nil)))
2981     (if (and (cperl-val 'cperl-electric-parens)
2982              (memq last-command-char
2983                    (append cperl-electric-parens-string nil))
2984              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
2985              ;;(not (save-excursion (search-backward "#" beg t)))
2986              (if (eq last-command-char ?<)
2987                  (progn
2988                    (and abbrev-mode ; later it is too late, may be after `for'
2989                         (expand-abbrev))
2990                    (cperl-after-expr-p nil "{;(,:="))
2991                1))
2992         (progn
2993           (self-insert-command (prefix-numeric-value arg))
2994           (if other-end (goto-char (marker-position other-end)))
2995           (insert (make-string
2996                    (prefix-numeric-value arg)
2997                    (cdr (assoc last-command-char '((?{ .?})
2998                                                    (?[ . ?])
2999                                                    (?( . ?))
3000                                                    (?< . ?>))))))
3001           (forward-char (- (prefix-numeric-value arg))))
3002       (self-insert-command (prefix-numeric-value arg)))))
3003
3004 (defun cperl-electric-rparen (arg)
3005   "Insert a matching pair of parentheses if marking is active.
3006 If not, or if we are not at the end of marking range, would self-insert.
3007 Affected by `cperl-electric-parens'."
3008   (interactive "P")
3009   (let ((beg (save-excursion (beginning-of-line) (point)))
3010         (other-end (if (and cperl-electric-parens-mark
3011                             (cperl-val 'cperl-electric-parens)
3012                             (memq last-command-char
3013                                   (append cperl-electric-parens-string nil))
3014                             (cperl-mark-active)
3015                             (< (mark) (point)))
3016                        (mark)
3017                      nil))
3018         p)
3019     (if (and other-end
3020              (cperl-val 'cperl-electric-parens)
3021              (memq last-command-char '( ?\) ?\] ?\} ?\> ))
3022              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
3023              ;;(not (save-excursion (search-backward "#" beg t)))
3024              )
3025         (progn
3026           (self-insert-command (prefix-numeric-value arg))
3027           (setq p (point))
3028           (if other-end (goto-char other-end))
3029           (insert (make-string
3030                    (prefix-numeric-value arg)
3031                    (cdr (assoc last-command-char '((?\} . ?\{)
3032                                                    (?\] . ?\[)
3033                                                    (?\) . ?\()
3034                                                    (?\> . ?\<))))))
3035           (goto-char (1+ p)))
3036       (self-insert-command (prefix-numeric-value arg)))))
3037
3038 (defun cperl-electric-keyword ()
3039   "Insert a construction appropriate after a keyword.
3040 Help message may be switched off by setting `cperl-message-electric-keyword'
3041 to nil."
3042   (let ((beg (save-excursion (beginning-of-line) (point)))
3043         (dollar (and (eq last-command-char ?$)
3044                      (eq this-command 'self-insert-command)))
3045         (delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3046                      (memq this-command '(self-insert-command newline))))
3047         my do)
3048     (and (save-excursion
3049            (condition-case nil
3050                (progn
3051                  (backward-sexp 1)
3052                  (setq do (looking-at "do\\>")))
3053              (error nil))
3054            (cperl-after-expr-p nil "{;:"))
3055          (save-excursion
3056            (not
3057             (re-search-backward
3058              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3059              beg t)))
3060          (save-excursion (or (not (re-search-backward "^=" nil t))
3061                              (or
3062                               (looking-at "=cut")
3063                               (and cperl-use-syntax-table-text-property
3064                                    (not (eq (get-text-property (point)
3065                                                                'syntax-type)
3066                                             'pod))))))
3067          (save-excursion (forward-sexp -1) 
3068                          (not (memq (following-char) (append "$@%&*" nil))))
3069          (progn
3070            (and (eq (preceding-char) ?y)
3071                 (progn                  ; "foreachmy"
3072                   (forward-char -2)
3073                   (insert " ")
3074                   (forward-char 2)
3075                   (setq my t dollar t
3076                         delete
3077                         (memq this-command '(self-insert-command newline)))))
3078            (and dollar (insert " $"))
3079            (cperl-indent-line)
3080            ;;(insert " () {\n}")
3081            (cond
3082             (cperl-extra-newline-before-brace
3083              (insert (if do "\n" " ()\n"))
3084              (insert "{")
3085              (cperl-indent-line)
3086              (insert "\n")
3087              (cperl-indent-line)
3088              (insert "\n}")
3089              (and do (insert " while ();")))
3090             (t
3091              (insert (if do " {\n} while ();" " () {\n}"))))
3092            (or (looking-at "[ \t]\\|$") (insert " "))
3093            (cperl-indent-line)
3094            (if dollar (progn (search-backward "$")
3095                              (if my
3096                                  (forward-char 1)
3097                                (delete-char 1)))
3098              (search-backward ")")
3099              (if (eq last-command-char ?\()
3100                  (progn                 ; Avoid "if (())"
3101                    (delete-backward-char 1)
3102                    (delete-backward-char -1))))
3103            (if delete
3104                (cperl-putback-char cperl-del-back-ch))
3105            (if cperl-message-electric-keyword
3106                (message "Precede char by C-q to avoid expansion"))))))
3107
3108 (defun cperl-ensure-newlines (n &optional pos)
3109   "Make sure there are N newlines after the point."
3110   (or pos (setq pos (point)))
3111   (if (looking-at "\n")
3112       (forward-char 1)
3113     (insert "\n"))
3114   (if (> n 1)
3115       (cperl-ensure-newlines (1- n) pos)
3116     (goto-char pos)))
3117
3118 (defun cperl-electric-pod ()
3119   "Insert a POD chunk appropriate after a =POD directive."
3120   (let ((delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3121                      (memq this-command '(self-insert-command newline))))
3122         head1 notlast name p really-delete over)
3123     (and (save-excursion
3124            (forward-word -1)
3125            (and
3126             (eq (preceding-char) ?=)
3127             (progn
3128               (setq head1 (looking-at "head1\\>[ \t]*$"))
3129               (setq over (and (looking-at "over\\>[ \t]*$")
3130                               (not (looking-at "over[ \t]*\n\n\n*=item\\>"))))
3131               (forward-char -1)
3132               (bolp))
3133             (or
3134              (get-text-property (point) 'in-pod)
3135              (cperl-after-expr-p nil "{;:")
3136              (and (re-search-backward
3137                    ;; "\\(\\`\n?\\|\n\n\\)=\\sw+"
3138                    "\\(\\`\n?\\|^\n\\)=\\sw+"
3139                    (point-min) t)
3140                   (not (or
3141                         (looking-at "=cut")
3142                         (and cperl-use-syntax-table-text-property
3143                              (not (eq (get-text-property (point) 'syntax-type)
3144                                       'pod)))))))))
3145          (progn
3146            (save-excursion
3147              (setq notlast (re-search-forward "^\n=" nil t)))
3148            (or notlast
3149                (progn
3150                  (insert "\n\n=cut")
3151                  (cperl-ensure-newlines 2)
3152                  (forward-word -2)
3153                  (if (and head1
3154                           (not
3155                            (save-excursion
3156                              (forward-char -1)
3157                              (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\>"
3158                                                  nil t)))) ; Only one
3159                      (progn
3160                        (forward-word 1)
3161                        (setq name (file-name-sans-extension
3162                                    (file-name-nondirectory (buffer-file-name)))
3163                              p (point))
3164                        (insert " NAME\n\n" name
3165                                " - \n\n=head1 SYNOPSIS\n\n\n\n"
3166                                "=head1 DESCRIPTION")
3167                        (cperl-ensure-newlines 4)
3168                        (goto-char p)
3169                        (forward-word 2)
3170                        (end-of-line)
3171                        (setq really-delete t))
3172                    (forward-word 1))))
3173            (if over
3174                (progn
3175                  (setq p (point))
3176                  (insert "\n\n=item \n\n\n\n"
3177                          "=back")
3178                  (cperl-ensure-newlines 2)
3179                  (goto-char p)
3180                  (forward-word 1)
3181                  (end-of-line)
3182                  (setq really-delete t)))
3183            (if (and delete really-delete)
3184                (cperl-putback-char cperl-del-back-ch))))))
3185
3186 (defun cperl-electric-else ()
3187   "Insert a construction appropriate after a keyword.
3188 Help message may be switched off by setting `cperl-message-electric-keyword'
3189 to nil."
3190   (let ((beg (save-excursion (beginning-of-line) (point))))
3191     (and (save-excursion
3192            (backward-sexp 1)
3193            (cperl-after-expr-p nil "{;:"))
3194          (save-excursion
3195            (not
3196             (re-search-backward
3197              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3198              beg t)))
3199          (save-excursion (or (not (re-search-backward "^=" nil t))
3200                              (looking-at "=cut")
3201                              (and cperl-use-syntax-table-text-property
3202                                   (not (eq (get-text-property (point)
3203                                                               'syntax-type)
3204                                            'pod)))))
3205          (progn
3206            (cperl-indent-line)
3207            ;;(insert " {\n\n}")
3208            (cond
3209             (cperl-extra-newline-before-brace
3210              (insert "\n")
3211              (insert "{")
3212              (cperl-indent-line)
3213              (insert "\n\n}"))
3214             (t
3215              (insert " {\n\n}")))
3216            (or (looking-at "[ \t]\\|$") (insert " "))
3217            (cperl-indent-line)
3218            (forward-line -1)
3219            (cperl-indent-line)
3220            (cperl-putback-char cperl-del-back-ch)
3221            (setq this-command 'cperl-electric-else)
3222            (if cperl-message-electric-keyword
3223                (message "Precede char by C-q to avoid expansion"))))))
3224
3225 (defun cperl-linefeed ()
3226   "Go to end of line, open a new line and indent appropriately.
3227 If in POD, insert appropriate lines."
3228   (interactive)
3229   (let ((beg (save-excursion (beginning-of-line) (point)))
3230         (end (save-excursion (end-of-line) (point)))
3231         (pos (point)) start over cut res)
3232     (if (and                            ; Check if we need to split:
3233                                         ; i.e., on a boundary and inside "{...}"
3234          (save-excursion (cperl-to-comment-or-eol)
3235                          (>= (point) pos)) ; Not in a comment
3236          (or (save-excursion
3237                (skip-chars-backward " \t" beg)
3238                (forward-char -1)
3239                (looking-at "[;{]"))     ; After { or ; + spaces
3240              (looking-at "[ \t]*}")     ; Before }
3241              (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
3242          (save-excursion
3243            (and
3244             (eq (car (parse-partial-sexp pos end -1)) -1)
3245                                         ; Leave the level of parens
3246             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
3247                                         ; Are at end
3248             (cperl-after-block-p (point-min))
3249             (progn
3250               (backward-sexp 1)
3251               (setq start (point-marker))
3252               (<= start pos)))))        ; Redundant?  Are after the
3253                                         ; start of parens group.
3254         (progn
3255           (skip-chars-backward " \t")
3256           (or (memq (preceding-char) (append ";{" nil))
3257               (insert ";"))
3258           (insert "\n")
3259           (forward-line -1)
3260           (cperl-indent-line)
3261           (goto-char start)
3262           (or (looking-at "{[ \t]*$")   ; If there is a statement
3263                                         ; before, move it to separate line
3264               (progn
3265                 (forward-char 1)
3266                 (insert "\n")
3267                 (cperl-indent-line)))
3268           (forward-line 1)              ; We are on the target line
3269           (cperl-indent-line)
3270           (beginning-of-line)
3271           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
3272                                         ; after, move it to separate line
3273               (progn
3274                 (end-of-line)
3275                 (search-backward "}" beg)
3276                 (skip-chars-backward " \t")
3277                 (or (memq (preceding-char) (append ";{" nil))
3278                     (insert ";"))
3279                 (insert "\n")
3280                 (cperl-indent-line)
3281                 (forward-line -1)))
3282           (forward-line -1)             ; We are on the line before target
3283           (end-of-line)
3284           (newline-and-indent))
3285       (end-of-line)                     ; else - no splitting
3286       (cond
3287        ((and (looking-at "\n[ \t]*{$")
3288              (save-excursion
3289                (skip-chars-backward " \t")
3290                (eq (preceding-char) ?\)))) ; Probably if () {} group
3291                                         ; with an extra newline.
3292         (forward-line 2)
3293         (cperl-indent-line))
3294        ((save-excursion                 ; In POD header
3295           (forward-paragraph -1)
3296           ;; (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\b")
3297           ;; We are after \n now, so look for the rest
3298           (if (looking-at "\\(\\`\n?\\|\n\\)=\\sw+")
3299               (progn
3300                 (setq cut (looking-at "\\(\\`\n?\\|\n\\)=cut\\>"))
3301                 (setq over (looking-at "\\(\\`\n?\\|\n\\)=over\\>"))
3302                 t)))
3303         (if (and over
3304                  (progn
3305                    (forward-paragraph -1)
3306                    (forward-word 1)
3307                    (setq pos (point))
3308                    (setq cut (buffer-substring (point)
3309                                                (save-excursion
3310                                                  (end-of-line)
3311                                                  (point))))
3312                    (delete-char (- (save-excursion (end-of-line) (point))
3313                                    (point)))
3314                    (setq res (expand-abbrev))
3315                    (save-excursion
3316                      (goto-char pos)
3317                      (insert cut))
3318                    res))
3319             nil
3320           (cperl-ensure-newlines (if cut 2 4))
3321           (forward-line 2)))
3322        ((get-text-property (point) 'in-pod) ; In POD section
3323         (cperl-ensure-newlines 4)
3324         (forward-line 2))
3325        ((looking-at "\n[ \t]*$")        ; Next line is empty - use it.
3326         (forward-line 1)
3327         (cperl-indent-line))
3328        (t
3329         (newline-and-indent))))))
3330
3331 (defun cperl-electric-semi (arg)
3332   "Insert character and correct line's indentation."
3333   (interactive "P")
3334   (if cperl-auto-newline
3335       (cperl-electric-terminator arg)
3336     (self-insert-command (prefix-numeric-value arg))
3337     (if cperl-autoindent-on-semi
3338         (cperl-indent-line))))
3339
3340 (defun cperl-electric-terminator (arg)
3341   "Insert character and correct line's indentation."
3342   (interactive "P")
3343   (let ((end (point))
3344         (auto (and cperl-auto-newline
3345                    (or (not (eq last-command-char ?:))
3346                        cperl-auto-newline-after-colon)))
3347         insertpos)
3348     (if (and ;;(not arg)
3349              (eolp)
3350              (not (save-excursion
3351                     (beginning-of-line)
3352                     (skip-chars-forward " \t")
3353                     (or
3354                      ;; Ignore in comment lines
3355                      (= (following-char) ?#)
3356                      ;; Colon is special only after a label
3357                      ;; So quickly rule out most other uses of colon
3358                      ;; and do no indentation for them.
3359                      (and (eq last-command-char ?:)
3360                           (save-excursion
3361                             (forward-word 1)
3362                             (skip-chars-forward " \t")
3363                             (and (< (point) end)
3364                                  (progn (goto-char (- end 1))
3365                                         (not (looking-at ":"))))))
3366                      (progn
3367                        (beginning-of-defun)
3368                        (let ((pps (parse-partial-sexp (point) end)))
3369                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
3370         (progn
3371           (self-insert-command (prefix-numeric-value arg))
3372           ;;(forward-char -1)
3373           (if auto (setq insertpos (point-marker)))
3374           ;;(forward-char 1)
3375           (cperl-indent-line)
3376           (if auto
3377               (progn
3378                 (newline)
3379                 (cperl-indent-line)))
3380           (save-excursion
3381             (if insertpos (goto-char (1- (marker-position insertpos)))
3382               (forward-char -1))
3383             (delete-char 1))))
3384     (if insertpos
3385         (save-excursion
3386           (goto-char insertpos)
3387           (self-insert-command (prefix-numeric-value arg)))
3388       (self-insert-command (prefix-numeric-value arg)))))
3389
3390 (defun cperl-electric-backspace (arg)
3391   "Backspace, or remove the whitespace around the point inserted by an electric
3392 key.  Will untabivy if `cperl-electric-backspace-untabify' is non-nil."
3393   (interactive "p")
3394   (if (and cperl-auto-newline
3395            (memq last-command '(cperl-electric-semi
3396                                 cperl-electric-terminator
3397                                 cperl-electric-lbrace))
3398            (memq (preceding-char) '(?\  ?\t ?\n)))
3399       (let (p)
3400         (if (eq last-command 'cperl-electric-lbrace)
3401             (skip-chars-forward " \t\n"))
3402         (setq p (point))
3403         (skip-chars-backward " \t\n")
3404         (delete-region (point) p))
3405     (and (eq last-command 'cperl-electric-else)
3406          ;; We are removing the whitespace *inside* cperl-electric-else
3407          (setq this-command 'cperl-electric-else-really))
3408     (if (and cperl-auto-newline
3409              (eq last-command 'cperl-electric-else-really)
3410              (memq (preceding-char) '(?\  ?\t ?\n)))
3411         (let (p)
3412           (skip-chars-forward " \t\n")
3413           (setq p (point))
3414           (skip-chars-backward " \t\n")
3415           (delete-region (point) p))
3416       (if cperl-electric-backspace-untabify
3417           (backward-delete-char-untabify arg)
3418         (delete-backward-char arg)))))
3419
3420 (defun cperl-inside-parens-p ()
3421   (condition-case ()
3422       (save-excursion
3423         (save-restriction
3424           (narrow-to-region (point)
3425                             (progn (beginning-of-defun) (point)))
3426           (goto-char (point-max))
3427           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
3428     (error nil)))
3429 \f
3430 (defun cperl-indent-command (&optional whole-exp)
3431   "Indent current line as Perl code, or in some cases insert a tab character.
3432 If `cperl-tab-always-indent' is non-nil (the default), always indent current
3433 line.  Otherwise, indent the current line only if point is at the left margin
3434 or in the line's indentation; otherwise insert a tab.
3435
3436 A numeric argument, regardless of its value,
3437 means indent rigidly all the lines of the expression starting after point
3438 so that this line becomes properly indented.
3439 The relative indentation among the lines of the expression are preserved."
3440   (interactive "P")
3441   (cperl-update-syntaxification (point) (point))
3442   (if whole-exp
3443       ;; If arg, always indent this line as Perl
3444       ;; and shift remaining lines of expression the same amount.
3445       (let ((shift-amt (cperl-indent-line))
3446             beg end)
3447         (save-excursion
3448           (if cperl-tab-always-indent
3449               (beginning-of-line))
3450           (setq beg (point))
3451           (forward-sexp 1)
3452           (setq end (point))
3453           (goto-char beg)
3454           (forward-line 1)
3455           (setq beg (point)))
3456         (if (and shift-amt (> end beg))
3457             (indent-code-rigidly beg end shift-amt "#")))
3458     (if (and (not cperl-tab-always-indent)
3459              (save-excursion
3460                (skip-chars-backward " \t")
3461                (not (bolp))))
3462         (insert-tab)
3463       (cperl-indent-line))))
3464
3465 (defun cperl-indent-line (&optional parse-data)
3466   "Indent current line as Perl code.
3467 Return the amount the indentation changed by."
3468   (let ((case-fold-search nil)
3469         (pos (- (point-max) (point)))
3470         indent i beg shift-amt)
3471     (setq indent (cperl-calculate-indent parse-data)
3472           i indent)
3473     (beginning-of-line)
3474     (setq beg (point))
3475     (cond ((or (eq indent nil) (eq indent t))
3476            (setq indent (current-indentation) i nil))
3477           ;;((eq indent t)    ; Never?
3478           ;; (setq indent (cperl-calculate-indent-within-comment)))
3479           ;;((looking-at "[ \t]*#")
3480           ;; (setq indent 0))
3481           (t
3482            (skip-chars-forward " \t")
3483            (if (listp indent) (setq indent (car indent)))
3484            (cond ((looking-at "[A-Za-z_][A-Za-z_0-9]*:[^:]")
3485                   (and (> indent 0)
3486                        (setq indent (max cperl-min-label-indent
3487                                          (+ indent cperl-label-offset)))))
3488                  ((= (following-char) ?})
3489                   (setq indent (- indent cperl-indent-level)))
3490                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
3491                   (setq indent (+ indent cperl-close-paren-offset)))
3492                  ((= (following-char) ?{)
3493                   (setq indent (+ indent cperl-brace-offset))))))
3494     (skip-chars-forward " \t")
3495     (setq shift-amt (and i (- indent (current-column))))
3496     (if (or (not shift-amt)
3497             (zerop shift-amt))
3498         (if (> (- (point-max) pos) (point))
3499             (goto-char (- (point-max) pos)))
3500       (delete-region beg (point))
3501       (indent-to indent)
3502       ;; If initial point was within line's indentation,
3503       ;; position after the indentation.  Else stay at same point in text.
3504       (if (> (- (point-max) pos) (point))
3505           (goto-char (- (point-max) pos))))
3506     shift-amt))
3507
3508 (defun cperl-after-label ()
3509   ;; Returns true if the point is after label.  Does not do save-excursion.
3510   (and (eq (preceding-char) ?:)
3511        (memq (char-syntax (char-after (- (point) 2)))
3512              '(?w ?_))
3513        (progn
3514          (backward-sexp)
3515          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))
3516
3517 (defun cperl-get-state (&optional parse-start start-state)
3518   ;; returns list (START STATE DEPTH PRESTART),
3519   ;; START is a good place to start parsing, or equal to
3520   ;; PARSE-START if preset,
3521   ;; STATE is what is returned by `parse-partial-sexp'.
3522   ;; DEPTH is true is we are immediately after end of block
3523   ;; which contains START.
3524   ;; PRESTART is the position basing on which START was found.
3525   (save-excursion
3526     (let ((start-point (point)) depth state start prestart)
3527       (if (and parse-start
3528                (<= parse-start start-point))
3529           (goto-char parse-start)
3530         (beginning-of-defun)
3531         (setq start-state nil))
3532       (setq prestart (point))
3533       (if start-state nil
3534         ;; Try to go out, if sub is not on the outermost level
3535         (while (< (point) start-point)
3536           (setq start (point) parse-start start depth nil
3537                 state (parse-partial-sexp start start-point -1))
3538           (if (> (car state) -1) nil
3539             ;; The current line could start like }}}, so the indentation
3540             ;; corresponds to a different level than what we reached
3541             (setq depth t)
3542             (beginning-of-line 2)))     ; Go to the next line.
3543         (if start (goto-char start)))   ; Not at the start of file
3544       (setq start (point))
3545       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
3546       (list start state depth prestart))))
3547
3548 (defun cperl-block-p ()            ; Do not C-M-q !  One string contains ";" !
3549   ;; Positions is before ?\{.  Checks whether it starts a block.
3550   ;; No save-excursion!
3551   (cperl-backward-to-noncomment (point-min))
3552   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label!  \C-@ at bobp
3553                                         ; Label may be mixed up with `$blah :'
3554       (save-excursion (cperl-after-label))
3555       (and (memq (char-syntax (preceding-char)) '(?w ?_))
3556            (progn
3557              (backward-sexp)
3558              ;; Need take into account `bless', `return', `tr',...
3559              (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
3560                       (not (looking-at "\\(bless\\|return\\|q[wqrx]?\\|tr\\|[smy]\\)\\>")))
3561                  (progn
3562                    (skip-chars-backward " \t\n\f")
3563                    (and (memq (char-syntax (preceding-char)) '(?w ?_))
3564                         (progn
3565                           (backward-sexp)
3566                           (looking-at
3567                            "sub[ \t]+[a-zA-Z0-9_:]+[ \t\n\f]*\\(([^()]*)[ \t\n\f]*\\)?[#{]")))))))))
3568
3569 (defvar cperl-look-for-prop '((pod in-pod) (here-doc-delim here-doc-group)))
3570
3571 (defun cperl-calculate-indent (&optional parse-data) ; was parse-start
3572   "Return appropriate indentation for current line as Perl code.
3573 In usual case returns an integer: the column to indent to.
3574 Returns nil if line starts inside a string, t if in a comment.
3575
3576 Will not correct the indentation for labels, but will correct it for braces
3577 and closing parentheses and brackets."
3578   (cperl-update-syntaxification (point) (point))
3579   (save-excursion
3580     (if (or
3581          (and (memq (get-text-property (point) 'syntax-type)
3582                     '(pod here-doc here-doc-delim format))
3583               (not (get-text-property (point) 'indentable)))
3584          ;; before start of POD - whitespace found since do not have 'pod!
3585          (and (looking-at "[ \t]*\n=")
3586               (error "Spaces before POD section!"))
3587          (and (not cperl-indent-left-aligned-comments)
3588               (looking-at "^#")))
3589         nil
3590       (beginning-of-line)
3591       (let ((indent-point (point))
3592             (char-after (save-excursion
3593                           (skip-chars-forward " \t")
3594                           (following-char)))
3595             (in-pod (get-text-property (point) 'in-pod))
3596             (pre-indent-point (point))
3597             p prop look-prop is-block delim)
3598         (cond
3599          (in-pod
3600           ;; In the verbatim part, probably code example.  What to do???
3601           )
3602          (t
3603           (save-excursion
3604             ;; Not in POD
3605             (cperl-backward-to-noncomment nil)
3606             (setq p (max (point-min) (1- (point)))
3607                   prop (get-text-property p 'syntax-type)
3608                   look-prop (or (nth 1 (assoc prop cperl-look-for-prop))
3609                                 'syntax-type))
3610             (if (memq prop '(pod here-doc format here-doc-delim))
3611                 (progn
3612                   (goto-char (or (previous-single-property-change p look-prop)
3613                                  (point-min)))
3614                   (beginning-of-line)
3615                   (setq pre-indent-point (point)))))))
3616         (goto-char pre-indent-point)
3617         (let* ((case-fold-search nil)
3618                (s-s (cperl-get-state (car parse-data) (nth 1 parse-data)))
3619                (start (or (nth 2 parse-data)
3620                           (nth 0 s-s)))
3621                (state (nth 1 s-s))
3622                (containing-sexp (car (cdr state)))
3623                old-indent)
3624           (if (and
3625                ;;containing-sexp                ;; We are buggy at toplevel :-(
3626                parse-data)
3627               (progn
3628                 (setcar parse-data pre-indent-point)
3629                 (setcar (cdr parse-data) state)
3630                 (or (nth 2 parse-data)
3631                     (setcar (cddr parse-data) start))
3632                 ;; Before this point: end of statement
3633                 (setq old-indent (nth 3 parse-data))))
3634           (cond ((get-text-property (point) 'indentable)
3635                  ;; indent to just after the surrounding open,
3636                  ;; skip blanks if we do not close the expression.
3637                  (goto-char (1+ (previous-single-property-change (point) 'indentable)))
3638                  (or (memq char-after (append ")]}" nil))
3639                      (looking-at "[ \t]*\\(#\\|$\\)")
3640                      (skip-chars-forward " \t"))
3641                  (current-column))
3642                 ((or (nth 3 state) (nth 4 state))
3643                  ;; return nil or t if should not change this line
3644                  (nth 4 state))
3645                 ;; XXXX Do we need to special-case this?
3646                 ((null containing-sexp)
3647                  ;; Line is at top level.  May be data or function definition,
3648                  ;; or may be function argument declaration.
3649                  ;; Indent like the previous top level line
3650                  ;; unless that ends in a closeparen without semicolon,
3651                  ;; in which case this line is the first argument decl.
3652                  (skip-chars-forward " \t")
3653                  (+ (save-excursion
3654                       (goto-char start)
3655                       (- (current-indentation)
3656                          (if (nth 2 s-s) cperl-indent-level 0)))
3657                     (if (= char-after ?{) cperl-continued-brace-offset 0)
3658                     (progn
3659                       (cperl-backward-to-noncomment (or old-indent (point-min)))
3660                       ;; Look at previous line that's at column 0
3661                       ;; to determine whether we are in top-level decls
3662                       ;; or function's arg decls.  Set basic-indent accordingly.
3663                       ;; Now add a little if this is a continuation line.
3664                       (if (or (bobp)
3665                               (eq (point) old-indent) ; old-indent was at comment
3666                               (eq (preceding-char) ?\;)
3667                               ;;  Had ?\) too
3668                               (and (eq (preceding-char) ?\})
3669                                    (cperl-after-block-and-statement-beg
3670                                     (point-min))) ; Was start - too close
3671                               (memq char-after (append ")]}" nil))
3672                               (and (eq (preceding-char) ?\:) ; label
3673                                    (progn
3674                                      (forward-sexp -1)
3675                                      (skip-chars-backward " \t")
3676                                      (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*[ \t]*:")))
3677                               (get-text-property (point) 'first-format-line))
3678                           (progn
3679                             (if (and parse-data
3680                                      (not (eq char-after ?\C-j)))
3681                                 (setcdr (cddr parse-data)
3682                                         (list pre-indent-point)))
3683                             0)
3684                         cperl-continued-statement-offset))))
3685                 ((not
3686                   (or (setq is-block
3687                             (and (setq delim (= (char-after containing-sexp) ?{))
3688                                  (save-excursion ; Is it a hash?
3689                                    (goto-char containing-sexp)
3690                                    (cperl-block-p))))
3691                       cperl-indent-parens-as-block))
3692                  ;; group is an expression, not a block:
3693                  ;; indent to just after the surrounding open parens,
3694                  ;; skip blanks if we do not close the expression.
3695                  (goto-char (1+ containing-sexp))
3696                  (or (memq char-after
3697                            (append (if delim "}" ")]}") nil))
3698                      (looking-at "[ \t]*\\(#\\|$\\)")
3699                      (skip-chars-forward " \t"))
3700                  (+ (current-column)
3701                     (if (and delim
3702                              (eq char-after ?\}))
3703                         ;; Correct indentation of trailing ?\}
3704                         (+ cperl-indent-level cperl-close-paren-offset)
3705                       0)))
3706 ;;;           ((and (/= (char-after containing-sexp) ?{)
3707 ;;;                 (not cperl-indent-parens-as-block))
3708 ;;;            ;; line is expression, not statement:
3709 ;;;            ;; indent to just after the surrounding open,
3710 ;;;            ;; skip blanks if we do not close the expression.
3711 ;;;            (goto-char (1+ containing-sexp))
3712 ;;;            (or (memq char-after (append ")]}" nil))
3713 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
3714 ;;;                (skip-chars-forward " \t"))
3715 ;;;            (current-column))
3716 ;;;           ((progn
3717 ;;;              ;; Containing-expr starts with \{.  Check whether it is a hash.
3718 ;;;              (goto-char containing-sexp)
3719 ;;;              (and (not (cperl-block-p))
3720 ;;;                   (not cperl-indent-parens-as-block)))
3721 ;;;            (goto-char (1+ containing-sexp))
3722 ;;;            (or (eq char-after ?\})
3723 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
3724 ;;;                (skip-chars-forward " \t"))
3725 ;;;            (+ (current-column)      ; Correct indentation of trailing ?\}
3726 ;;;               (if (eq char-after ?\}) (+ cperl-indent-level
3727 ;;;                                          cperl-close-paren-offset)
3728 ;;;                 0)))
3729                 (t
3730                  ;; Statement level.  Is it a continuation or a new statement?
3731                  ;; Find previous non-comment character.
3732                  (goto-char pre-indent-point)
3733                  (cperl-backward-to-noncomment containing-sexp)
3734                  ;; Back up over label lines, since they don't
3735                  ;; affect whether our line is a continuation.
3736                  ;; (Had \, too)
3737                  (while ;;(or (eq (preceding-char) ?\,)
3738                      (and (eq (preceding-char) ?:)
3739                           (or ;;(eq (char-after (- (point) 2)) ?\') ; ????
3740                            (memq (char-syntax (char-after (- (point) 2)))
3741                                  '(?w ?_))))
3742                    ;;)
3743                    (if (eq (preceding-char) ?\,)
3744                        ;; Will go to beginning of line, essentially.
3745                        ;; Will ignore embedded sexpr XXXX.
3746                        (cperl-backward-to-start-of-continued-exp containing-sexp))
3747                    (beginning-of-line)
3748                    (cperl-backward-to-noncomment containing-sexp))
3749                  ;; Now we get the answer.
3750                  (if (not (or (eq (1- (point)) containing-sexp)
3751                               (memq (preceding-char)
3752                                     (append (if is-block " ;{" " ,;{") '(nil)))
3753                               (and (eq (preceding-char) ?\})
3754                                    (cperl-after-block-and-statement-beg
3755                                     containing-sexp))
3756                               (get-text-property (point) 'first-format-line)))
3757                      ;; This line is continuation of preceding line's statement;
3758                      ;; indent  `cperl-continued-statement-offset'  more than the
3759                      ;; previous line of the statement.
3760                      ;;
3761                      ;; There might be a label on this line, just
3762                      ;; consider it bad style and ignore it.
3763                      (progn
3764                        (cperl-backward-to-start-of-continued-exp containing-sexp)
3765                        (+ (if (memq char-after (append "}])" nil))
3766                               0         ; Closing parenth
3767                             cperl-continued-statement-offset)
3768                           (if (or is-block
3769                                   (not delim)
3770                                   (not (eq char-after ?\})))
3771                               0
3772                             ;; Now it is a hash reference
3773                             (+ cperl-indent-level cperl-close-paren-offset))
3774                           (if (looking-at "\\w+[ \t]*:")
3775                               (if (> (current-indentation) cperl-min-label-indent)
3776                                   (- (current-indentation) cperl-label-offset)
3777                                 ;; Do not move `parse-data', this should
3778                                 ;; be quick anyway (this comment comes
3779                                 ;; from different location):
3780                                 (cperl-calculate-indent))
3781                             (current-column))
3782                           (if (eq char-after ?\{)
3783                               cperl-continued-brace-offset 0)))
3784                    ;; This line starts a new statement.
3785                    ;; Position following last unclosed open.
3786                    (goto-char containing-sexp)
3787                    ;; Is line first statement after an open-brace?
3788                    (or
3789                     ;; If no, find that first statement and indent like
3790                     ;; it.  If the first statement begins with label, do
3791                     ;; not believe when the indentation of the label is too
3792                     ;; small.
3793                     (save-excursion
3794                       (forward-char 1)
3795                       (setq old-indent (current-indentation))
3796                       (let ((colon-line-end 0))
3797                         (while
3798                             (progn (skip-chars-forward " \t\n")
3799                                    (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]\\|=[a-zA-Z]"))
3800                           ;; Skip over comments and labels following openbrace.
3801                           (cond ((= (following-char) ?\#)
3802                                  (forward-line 1))
3803                                 ((= (following-char) ?\=)
3804                                  (goto-char
3805                                   (or (next-single-property-change (point) 'in-pod)
3806                                       (point-max)))) ; do not loop if no syntaxification
3807                                 ;; label:
3808                                 (t
3809                                  (save-excursion (end-of-line)
3810                                                  (setq colon-line-end (point)))
3811                                  (search-forward ":"))))
3812                         ;; The first following code counts
3813                         ;; if it is before the line we want to indent.
3814                         (and (< (point) indent-point)
3815                              (if (> colon-line-end (point)) ; After label
3816                                  (if (> (current-indentation)
3817                                         cperl-min-label-indent)
3818                                      (- (current-indentation) cperl-label-offset)
3819                                    ;; Do not believe: `max' is involved
3820                                    (+ old-indent cperl-indent-level))
3821                                (current-column)))))
3822                     ;; If no previous statement,
3823                     ;; indent it relative to line brace is on.
3824                     ;; For open brace in column zero, don't let statement
3825                     ;; start there too.  If cperl-indent-level is zero,
3826                     ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
3827                     ;; For open-braces not the first thing in a line,
3828                     ;; add in cperl-brace-imaginary-offset.
3829
3830                     ;; If first thing on a line:  ?????
3831                     (+ (if (and (bolp) (zerop cperl-indent-level))
3832                            (+ cperl-brace-offset cperl-continued-statement-offset)
3833                          cperl-indent-level)
3834                        (if (or is-block
3835                                (not delim)
3836                                (not (eq char-after ?\})))
3837                            0
3838                          ;; Now it is a hash reference
3839                          (+ cperl-indent-level cperl-close-paren-offset))
3840                        ;; Move back over whitespace before the openbrace.
3841                        ;; If openbrace is not first nonwhite thing on the line,
3842                        ;; add the cperl-brace-imaginary-offset.
3843                        (progn (skip-chars-backward " \t")
3844                               (if (bolp) 0 cperl-brace-imaginary-offset))
3845                        ;; If the openbrace is preceded by a parenthesized exp,
3846                        ;; move to the beginning of that;
3847                        ;; possibly a different line
3848                        (progn
3849                          (if (eq (preceding-char) ?\))
3850                              (forward-sexp -1))
3851                          ;; In the case it starts a subroutine, indent with
3852                          ;; respect to `sub', not with respect to the
3853                          ;; first thing on the line, say in the case of
3854                          ;; anonymous sub in a hash.
3855                          ;;
3856                          (skip-chars-backward " \t")
3857                          (if (and (eq (preceding-char) ?b)
3858                                   (progn
3859                                     (forward-sexp -1)
3860                                     (looking-at "sub\\>"))
3861                                   (setq old-indent
3862                                         (nth 1
3863                                              (parse-partial-sexp
3864                                               (save-excursion (beginning-of-line) (point))
3865                                               (point)))))
3866                              (progn (goto-char (1+ old-indent))
3867                                     (skip-chars-forward " \t")
3868                                     (current-column))
3869                            ;; Get initial indentation of the line we are on.
3870                            ;; If line starts with label, calculate label indentation
3871                            (if (save-excursion
3872                                  (beginning-of-line)
3873                                  (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
3874                                (if (> (current-indentation) cperl-min-label-indent)
3875                                    (- (current-indentation) cperl-label-offset)
3876                                  ;; Do not move `parse-data', this should
3877                                  ;; be quick anyway:
3878                                  (cperl-calculate-indent))
3879                              (current-indentation))))))))))))))
3880
3881 (defvar cperl-indent-alist
3882   '((string nil)
3883     (comment nil)
3884     (toplevel 0)
3885     (toplevel-after-parenth 2)
3886     (toplevel-continued 2)
3887     (expression 1))
3888   "Alist of indentation rules for CPerl mode.
3889 The values mean:
3890   nil: do not indent;
3891   number: add this amount of indentation.
3892
3893 Not finished, not used.")
3894
3895 (defun cperl-where-am-i (&optional parse-start start-state)
3896   ;; Unfinished
3897   "Return a list of lists ((TYPE POS)...) of good points before the point.
3898 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'.
3899
3900 Not finished, not used."
3901   (save-excursion
3902     (let* ((start-point (point))
3903            (s-s (cperl-get-state))
3904            (start (nth 0 s-s))
3905            (state (nth 1 s-s))
3906            (prestart (nth 3 s-s))
3907            (containing-sexp (car (cdr state)))
3908            (case-fold-search nil)
3909            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
3910       (cond ((nth 3 state)              ; In string
3911              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
3912             ((nth 4 state)              ; In comment
3913              (setq res (cons '(comment) res)))
3914             ((null containing-sexp)
3915              ;; Line is at top level.
3916              ;; Indent like the previous top level line
3917              ;; unless that ends in a closeparen without semicolon,
3918              ;; in which case this line is the first argument decl.
3919              (cperl-backward-to-noncomment (or parse-start (point-min)))
3920              ;;(skip-chars-backward " \t\f\n")
3921              (cond
3922               ((or (bobp)
3923                    (memq (preceding-char) (append ";}" nil)))
3924                (setq res (cons (list 'toplevel start) res)))
3925               ((eq (preceding-char) ?\) )
3926                (setq res (cons (list 'toplevel-after-parenth start) res)))
3927               (t
3928                (setq res (cons (list 'toplevel-continued start) res)))))
3929             ((/= (char-after containing-sexp) ?{)
3930              ;; line is expression, not statement:
3931              ;; indent to just after the surrounding open.
3932              ;; skip blanks if we do not close the expression.
3933              (setq res (cons (list 'expression-blanks
3934                                    (progn
3935                                      (goto-char (1+ containing-sexp))
3936                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
3937                                          (skip-chars-forward " \t"))
3938                                      (point)))
3939                              (cons (list 'expression containing-sexp) res))))
3940             ((progn
3941                ;; Containing-expr starts with \{.  Check whether it is a hash.
3942                (goto-char containing-sexp)
3943                (not (cperl-block-p)))
3944              (setq res (cons (list 'expression-blanks
3945                                    (progn
3946                                      (goto-char (1+ containing-sexp))
3947                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
3948                                          (skip-chars-forward " \t"))
3949                                      (point)))
3950                              (cons (list 'expression containing-sexp) res))))
3951             (t
3952              ;; Statement level.
3953              (setq res (cons (list 'in-block containing-sexp) res))
3954              ;; Is it a continuation or a new statement?
3955              ;; Find previous non-comment character.
3956              (cperl-backward-to-noncomment containing-sexp)
3957              ;; Back up over label lines, since they don't
3958              ;; affect whether our line is a continuation.
3959              ;; Back up comma-delimited lines too ?????
3960              (while (or (eq (preceding-char) ?\,)
3961                         (save-excursion (cperl-after-label)))
3962                (if (eq (preceding-char) ?\,)
3963                    ;; Will go to beginning of line, essentially
3964                    ;; Will ignore embedded sexpr XXXX.
3965                    (cperl-backward-to-start-of-continued-exp containing-sexp))
3966                (beginning-of-line)
3967                (cperl-backward-to-noncomment containing-sexp))
3968              ;; Now we get the answer.
3969              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
3970                  ;; This line is continuation of preceding line's statement.
3971                  (list (list 'statement-continued containing-sexp))
3972                ;; This line starts a new statement.
3973                ;; Position following last unclosed open.
3974                (goto-char containing-sexp)
3975                ;; Is line first statement after an open-brace?
3976                (or
3977                 ;; If no, find that first statement and indent like
3978                 ;; it.  If the first statement begins with label, do
3979                 ;; not believe when the indentation of the label is too
3980                 ;; small.
3981                 (save-excursion
3982                   (forward-char 1)
3983                   (let ((colon-line-end 0))
3984                     (while (progn (skip-chars-forward " \t\n" start-point)
3985                                   (and (< (point) start-point)
3986                                        (looking-at
3987                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
3988                       ;; Skip over comments and labels following openbrace.
3989                       (cond ((= (following-char) ?\#)
3990                              ;;(forward-line 1)
3991                              (end-of-line))
3992                             ;; label:
3993                             (t
3994                              (save-excursion (end-of-line)
3995                                              (setq colon-line-end (point)))
3996                              (search-forward ":"))))
3997                     ;; Now at the point, after label, or at start
3998                     ;; of first statement in the block.
3999                     (and (< (point) start-point)
4000                          (if (> colon-line-end (point))
4001                              ;; Before statement after label
4002                              (if (> (current-indentation)
4003                                     cperl-min-label-indent)
4004                                  (list (list 'label-in-block (point)))
4005                                ;; Do not believe: `max' is involved
4006                                (list
4007                                 (list 'label-in-block-min-indent (point))))
4008                            ;; Before statement
4009                            (list 'statement-in-block (point))))))
4010                 ;; If no previous statement,
4011                 ;; indent it relative to line brace is on.
4012                 ;; For open brace in column zero, don't let statement
4013                 ;; start there too.  If cperl-indent-level is zero,
4014                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
4015                 ;; For open-braces not the first thing in a line,
4016                 ;; add in cperl-brace-imaginary-offset.
4017
4018                 ;; If first thing on a line:  ?????
4019                 (+ (if (and (bolp) (zerop cperl-indent-level))
4020                        (+ cperl-brace-offset cperl-continued-statement-offset)
4021                      cperl-indent-level)
4022                    ;; Move back over whitespace before the openbrace.
4023                    ;; If openbrace is not first nonwhite thing on the line,
4024                    ;; add the cperl-brace-imaginary-offset.
4025                    (progn (skip-chars-backward " \t")
4026                           (if (bolp) 0 cperl-brace-imaginary-offset))
4027                    ;; If the openbrace is preceded by a parenthesized exp,
4028                    ;; move to the beginning of that;
4029                    ;; possibly a different line
4030                    (progn
4031                      (if (eq (preceding-char) ?\))
4032                          (forward-sexp -1))
4033                      ;; Get initial indentation of the line we are on.
4034                      ;; If line starts with label, calculate label indentation
4035                      (if (save-excursion
4036                            (beginning-of-line)
4037                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
4038                          (if (> (current-indentation) cperl-min-label-indent)
4039                              (- (current-indentation) cperl-label-offset)
4040                            (cperl-calculate-indent))
4041                        (current-indentation))))))))
4042       res)))
4043
4044 (defun cperl-calculate-indent-within-comment ()
4045   "Return the indentation amount for line, assuming that
4046 the current line is to be regarded as part of a block comment."
4047   (let (end star-start)
4048     (save-excursion
4049       (beginning-of-line)
4050       (skip-chars-forward " \t")
4051       (setq end (point))
4052       (and (= (following-char) ?#)
4053            (forward-line -1)
4054            (cperl-to-comment-or-eol)
4055            (setq end (point)))
4056       (goto-char end)
4057       (current-column))))
4058
4059
4060 (defun cperl-to-comment-or-eol ()
4061   "Go to position before comment on the current line, or to end of line.
4062 Returns true if comment is found."
4063   (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
4064     (beginning-of-line)
4065     (if (or
4066          (eq (get-text-property (point) 'syntax-type) 'pod)
4067          (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t))
4068         (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
4069       ;; Else
4070       (while (not stop-in)
4071         (setq state (parse-partial-sexp (point) lim nil nil nil t))
4072                                         ; stop at comment
4073         ;; If fails (beginning-of-line inside sexp), then contains not-comment
4074         (if (nth 4 state)               ; After `#';
4075                                         ; (nth 2 state) can be
4076                                         ; beginning of m,s,qq and so
4077                                         ; on
4078             (if (nth 2 state)
4079                 (progn
4080                   (setq cpoint (point))
4081                   (goto-char (nth 2 state))
4082                   (cond
4083                    ((looking-at "\\(s\\|tr\\)\\>")
4084                     (or (re-search-forward
4085                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
4086                          lim 'move)
4087                         (setq stop-in t)))
4088                    ((looking-at "\\(m\\|q\\([qxwr]\\)?\\)\\>")
4089                     (or (re-search-forward
4090                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
4091                          lim 'move)
4092                         (setq stop-in t)))
4093                    (t                   ; It was fair comment
4094                     (setq stop-in t)    ; Finish
4095                     (goto-char (1- cpoint)))))
4096               (setq stop-in t)          ; Finish
4097               (forward-char -1))
4098           (setq stop-in t)))            ; Finish 
4099       (nth 4 state))))
4100
4101 (defsubst cperl-1- (p)
4102   (max (point-min) (1- p)))
4103
4104 (defsubst cperl-1+ (p)
4105   (min (point-max) (1+ p)))
4106
4107 (defsubst cperl-modify-syntax-type (at how)
4108   (if (< at (point-max))
4109       (progn
4110         (put-text-property at (1+ at) 'syntax-table how)
4111         (put-text-property at (1+ at) 'rear-nonsticky t))))
4112
4113 (defun cperl-protect-defun-start (s e)
4114   ;; C code looks for "^\\s(" to skip comment backward in "hard" situations
4115   (save-excursion
4116     (goto-char s)
4117     (while (re-search-forward "^\\s(" e 'to-end)
4118       (put-text-property (1- (point)) (point) 'syntax-table cperl-st-punct))))
4119
4120 (defun cperl-commentify (bb e string &optional noface)
4121   (if cperl-use-syntax-table-text-property
4122       (if (eq noface 'n)                ; Only immediate
4123           nil
4124         ;; We suppose that e is _after_ the end of construction, as after eol.
4125         (setq string (if string cperl-st-sfence cperl-st-cfence))
4126         (if (> bb (- e 2))
4127             ;; one-char string/comment?!
4128             (cperl-modify-syntax-type bb cperl-st-punct)
4129           (cperl-modify-syntax-type bb string)
4130           (cperl-modify-syntax-type (1- e) string))
4131         (if (and (eq string cperl-st-sfence) (> (- e 2) bb))
4132             (put-text-property (1+ bb) (1- e)
4133                                'syntax-table cperl-string-syntax-table))
4134         (cperl-protect-defun-start bb e))
4135     ;; Fontify
4136     (or noface
4137         (not cperl-pod-here-fontify)
4138         (put-text-property bb e 'face (if string 'font-lock-string-face
4139                                         'font-lock-comment-face)))))
4140
4141 (defvar cperl-starters '(( ?\( . ?\) )
4142                          ( ?\[ . ?\] )
4143                          ( ?\{ . ?\} )
4144                          ( ?\< . ?\> )))
4145
4146 (defun cperl-forward-re (lim end is-2arg set-st st-l err-l argument
4147                              &optional ostart oend)
4148   ;; Works *before* syntax recognition is done
4149   ;; May modify syntax-type text property if the situation is too hard
4150   (let (b starter ender st i i2 go-forward reset-st)
4151     (skip-chars-forward " \t")
4152     ;; ender means matching-char matcher.
4153     (setq b (point)
4154           starter (if (eobp) 0 (char-after b))
4155           ender (cdr (assoc starter cperl-starters)))
4156     ;; What if starter == ?\\  ????
4157     (if set-st
4158         (if (car st-l)
4159             (setq st (car st-l))
4160           (setcar st-l (make-syntax-table))
4161           (setq i 0 st (car st-l))
4162           (while (< i 256)
4163             (modify-syntax-entry i "." st)
4164             (setq i (1+ i)))
4165           (modify-syntax-entry ?\\ "\\" st)))
4166     (setq set-st t)
4167     ;; Whether we have an intermediate point
4168     (setq i nil)
4169     ;; Prepare the syntax table:
4170     (and set-st
4171          (if (not ender)                ; m/blah/, s/x//, s/x/y/
4172              (modify-syntax-entry starter "$" st)
4173            (modify-syntax-entry starter (concat "(" (list ender)) st)
4174            (modify-syntax-entry ender  (concat ")" (list starter)) st)))
4175     (condition-case bb
4176         (progn
4177           ;; We use `$' syntax class to find matching stuff, but $$
4178           ;; is recognized the same as $, so we need to check this manually.
4179           (if (and (eq starter (char-after (cperl-1+ b)))
4180                    (not ender))
4181               ;; $ has TeXish matching rules, so $$ equiv $...
4182               (forward-char 2)
4183             (setq reset-st (syntax-table))
4184             (set-syntax-table st)
4185             (forward-sexp 1)
4186             (if (<= (point) (1+ b))
4187                 (error "Unfinished regular expression"))
4188             (set-syntax-table reset-st)
4189             (setq reset-st nil)
4190             ;; Now the problem is with m;blah;;
4191             (and (not ender)
4192                  (eq (preceding-char)
4193                      (char-after (- (point) 2)))
4194                  (save-excursion
4195                    (forward-char -2)
4196                    (= 0 (% (skip-chars-backward "\\\\") 2)))
4197                  (forward-char -1)))
4198           ;; Now we are after the first part.
4199           (and is-2arg                  ; Have trailing part
4200                (not ender)
4201                (eq (following-char) starter) ; Empty trailing part
4202                (progn
4203                  (or (eq (char-syntax (following-char)) ?.)
4204                      ;; Make trailing letter into punctuation
4205                      (cperl-modify-syntax-type (point) cperl-st-punct))
4206                  (setq is-2arg nil go-forward t))) ; Ignore the tail
4207           (if is-2arg                   ; Not number => have second part
4208               (progn
4209                 (setq i (point) i2 i)
4210                 (if ender
4211                     (if (memq (following-char) '(?\  ?\t ?\n ?\f))
4212                         (progn
4213                           (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4214                               (goto-char (match-end 0))
4215                             (skip-chars-forward " \t\n\f"))
4216                           (setq i2 (point))))
4217                   (forward-char -1))
4218                 (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4219                 (if ender (modify-syntax-entry ender "." st))
4220                 (setq set-st nil)
4221                 (setq ender (cperl-forward-re lim end nil t st-l err-l
4222                                               argument starter ender)
4223                       ender (nth 2 ender)))))
4224       (error (goto-char lim)
4225              (setq set-st nil)
4226              (if reset-st
4227                  (set-syntax-table reset-st))
4228              (or end
4229                  (message
4230                   "End of `%s%s%c ... %c' string/RE not found: %s"
4231                   argument
4232                   (if ostart (format "%c ... %c" ostart (or oend ostart)) "")
4233                   starter (or ender starter) bb)
4234                  (or (car err-l) (setcar err-l b)))))
4235     (if set-st
4236         (progn
4237           (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4238           (if ender (modify-syntax-entry ender "." st))))
4239     ;; i: have 2 args, after end of the first arg
4240     ;; i2: start of the second arg, if any (before delim iff `ender').
4241     ;; ender: the last arg bounded by parens-like chars, the second one of them
4242     ;; starter: the starting delimiter of the first arg
4243     ;; go-forward: has 2 args, and the second part is empty
4244     (list i i2 ender starter go-forward)))
4245
4246 (defvar font-lock-string-face)
4247 ;;(defvar font-lock-reference-face)
4248 (defvar font-lock-constant-face)
4249 (defsubst cperl-postpone-fontification (b e type val &optional now)
4250   ;; Do after syntactic fontification?
4251   (if cperl-syntaxify-by-font-lock
4252       (or now (put-text-property b e 'cperl-postpone (cons type val)))
4253     (put-text-property b e type val)))
4254
4255 ;;; Here is how the global structures (those which cannot be
4256 ;;; recognized locally) are marked:
4257 ;;      a) PODs:
4258 ;;              Start-to-end is marked `in-pod' ==> t
4259 ;;              Each non-literal part is marked `syntax-type' ==> `pod'
4260 ;;              Each literal part is marked `syntax-type' ==> `in-pod'
4261 ;;      b) HEREs:
4262 ;;              Start-to-end is marked `here-doc-group' ==> t
4263 ;;              The body is marked `syntax-type' ==> `here-doc'
4264 ;;              The delimiter is marked `syntax-type' ==> `here-doc-delim'
4265 ;;      c) FORMATs:
4266 ;;              First line (to =) marked `first-format-line' ==> t
4267 ;;              After-this--to-end is marked `syntax-type' ==> `format'
4268 ;;      d) 'Q'uoted string:
4269 ;;              part between markers inclusive is marked `syntax-type' ==> `string'
4270 ;;              part between `q' and the first marker is marked `syntax-type' ==> `prestring'
4271
4272 (defun cperl-unwind-to-safe (before &optional end)
4273   ;; if BEFORE, go to the previous start-of-line on each step of unwinding
4274   (let ((pos (point)) opos)
4275     (setq opos pos)
4276     (while (and pos (get-text-property pos 'syntax-type))
4277       (setq pos (previous-single-property-change pos 'syntax-type))
4278       (if pos
4279           (if before
4280               (progn
4281                 (goto-char (cperl-1- pos))
4282                 (beginning-of-line)
4283                 (setq pos (point)))
4284             (goto-char (setq pos (cperl-1- pos))))
4285         ;; Up to the start
4286         (goto-char (point-min))))
4287     ;; Skip empty lines
4288     (and (looking-at "\n*=")
4289          (/= 0 (skip-chars-backward "\n"))
4290          (forward-char))
4291     (setq pos (point))
4292     (if end
4293         ;; Do the same for end, going small steps
4294         (progn
4295           (while (and end (get-text-property end 'syntax-type))
4296             (setq pos end
4297                   end (next-single-property-change end 'syntax-type)))
4298           (or end pos)))))
4299
4300 (defvar cperl-nonoverridable-face)
4301 (defvar font-lock-function-name-face)
4302 (defvar font-lock-comment-face)
4303
4304 (defun cperl-find-pods-heres (&optional min max non-inter end ignore-max)
4305   "Scans the buffer for hard-to-parse Perl constructions.
4306 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify
4307 the sections using `cperl-pod-head-face', `cperl-pod-face',
4308 `cperl-here-face'."
4309   (interactive)
4310   (or min (setq min (point-min)
4311                 cperl-syntax-state nil
4312                 cperl-syntax-done-to min))
4313   (or max (setq max (point-max)))
4314   (let* ((cperl-pod-here-fontify (eval cperl-pod-here-fontify)) go tmpend
4315          face head-face here-face b e bb tag qtag b1 e1 argument i c tail tb
4316          is-REx is-x-REx REx-comment-start REx-comment-end was-comment i2
4317          (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
4318          (modified (buffer-modified-p))
4319          (after-change-functions nil)
4320          (use-syntax-state (and cperl-syntax-state
4321                                 (>= min (car cperl-syntax-state))))
4322          (state-point (if use-syntax-state
4323                           (car cperl-syntax-state)
4324                         (point-min)))
4325          (state (if use-syntax-state
4326                     (cdr cperl-syntax-state)))
4327          ;; (st-l '(nil)) (err-l '(nil)) ; Would overwrite - propagates from a function call to a function call!
4328          (st-l (list nil)) (err-l (list nil))
4329          ;; Somehow font-lock may be not loaded yet...
4330          (font-lock-string-face (if (boundp 'font-lock-string-face)
4331                                     font-lock-string-face
4332                                   'font-lock-string-face))
4333          (font-lock-constant-face (if (boundp 'font-lock-constant-face)
4334                                       font-lock-constant-face
4335                                     'font-lock-constant-face))
4336          (font-lock-function-name-face
4337           (if (boundp 'font-lock-function-name-face)
4338               font-lock-function-name-face
4339             'font-lock-function-name-face))
4340          (font-lock-comment-face
4341           (if (boundp 'font-lock-comment-face)
4342               font-lock-comment-face
4343             'font-lock-comment-face))
4344          (cperl-nonoverridable-face
4345           (if (boundp 'cperl-nonoverridable-face)
4346               cperl-nonoverridable-face
4347             'cperl-nonoverridable-face))
4348          (stop-point (if ignore-max
4349                          (point-max)
4350                        max))
4351          (search
4352           (concat
4353            "\\(\\`\n?\\|^\n\\)="
4354            "\\|"
4355            ;; One extra () before this:
4356            "<<"
4357            "\\("                        ; 1 + 1
4358            ;; First variant "BLAH" or just ``.
4359            "[ \t]*"                     ; Yes, whitespace is allowed!
4360            "\\([\"'`]\\)"               ; 2 + 1 = 3
4361            "\\([^\"'`\n]*\\)"           ; 3 + 1
4362            "\\3"
4363            "\\|"
4364            ;; Second variant: Identifier or \ID (same as 'ID') or empty
4365            "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
4366            ;; Do not have <<= or << 30 or <<30 or << $blah.
4367            ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
4368            "\\(\\)"             ; To preserve count of pars :-( 6 + 1
4369            "\\)"
4370            "\\|"
4371            ;; 1+6 extra () before this:
4372            "^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
4373            (if cperl-use-syntax-table-text-property
4374                (concat
4375                 "\\|"
4376                 ;; 1+6+2=9 extra () before this:
4377                 "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>"
4378                 "\\|"
4379                 ;; 1+6+2+1=10 extra () before this:
4380                 "\\([?/<]\\)"   ; /blah/ or ?blah? or <file*glob>
4381                 "\\|"
4382                 ;; 1+6+2+1+1=11 extra () before this:
4383                 "\\<sub\\>[ \t]*\\([a-zA-Z_:'0-9]+[ \t]*\\)?\\(([^()]*)\\)"
4384                 "\\|"
4385                 ;; 1+6+2+1+1+2=13 extra () before this:
4386                 "\\$\\(['{]\\)"
4387                 "\\|"
4388                 ;; 1+6+2+1+1+2+1=14 extra () before this:
4389                 "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'"
4390                 ;; 1+6+2+1+1+2+1+1=15 extra () before this:
4391                 "\\|"
4392                 "__\\(END\\|DATA\\)__"
4393                 ;; 1+6+2+1+1+2+1+1+1=16 extra () before this:
4394                 "\\|"
4395                 "\\\\\\(['`\"($]\\)")
4396              ""))))
4397     (unwind-protect
4398         (progn
4399           (save-excursion
4400             (or non-inter
4401                 (message "Scanning for \"hard\" Perl constructions..."))
4402             (and cperl-pod-here-fontify
4403                  ;; We had evals here, do not know why...
4404                  (setq face cperl-pod-face
4405                        head-face cperl-pod-head-face
4406                        here-face cperl-here-face))
4407             (remove-text-properties min max
4408                                     '(syntax-type t in-pod t syntax-table t
4409                                                   cperl-postpone t
4410                                                   syntax-subtype t
4411                                                   rear-nonsticky t
4412                                                   here-doc-group t
4413                                                   first-format-line t
4414                                                   indentable t))
4415             ;; Need to remove face as well...
4416             (goto-char min)
4417             (and (eq system-type 'emx)
4418                  (looking-at "extproc[ \t]") ; Analogue of #!
4419                  (cperl-commentify min
4420                                    (save-excursion (end-of-line) (point))
4421                                    nil))
4422             (while (and
4423                     (< (point) max)
4424                     (re-search-forward search max t))
4425               (setq tmpend nil)         ; Valid for most cases
4426               (cond
4427                ((match-beginning 1)     ; POD section
4428                 ;;  "\\(\\`\n?\\|^\n\\)="
4429                 (if (looking-at "cut\\>")
4430                     (if ignore-max
4431                         nil             ; Doing a chunk only
4432                       (message "=cut is not preceded by a POD section")
4433                       (or (car err-l) (setcar err-l (point))))
4434                   (beginning-of-line)
4435
4436                   (setq b (point)
4437                         bb b
4438                         tb (match-beginning 0)
4439                         b1 nil)         ; error condition
4440                   ;; We do not search to max, since we may be called from
4441                   ;; some hook of fontification, and max is random
4442                   (or (re-search-forward "^\n=cut\\>" stop-point 'toend)
4443                       (progn
4444                         (goto-char b)
4445                         (if (re-search-forward "\n=cut\\>" stop-point 'toend)
4446                             (progn
4447                               (message "=cut is not preceded by an empty line")
4448                               (setq b1 t)
4449                               (or (car err-l) (setcar err-l b))))))
4450                   (beginning-of-line 2) ; An empty line after =cut is not POD!
4451                   (setq e (point))
4452                   (and (> e max)
4453                        (progn
4454                          (remove-text-properties
4455                           max e '(syntax-type t in-pod t syntax-table t
4456                                               cperl-postpone t
4457                                               syntax-subtype t
4458                                               here-doc-group t
4459                                               rear-nonsticky t
4460                                               first-format-line t
4461                                               indentable t))
4462                          (setq tmpend tb)))
4463                   (put-text-property b e 'in-pod t)
4464                   (put-text-property b e 'syntax-type 'in-pod)
4465                   (goto-char b)
4466                   (while (re-search-forward "\n\n[ \t]" e t)
4467                     ;; We start 'pod 1 char earlier to include the preceding line
4468                     (beginning-of-line)
4469                     (put-text-property (cperl-1- b) (point) 'syntax-type 'pod)
4470                     (cperl-put-do-not-fontify b (point) t)
4471                     ;; mark the non-literal parts as PODs
4472                     (if cperl-pod-here-fontify
4473                         (cperl-postpone-fontification b (point) 'face face t))
4474                     (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
4475                     (beginning-of-line)
4476                     (setq b (point)))
4477                   (put-text-property (cperl-1- (point)) e 'syntax-type 'pod)
4478                   (cperl-put-do-not-fontify (point) e t)
4479                   (if cperl-pod-here-fontify
4480                       (progn
4481                         ;; mark the non-literal parts as PODs
4482                         (cperl-postpone-fontification (point) e 'face face t)
4483                         (goto-char bb)
4484                         (if (looking-at
4485                              "=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
4486                             ;; mark the headers
4487                             (cperl-postpone-fontification
4488                              (match-beginning 1) (match-end 1)
4489                              'face head-face))
4490                         (while (re-search-forward
4491                                 ;; One paragraph
4492                                 "^\n=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
4493                                 e 'toend)
4494                           ;; mark the headers
4495                           (cperl-postpone-fontification
4496                            (match-beginning 1) (match-end 1)
4497                            'face head-face))))
4498                   (cperl-commentify bb e nil)
4499                   (goto-char e)
4500                   (or (eq e (point-max))
4501                       (forward-char -1)))) ; Prepare for immediate POD start.
4502                ;; Here document
4503                ;; We do only one here-per-line
4504                ;; ;; One extra () before this:
4505                ;;"<<"
4506                ;;  "\\("                        ; 1 + 1
4507                ;;  ;; First variant "BLAH" or just ``.
4508                ;;     "[ \t]*"                  ; Yes, whitespace is allowed!
4509                ;;     "\\([\"'`]\\)"    ; 2 + 1
4510                ;;     "\\([^\"'`\n]*\\)"        ; 3 + 1
4511                ;;     "\\3"
4512                ;;  "\\|"
4513                ;;  ;; Second variant: Identifier or \ID or empty
4514                ;;    "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
4515                ;;    ;; Do not have <<= or << 30 or <<30 or << $blah.
4516                ;;    ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
4517                ;;    "\\(\\)"           ; To preserve count of pars :-( 6 + 1
4518                ;;  "\\)"
4519                ((match-beginning 2)     ; 1 + 1
4520                 ;; Abort in comment:
4521                 (setq b (point))
4522                 (setq state (parse-partial-sexp state-point b nil nil state)
4523                       state-point b
4524                       tb (match-beginning 0)
4525                       i (or (nth 3 state) (nth 4 state)))
4526                 (if i
4527                     (setq c t)
4528                   (setq c (and
4529                            (match-beginning 5)
4530                            (not (match-beginning 6)) ; Empty
4531                            (looking-at
4532                             "[ \t]*[=0-9$@%&(]"))))
4533                 (if c                   ; Not here-doc
4534                     nil                 ; Skip it.
4535                   (if (match-beginning 5) ;4 + 1
4536                       (setq b1 (match-beginning 5) ; 4 + 1
4537                             e1 (match-end 5)) ; 4 + 1
4538                     (setq b1 (match-beginning 4) ; 3 + 1
4539                           e1 (match-end 4))) ; 3 + 1
4540                   (setq tag (buffer-substring b1 e1)
4541                         qtag (regexp-quote tag))
4542                   (cond (cperl-pod-here-fontify
4543                          ;; Highlight the starting delimiter
4544                          (cperl-postpone-fontification b1 e1 'face font-lock-constant-face)
4545                          (cperl-put-do-not-fontify b1 e1 t)))
4546                   (forward-line)
4547                   (setq b (point))
4548                   ;; We do not search to max, since we may be called from
4549                   ;; some hook of fontification, and max is random
4550                   (or (and (re-search-forward (concat "^" qtag "$")
4551                                               stop-point 'toend)
4552                            (eq (following-char) ?\n))
4553                     (progn              ; Pretend we matched at the end
4554                       (goto-char (point-max))
4555                       (re-search-forward "\\'")
4556                       (message "End of here-document `%s' not found." tag)
4557                       (or (car err-l) (setcar err-l b))))
4558                   (if cperl-pod-here-fontify
4559                       (progn
4560                         ;; Highlight the ending delimiter
4561                         (cperl-postpone-fontification (match-beginning 0) (match-end 0)
4562                                                       'face font-lock-constant-face)
4563                         (cperl-put-do-not-fontify b (match-end 0) t)
4564                         ;; Highlight the HERE-DOC
4565                         (cperl-postpone-fontification b (match-beginning 0)
4566                                                       'face here-face)))
4567                   (setq e1 (cperl-1+ (match-end 0)))
4568                   (put-text-property b (match-beginning 0)
4569                                      'syntax-type 'here-doc)
4570                   (put-text-property (match-beginning 0) e1
4571                                      'syntax-type 'here-doc-delim)
4572                   (put-text-property b e1
4573                                      'here-doc-group t)
4574                   (cperl-commentify b e1 nil)
4575                   (cperl-put-do-not-fontify b (match-end 0) t)
4576                   (if (> e1 max)
4577                       (setq tmpend tb))))
4578                ;; format
4579                ((match-beginning 8)
4580                 ;; 1+6=7 extra () before this:
4581                 ;;"^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
4582                 (setq b (point)
4583                       name (if (match-beginning 8) ; 7 + 1
4584                                (buffer-substring (match-beginning 8) ; 7 + 1
4585                                                  (match-end 8)) ; 7 + 1
4586                              "")
4587                       tb (match-beginning 0))
4588                 (setq argument nil)
4589                 (put-text-property (save-excursion
4590                                      (beginning-of-line)
4591                                      (point))
4592                                    b 'first-format-line 't)
4593                 (if cperl-pod-here-fontify
4594                     (while (and (eq (forward-line) 0)
4595                                 (not (looking-at "^[.;]$")))
4596                       (cond
4597                        ((looking-at "^#")) ; Skip comments
4598                        ((and argument   ; Skip argument multi-lines
4599                              (looking-at "^[ \t]*{"))
4600                         (forward-sexp 1)
4601                         (setq argument nil))
4602                        (argument        ; Skip argument lines
4603                         (setq argument nil))
4604                        (t               ; Format line
4605                         (setq b1 (point))
4606                         (setq argument (looking-at "^[^\n]*[@^]"))
4607                         (end-of-line)
4608                         ;; Highlight the format line
4609                         (cperl-postpone-fontification b1 (point)
4610                                                       'face font-lock-string-face)
4611                         (cperl-commentify b1 (point) nil)
4612                         (cperl-put-do-not-fontify b1 (point) t))))
4613                   ;; We do not search to max, since we may be called from
4614                   ;; some hook of fontification, and max is random
4615                   (re-search-forward "^[.;]$" stop-point 'toend))
4616                 (beginning-of-line)
4617                 (if (looking-at "^\\.$") ; ";" is not supported yet
4618                     (progn
4619                       ;; Highlight the ending delimiter
4620                       (cperl-postpone-fontification (point) (+ (point) 2)
4621                                                     'face font-lock-string-face)
4622                       (cperl-commentify (point) (+ (point) 2) nil)
4623                       (cperl-put-do-not-fontify (point) (+ (point) 2) t))
4624                   (message "End of format `%s' not found." name)
4625                   (or (car err-l) (setcar err-l b)))
4626                 (forward-line)
4627                 (if (> (point) max)
4628                     (setq tmpend tb))
4629                 (put-text-property b (point) 'syntax-type 'format))
4630                ;; Regexp:
4631                ((or (match-beginning 10) (match-beginning 11))
4632                 ;; 1+6+2=9 extra () before this:
4633                 ;; "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>"
4634                 ;; "\\|"
4635                 ;; "\\([?/<]\\)"        ; /blah/ or ?blah? or <file*glob>
4636                 (setq b1 (if (match-beginning 10) 10 11)
4637                       argument (buffer-substring
4638                                 (match-beginning b1) (match-end b1))
4639                       b (point)
4640                       i b
4641                       c (char-after (match-beginning b1))
4642                       bb (char-after (1- (match-beginning b1))) ; tmp holder
4643                       ;; bb == "Not a stringy"
4644                       bb (if (eq b1 10) ; user variables/whatever
4645                              (and (memq bb (append "$@%*#_:-&>" nil)) ; $#y)
4646                                   (cond ((eq bb ?-) (eq c ?s)) ; -s file test
4647                                         ((eq bb ?\:) ; $opt::s
4648                                          (eq (char-after
4649                                               (- (match-beginning b1) 2))
4650                                              ?\:))
4651                                         ((eq bb ?\>) ; $foo->s
4652                                          (eq (char-after
4653                                               (- (match-beginning b1) 2))
4654                                              ?\-))
4655                                         ((eq bb ?\&)
4656                                          (not (eq (char-after   ; &&m/blah/
4657                                                    (- (match-beginning b1) 2))
4658                                                   ?\&)))
4659                                         (t t)))
4660                            ;; <file> or <$file>
4661                            (and (eq c ?\<)
4662                                 ;; Do not stringify <FH>, <$fh> :
4663                                 (save-match-data
4664                                   (looking-at
4665                                    "\\$?\\([_a-zA-Z:][_a-zA-Z0-9:]*\\)?>"))))
4666                       tb (match-beginning 0))
4667                 (goto-char (match-beginning b1))
4668                 (cperl-backward-to-noncomment (point-min))
4669                 (or bb
4670                     (if (eq b1 11)      ; bare /blah/ or ?blah? or <foo>
4671                         (setq argument ""
4672                               b1 nil
4673                               bb        ; Not a regexp?
4674                               (progn
4675                                 (not
4676                                  ;; What is below: regexp-p?
4677                                  (and
4678                                   (or (memq (preceding-char)
4679                                             (append (if (memq c '(?\? ?\<))
4680                                                         ;; $a++ ? 1 : 2
4681                                                         "~{(=|&*!,;:"
4682                                                       "~{(=|&+-*!,;:") nil))
4683                                       (and (eq (preceding-char) ?\})
4684                                            (cperl-after-block-p (point-min)))
4685                                       (and (eq (char-syntax (preceding-char)) ?w)
4686                                            (progn
4687                                              (forward-sexp -1)
4688 ;;; After these keywords `/' starts a RE.  One should add all the
4689 ;;; functions/builtins which expect an argument, but ...
4690                                              (if (eq (preceding-char) ?-)
4691                                                  ;; -d ?foo? is a RE
4692                                                  (looking-at "[a-zA-Z]\\>")
4693                                                (and
4694                                                 (not (memq (preceding-char)
4695                                                            '(?$ ?@ ?& ?%)))
4696                                                 (looking-at
4697                                                  "\\(while\\|if\\|unless\\|until\\|and\\|or\\|not\\|xor\\|split\\|grep\\|map\\|print\\)\\>")))))
4698                                       (and (eq (preceding-char) ?.)
4699                                            (eq (char-after (- (point) 2)) ?.))
4700                                       (bobp))
4701                                   ;;  m|blah| ? foo : bar;
4702                                   (not
4703                                    (and (eq c ?\?)
4704                                         cperl-use-syntax-table-text-property
4705                                         (not (bobp))
4706                                         (progn
4707                                           (forward-char -1)
4708                                           (looking-at "\\s|")))))))
4709                               b (1- b))
4710                       ;; s y tr m
4711                       ;; Check for $a -> y
4712                       (setq b1 (preceding-char)
4713                             go (point))
4714                       (if (and (eq b1 ?>)
4715                                (eq (char-after (- go 2)) ?-))
4716                           ;; Not a regexp
4717                           (setq bb t))))
4718                 (or bb (setq state (parse-partial-sexp
4719                                     state-point b nil nil state)
4720                              state-point b))
4721                 (setq bb (or bb (nth 3 state) (nth 4 state)))
4722                 (goto-char b)
4723                 (or bb
4724                     (progn
4725                       (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4726                           (goto-char (match-end 0))
4727                         (skip-chars-forward " \t\n\f"))
4728                       (cond ((and (eq (following-char) ?\})
4729                                   (eq b1 ?\{))
4730                              ;; Check for $a[23]->{ s }, @{s} and *{s::foo}
4731                              (goto-char (1- go))
4732                              (skip-chars-backward " \t\n\f")
4733                              (if (memq (preceding-char) (append "$@%&*" nil))
4734                                  (setq bb t) ; @{y}
4735                                (condition-case nil
4736                                    (forward-sexp -1)
4737                                  (error nil)))
4738                              (if (or bb
4739                                      (looking-at ; $foo -> {s}
4740                                       "[$@]\\$*\\([a-zA-Z0-9_:]+\\|[^{]\\)\\([ \t\n]*->\\)?[ \t\n]*{")
4741                                      (and ; $foo[12] -> {s}
4742                                       (memq (following-char) '(?\{ ?\[))
4743                                       (progn
4744                                         (forward-sexp 1)
4745                                         (looking-at "\\([ \t\n]*->\\)?[ \t\n]*{"))))
4746                                  (setq bb t)
4747                                (goto-char b)))
4748                             ((and (eq (following-char) ?=)
4749                                   (eq (char-after (1+ (point))) ?\>))
4750                              ;; Check for { foo => 1, s => 2 }
4751                              ;; Apparently s=> is never a substitution...
4752                              (setq bb t))
4753                             ((and (eq (following-char) ?:)
4754                                   (eq b1 ?\{) ; Check for $ { s::bar }
4755                                   (looking-at "::[a-zA-Z0-9_:]*[ \t\n\f]*}")
4756                                   (progn 
4757                                     (goto-char (1- go))
4758                                     (skip-chars-backward " \t\n\f")
4759                                     (memq (preceding-char)
4760                                           (append "$@%&*" nil))))
4761                              (setq bb t)))))
4762                 (if bb
4763                     (goto-char i)
4764                   ;; Skip whitespace and comments...
4765                   (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4766                       (goto-char (match-end 0))
4767                     (skip-chars-forward " \t\n\f"))
4768                   (if (> (point) b)
4769                       (put-text-property b (point) 'syntax-type 'prestring))
4770                   ;; qtag means two-arg matcher, may be reset to
4771                   ;;   2 or 3 later if some special quoting is needed.
4772                   ;; e1 means matching-char matcher.
4773                   (setq b (point)
4774                         ;; has 2 args
4775                         i2 (string-match "^\\([sy]\\|tr\\)$" argument)
4776                         ;; We do not search to max, since we may be called from
4777                         ;; some hook of fontification, and max is random
4778                         i (cperl-forward-re stop-point end
4779                                             i2
4780                                             t st-l err-l argument)
4781                         ;; Note that if `go', then it is considered as 1-arg
4782                         b1 (nth 1 i)    ; start of the second part
4783                         tag (nth 2 i)   ; ender-char, true if second part
4784                                         ; is with matching chars []
4785                         go (nth 4 i)    ; There is a 1-char part after the end
4786                         i (car i)       ; intermediate point
4787                         e1 (point)      ; end
4788                         ;; Before end of the second part if non-matching: ///
4789                         tail (if (and i (not tag))
4790                                  (1- e1))
4791                         e (if i i e1)   ; end of the first part
4792                         qtag nil        ; need to preserve backslashitis
4793                         is-x-REx nil)   ; REx has //x modifier
4794                   ;; Commenting \\ is dangerous, what about ( ?
4795                   (and i tail
4796                        (eq (char-after i) ?\\)
4797                        (setq qtag t))
4798                   (if (looking-at "\\sw*x") ; qr//x
4799                       (setq is-x-REx t))
4800                   (if (null i)
4801                       ;; Considered as 1arg form
4802                       (progn
4803                         (cperl-commentify b (point) t)
4804                         (put-text-property b (point) 'syntax-type 'string)
4805                         (if (or is-x-REx
4806                                 ;; ignore other text properties:
4807                                 (string-match "^qw$" argument))
4808                             (put-text-property b (point) 'indentable t))
4809                         (and go
4810                              (setq e1 (cperl-1+ e1))
4811                              (or (eobp)
4812                                  (forward-char 1))))
4813                     (cperl-commentify b i t)
4814                     (if (looking-at "\\sw*e") ; s///e
4815                         (progn
4816                           (and
4817                            ;; silent:
4818                            (cperl-find-pods-heres b1 (1- (point)) t end)
4819                            ;; Error
4820                            (goto-char (1+ max)))
4821                           (if (and tag (eq (preceding-char) ?\>))
4822                               (progn
4823                                 (cperl-modify-syntax-type (1- (point)) cperl-st-ket)
4824                                 (cperl-modify-syntax-type i cperl-st-bra)))
4825                           (put-text-property b i 'syntax-type 'string)
4826                           (if is-x-REx
4827                               (put-text-property b i 'indentable t)))
4828                       (cperl-commentify b1 (point) t)
4829                       (put-text-property b (point) 'syntax-type 'string)
4830                       (if is-x-REx
4831                           (put-text-property b i 'indentable t))
4832                       (if qtag
4833                           (cperl-modify-syntax-type (1+ i) cperl-st-punct))
4834                       (setq tail nil)))
4835                   ;; Now: tail: if the second part is non-matching without ///e
4836                   (if (eq (char-syntax (following-char)) ?w)
4837                       (progn
4838                         (forward-word 1) ; skip modifiers s///s
4839                         (if tail (cperl-commentify tail (point) t))
4840                         (cperl-postpone-fontification
4841                          e1 (point) 'face 'cperl-nonoverridable-face)))
4842                   ;; Check whether it is m// which means "previous match"
4843                   ;; and highlight differently
4844                   (setq is-REx
4845                         (and (string-match "^\\([sm]?\\|qr\\)$" argument)
4846                              (or (not (= (length argument) 0))
4847                                  (not (eq c ?\<)))))
4848                   (if (and is-REx
4849                            (eq e (+ 2 b))
4850                            ;; split // *is* using zero-pattern
4851                            (save-excursion
4852                              (condition-case nil
4853                                  (progn
4854                                    (goto-char tb)
4855                                    (forward-sexp -1)
4856                                    (not (looking-at "split\\>")))
4857                                (error t))))
4858                       (cperl-postpone-fontification
4859                        b e 'face font-lock-function-name-face)
4860                     (if (or i2          ; Has 2 args
4861                             (and cperl-fontify-m-as-s
4862                                  (or
4863                                   (string-match "^\\(m\\|qr\\)$" argument)
4864                                   (and (eq 0 (length argument))
4865                                        (not (eq ?\< (char-after b)))))))
4866                         (progn
4867                           (cperl-postpone-fontification
4868                            b (cperl-1+ b) 'face font-lock-constant-face)
4869                           (cperl-postpone-fontification
4870                            (1- e) e 'face font-lock-constant-face)))
4871                     (if (and is-REx cperl-regexp-scan)
4872                         ;; Process RExen better
4873                         (save-excursion
4874                           (goto-char (1+ b))
4875                           (while
4876                               (and (< (point) e)
4877                                    (re-search-forward
4878                                     (if is-x-REx
4879                                         (if (eq (char-after b) ?\#)
4880                                             "\\((\\?\\\\#\\)\\|\\(\\\\#\\)"
4881                                           "\\((\\?#\\)\\|\\(#\\)")
4882                                       (if (eq (char-after b) ?\#)
4883                                           "\\((\\?\\\\#\\)"
4884                                         "\\((\\?#\\)"))
4885                                     (1- e) 'to-end))
4886                             (goto-char (match-beginning 0))
4887                             (setq REx-comment-start (point)
4888                                   was-comment t)
4889                             (if (save-excursion
4890                                   (and
4891                                    ;; XXX not working if outside delimiter is #
4892                                    (eq (preceding-char) ?\\)
4893                                    (= (% (skip-chars-backward "$\\\\") 2) -1)))
4894                                 ;; Not a comment, avoid loop:
4895                                 (progn (setq was-comment nil)
4896                                        (forward-char 1))
4897                               (if (match-beginning 2)
4898                                   (progn
4899                                     (beginning-of-line 2)
4900                                     (if (> (point) e)
4901                                         (goto-char (1- e))))
4902                                 ;; Works also if the outside delimiters are ().
4903                                 (or (search-forward ")" (1- e) 'toend)
4904                                     (message
4905                                      "Couldn't find end of (?#...)-comment in a REx, pos=%s"
4906                                      REx-comment-start))))
4907                             (if (>= (point) e)
4908                                 (goto-char (1- e)))
4909                             (if was-comment
4910                                 (progn
4911                                   (setq REx-comment-end (point))
4912                                   (cperl-commentify
4913                                    REx-comment-start REx-comment-end nil)
4914                                   (cperl-postpone-fontification
4915                                    REx-comment-start REx-comment-end
4916                                    'face font-lock-comment-face))))))
4917                     (if (and is-REx is-x-REx)
4918                         (put-text-property (1+ b) (1- e)
4919                                            'syntax-subtype 'x-REx)))
4920                   (if i2
4921                       (progn
4922                         (cperl-postpone-fontification
4923                          (1- e1) e1 'face font-lock-constant-face)
4924                         (if (assoc (char-after b) cperl-starters)
4925                             (cperl-postpone-fontification
4926                              b1 (1+ b1) 'face font-lock-constant-face))))
4927                   (if (> (point) max)
4928                       (setq tmpend tb))))
4929                ((match-beginning 13)    ; sub with prototypes
4930                 (setq b (match-beginning 0))
4931                 (if (memq (char-after (1- b))
4932                           '(?\$ ?\@ ?\% ?\& ?\*))
4933                     nil
4934                   (setq state (parse-partial-sexp
4935                                state-point b nil nil state)
4936                         state-point b)
4937                   (if (or (nth 3 state) (nth 4 state))
4938                       nil
4939                     ;; Mark as string
4940                     (cperl-commentify (match-beginning 13) (match-end 13) t))
4941                   (goto-char (match-end 0))))
4942                ;; 1+6+2+1+1+2=13 extra () before this:
4943                ;;    "\\$\\(['{]\\)"
4944                ((and (match-beginning 14)
4945                      (eq (preceding-char) ?\')) ; $'
4946                 (setq b (1- (point))
4947                       state (parse-partial-sexp
4948                              state-point (1- b) nil nil state)
4949                       state-point (1- b))
4950                 (if (nth 3 state)       ; in string
4951                     (cperl-modify-syntax-type (1- b) cperl-st-punct))
4952                 (goto-char (1+ b)))
4953                ;; 1+6+2+1+1+2=13 extra () before this:
4954                ;;    "\\$\\(['{]\\)"
4955                ((match-beginning 14)    ; ${
4956                 (setq bb (match-beginning 0))
4957                 (cperl-modify-syntax-type bb cperl-st-punct))
4958                ;; 1+6+2+1+1+2+1=14 extra () before this:
4959                ;;    "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'")
4960                ((match-beginning 15)    ; old $abc'efg syntax
4961                 (setq bb (match-end 0)
4962                       b (match-beginning 0)
4963                       state (parse-partial-sexp
4964                              state-point b nil nil state)
4965                       state-point b)
4966                 (if (nth 3 state)       ; in string
4967                     nil
4968                   (put-text-property (1- bb) bb 'syntax-table cperl-st-word))
4969                 (goto-char bb))
4970                ;; 1+6+2+1+1+2+1+1=15 extra () before this:
4971                ;; "__\\(END\\|DATA\\)__"
4972                ((match-beginning 16)    ; __END__, __DATA__
4973                 (setq bb (match-end 0)
4974                       b (match-beginning 0)
4975                       state (parse-partial-sexp
4976                              state-point b nil nil state)
4977                       state-point b)
4978                 (if (or (nth 3 state) (nth 4 state))
4979                     nil
4980                   ;; (put-text-property b (1+ bb) 'syntax-type 'pod) ; Cheat
4981                   (cperl-commentify b bb nil)
4982                   (setq end t))
4983                 (goto-char bb))
4984                ((match-beginning 17)    ; "\\\\\\(['`\"($]\\)"
4985                 ;; Trailing backslash ==> non-quoting outside string/comment
4986                 (setq bb (match-end 0)
4987                       b (match-beginning 0))
4988                 (goto-char b)
4989                 (skip-chars-backward "\\\\")
4990                 ;;;(setq i2 (= (% (skip-chars-backward "\\\\") 2) -1))
4991                 (setq state (parse-partial-sexp
4992                              state-point b nil nil state)
4993                       state-point b)
4994                 (if (or (nth 3 state) (nth 4 state) )
4995                     nil
4996                   (cperl-modify-syntax-type b cperl-st-punct))
4997                 (goto-char bb))
4998                (t (error "Error in regexp of the sniffer")))
4999               (if (> (point) stop-point)
5000                   (progn
5001                     (if end
5002                         (message "Garbage after __END__/__DATA__ ignored")
5003                       (message "Unbalanced syntax found while scanning")
5004                       (or (car err-l) (setcar err-l b)))
5005                     (goto-char stop-point))))
5006             (setq cperl-syntax-state (cons state-point state)
5007                   cperl-syntax-done-to (or tmpend (max (point) max))))
5008           (if (car err-l) (goto-char (car err-l))
5009             (or non-inter
5010                 (message "Scanning for \"hard\" Perl constructions... done"))))
5011       (and (buffer-modified-p)
5012            (not modified)
5013            (set-buffer-modified-p nil))
5014       (set-syntax-table cperl-mode-syntax-table))
5015     (car err-l)))
5016
5017 (defun cperl-backward-to-noncomment (lim)
5018   ;; Stops at lim or after non-whitespace that is not in comment
5019   (let (stop p pr)
5020     (while (and (not stop) (> (point) (or lim 1)))
5021       (skip-chars-backward " \t\n\f" lim)
5022       (setq p (point))
5023       (beginning-of-line)
5024       (if (memq (setq pr (get-text-property (point) 'syntax-type))
5025                 '(pod here-doc here-doc-delim))
5026           (cperl-unwind-to-safe nil)
5027       (or (looking-at "^[ \t]*\\(#\\|$\\)")
5028           (progn (cperl-to-comment-or-eol) (bolp))
5029           (progn
5030             (skip-chars-backward " \t")
5031             (if (< p (point)) (goto-char p))
5032             (setq stop t)))))))
5033
5034 (defun cperl-after-block-p (lim &optional pre-block)
5035   "Return true if the preceeding } ends a block or a following { starts one.
5036 Would not look before LIM.  If PRE-BLOCK is nil checks preceeding }.
5037 otherwise following {."
5038   ;; We suppose that the preceding char is }.
5039   (save-excursion
5040     (condition-case nil
5041         (progn
5042           (or pre-block (forward-sexp -1))
5043           (cperl-backward-to-noncomment lim)
5044           (or (eq (point) lim)
5045               (eq (preceding-char) ?\) ) ; if () {}    sub f () {}
5046               (if (eq (char-syntax (preceding-char)) ?w) ; else {}
5047                   (save-excursion
5048                     (forward-sexp -1)
5049                     (or (looking-at "\\(else\\|continue\\|grep\\|map\\|BEGIN\\|END\\|CHECK\\|INIT\\)\\>")
5050                         ;; sub f {}
5051                         (progn
5052                           (cperl-backward-to-noncomment lim)
5053                           (and (eq (char-syntax (preceding-char)) ?w)
5054                                (progn
5055                                  (forward-sexp -1)
5056                                  (looking-at "sub\\>"))))))
5057                 (cperl-after-expr-p lim))))
5058       (error nil))))
5059
5060 (defun cperl-after-expr-p (&optional lim chars test)
5061   "Return true if the position is good for start of expression.
5062 TEST is the expression to evaluate at the found position.  If absent,
5063 CHARS is a string that contains good characters to have before us (however,
5064 `}' is treated \"smartly\" if it is not in the list)."
5065   (let ((lim (or lim (point-min)))
5066         stop p pr)
5067     (cperl-update-syntaxification (point) (point))
5068     (save-excursion
5069       (while (and (not stop) (> (point) lim))
5070         (skip-chars-backward " \t\n\f" lim)
5071         (setq p (point))
5072         (beginning-of-line)
5073         ;;(memq (setq pr (get-text-property (point) 'syntax-type))
5074         ;;      '(pod here-doc here-doc-delim))
5075         (if (get-text-property (point) 'here-doc-group)
5076             (progn
5077               (goto-char
5078                (previous-single-property-change (point) 'here-doc-group))
5079               (beginning-of-line 0)))
5080         (if (get-text-property (point) 'in-pod)
5081             (progn
5082               (goto-char
5083                (previous-single-property-change (point) 'in-pod))
5084               (beginning-of-line 0)))
5085         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
5086           ;; Else: last iteration, or a label
5087           (cperl-to-comment-or-eol)     ; Will not move past "." after a format
5088           (skip-chars-backward " \t")
5089           (if (< p (point)) (goto-char p))
5090           (setq p (point))
5091           (if (and (eq (preceding-char) ?:)
5092                    (progn
5093                      (forward-char -1)
5094                      (skip-chars-backward " \t\n\f" lim)
5095                      (eq (char-syntax (preceding-char)) ?w)))
5096               (forward-sexp -1)         ; Possibly label.  Skip it
5097             (goto-char p)
5098             (setq stop t))))
5099       (or (bobp)                        ; ???? Needed
5100           (eq (point) lim)
5101           (looking-at "[ \t]*__\\(END\\|DATA\\)__") ; After this anything goes
5102           (progn
5103             (if test (eval test)
5104               (or (memq (preceding-char) (append (or chars "{;") nil))
5105                   (and (eq (preceding-char) ?\})
5106                        (cperl-after-block-p lim))
5107                   (and (eq (following-char) ?.) ; in format: see comment above
5108                        (eq (get-text-property (point) 'syntax-type)
5109                            'format)))))))))
5110
5111 (defun cperl-backward-to-start-of-continued-exp (lim)
5112   (if (memq (preceding-char) (append ")]}\"'`" nil))
5113       (forward-sexp -1))
5114   (beginning-of-line)
5115   (if (<= (point) lim)
5116       (goto-char (1+ lim)))
5117   (skip-chars-forward " \t"))
5118
5119 (defun cperl-after-block-and-statement-beg (lim)
5120   ;; We assume that we are after ?\}
5121   (and
5122    (cperl-after-block-p lim)
5123    (save-excursion
5124      (forward-sexp -1)
5125      (cperl-backward-to-noncomment (point-min))
5126      (or (bobp)
5127          (eq (point) lim)
5128          (not (= (char-syntax (preceding-char)) ?w))
5129          (progn
5130            (forward-sexp -1)
5131            (not
5132             (looking-at
5133              "\\(map\\|grep\\|printf?\\|system\\|exec\\|tr\\|s\\)\\>")))))))
5134
5135 \f
5136 (defvar innerloop-done nil)
5137 (defvar last-depth nil)
5138
5139 (defun cperl-indent-exp ()
5140   "Simple variant of indentation of continued-sexp.
5141
5142 Will not indent comment if it starts at `comment-indent' or looks like
5143 continuation of the comment on the previous line.
5144
5145 If `cperl-indent-region-fix-constructs', will improve spacing on
5146 conditional/loop constructs."
5147   (interactive)
5148   (save-excursion
5149     (let ((tmp-end (progn (end-of-line) (point))) top done)
5150       (save-excursion
5151         (beginning-of-line)
5152         (while (null done)
5153           (setq top (point))
5154           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
5155                                                -1)) -1)
5156             (setq top (point)))         ; Get the outermost parenths in line
5157           (goto-char top)
5158           (while (< (point) tmp-end)
5159             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
5160             (or (eolp) (forward-sexp 1)))
5161           (if (> (point) tmp-end)
5162               (save-excursion
5163                 (end-of-line)
5164                 (setq tmp-end (point)))
5165             (setq done t)))
5166         (goto-char tmp-end)
5167         (setq tmp-end (point-marker)))
5168       (if cperl-indent-region-fix-constructs
5169           (cperl-fix-line-spacing tmp-end))
5170       (cperl-indent-region (point) tmp-end))))
5171
5172 (defun cperl-fix-line-spacing (&optional end parse-data)
5173   "Improve whitespace in a conditional/loop construct.
5174 Returns some position at the last line."
5175   (interactive)
5176   (or end
5177       (setq end (point-max)))
5178   (let ((ee (save-excursion (end-of-line) (point)))
5179         (cperl-indent-region-fix-constructs
5180          (or cperl-indent-region-fix-constructs 1))
5181         p pp ml have-brace ret)
5182     (save-excursion
5183       (beginning-of-line)
5184       (setq ret (point))
5185       ;;  }? continue
5186       ;;  blah; }
5187       (if (not
5188            (or (looking-at "[ \t]*\\(els\\(e\\|if\\)\\|continue\\|if\\|while\\|for\\(each\\)?\\|until\\)")
5189                (setq have-brace (save-excursion (search-forward "}" ee t)))))
5190           nil                           ; Do not need to do anything
5191         ;; Looking at:
5192         ;; }
5193         ;; else
5194         (if (and cperl-merge-trailing-else
5195                  (looking-at
5196                   "[ \t]*}[ \t]*\n[ \t\n]*\\(els\\(e\\|if\\)\\|continue\\)\\>"))
5197             (progn
5198               (search-forward "}")
5199               (setq p (point))
5200               (skip-chars-forward " \t\n")
5201               (delete-region p (point))
5202               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5203               (beginning-of-line)))
5204         ;; Looking at:
5205         ;; }     else
5206         (if (looking-at "[ \t]*}\\(\t*\\|[ \t][ \t]+\\)\\<\\(els\\(e\\|if\\)\\|continue\\)\\>")
5207             (progn
5208               (search-forward "}")
5209               (delete-horizontal-space)
5210               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5211               (beginning-of-line)))
5212         ;; Looking at:
5213         ;; else   {
5214         (if (looking-at
5215              "[ \t]*}?[ \t]*\\<\\(\\els\\(e\\|if\\)\\|continue\\|unless\\|if\\|while\\|for\\(each\\)?\\|until\\)\\>\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
5216             (progn
5217               (forward-word 1)
5218               (delete-horizontal-space)
5219               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5220               (beginning-of-line)))
5221         ;; Looking at:
5222         ;; foreach my    $var
5223         (if (looking-at
5224              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)\\(\t*\\|[ \t][ \t]+\\)[^ \t\n]")
5225             (progn
5226               (forward-word 2)
5227               (delete-horizontal-space)
5228               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5229               (beginning-of-line)))
5230         ;; Looking at:
5231         ;; foreach my $var     (
5232         (if (looking-at
5233              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)[ \t]*\\$[_a-zA-Z0-9]+\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
5234             (progn
5235               (forward-sexp 3)
5236               (delete-horizontal-space)
5237               (insert
5238                (make-string cperl-indent-region-fix-constructs ?\ ))
5239               (beginning-of-line)))
5240         ;; Looking at:
5241         ;; } foreach my $var ()    {
5242         (if (looking-at
5243              "[ \t]*\\(}[ \t]*\\)?\\<\\(\\els\\(e\\|if\\)\\|continue\\|if\\|unless\\|while\\|for\\(each\\)?\\(\\([ \t]+\\(my\\|local\\|our\\)\\)?[ \t]*\\$[_a-zA-Z0-9]+\\)?\\|until\\)\\>\\([ \t]*(\\|[ \t\n]*{\\)\\|[ \t]*{")
5244             (progn
5245               (setq ml (match-beginning 8))
5246               (re-search-forward "[({]")
5247               (forward-char -1)
5248               (setq p (point))
5249               (if (eq (following-char) ?\( )
5250                   (progn
5251                     (forward-sexp 1)
5252                     (setq pp (point)))
5253                 ;; after `else' or nothing
5254                 (if ml                  ; after `else'
5255                     (skip-chars-backward " \t\n")
5256                   (beginning-of-line))
5257                 (setq pp nil))
5258               ;; Now after the sexp before the brace
5259               ;; Multiline expr should be special
5260               (setq ml (and pp (save-excursion (goto-char p)
5261                                                (search-forward "\n" pp t))))
5262               (if (and (or (not pp) (< pp end))
5263                        (looking-at "[ \t\n]*{"))
5264                   (progn
5265                     (cond
5266                      ((bolp)            ; Were before `{', no if/else/etc
5267                       nil)
5268                      ((looking-at "\\(\t*\\| [ \t]+\\){")
5269                       (delete-horizontal-space)
5270                       (if (if ml
5271                               cperl-extra-newline-before-brace-multiline
5272                             cperl-extra-newline-before-brace)
5273                           (progn
5274                             (delete-horizontal-space)
5275                             (insert "\n")
5276                             (setq ret (point))
5277                             (if (cperl-indent-line parse-data)
5278                                 (progn
5279                                   (cperl-fix-line-spacing end parse-data)
5280                                   (setq ret (point)))))
5281                         (insert
5282                          (make-string cperl-indent-region-fix-constructs ?\ ))))
5283                      ((and (looking-at "[ \t]*\n")
5284                            (not (if ml
5285                                     cperl-extra-newline-before-brace-multiline
5286                                   cperl-extra-newline-before-brace)))
5287                       (setq pp (point))
5288                       (skip-chars-forward " \t\n")
5289                       (delete-region pp (point))
5290                       (insert
5291                        (make-string cperl-indent-region-fix-constructs ?\ ))))
5292                     ;; Now we are before `{'
5293                     (if (looking-at "[ \t\n]*{[ \t]*[^ \t\n#]")
5294                         (progn
5295                           (skip-chars-forward " \t\n")
5296                           (setq pp (point))
5297                           (forward-sexp 1)
5298                           (setq p (point))
5299                           (goto-char pp)
5300                           (setq ml (search-forward "\n" p t))
5301                           (if (or cperl-break-one-line-blocks-when-indent ml)
5302                               ;; not good: multi-line BLOCK
5303                               (progn
5304                                 (goto-char (1+ pp))
5305                                 (delete-horizontal-space)
5306                                 (insert "\n")
5307                                 (setq ret (point))
5308                                 (if (cperl-indent-line parse-data)
5309                                     (setq ret (cperl-fix-line-spacing end parse-data)))))))))))
5310         (beginning-of-line)
5311         (setq p (point) pp (save-excursion (end-of-line) (point))) ; May be different from ee.
5312         ;; Now check whether there is a hanging `}'
5313         ;; Looking at:
5314         ;; } blah
5315         (if (and
5316              cperl-fix-hanging-brace-when-indent
5317              have-brace
5318              (not (looking-at "[ \t]*}[ \t]*\\(\\<\\(els\\(if\\|e\\)\\|continue\\|while\\|until\\)\\>\\|$\\|#\\)"))
5319              (condition-case nil
5320                  (progn
5321                    (up-list 1)
5322                    (if (and (<= (point) pp)
5323                             (eq (preceding-char) ?\} )
5324                             (cperl-after-block-and-statement-beg (point-min)))
5325                        t
5326                      (goto-char p)
5327                      nil))
5328                (error nil)))
5329             (progn
5330               (forward-char -1)
5331               (skip-chars-backward " \t")
5332               (if (bolp)
5333                   ;; `}' was the first thing on the line, insert NL *after* it.
5334                   (progn
5335                     (cperl-indent-line parse-data)
5336                     (search-forward "}")
5337                     (delete-horizontal-space)
5338                     (insert "\n"))
5339                 (delete-horizontal-space)
5340                 (or (eq (preceding-char) ?\;)
5341                     (bolp)
5342                     (and (eq (preceding-char) ?\} )
5343                          (cperl-after-block-p (point-min)))
5344                     (insert ";"))
5345                 (insert "\n")
5346                 (setq ret (point)))
5347               (if (cperl-indent-line parse-data)
5348                   (setq ret (cperl-fix-line-spacing end parse-data)))
5349               (beginning-of-line)))))
5350     ret))
5351
5352 (defvar cperl-update-start)             ; Do not need to make them local
5353 (defvar cperl-update-end)
5354 (defun cperl-delay-update-hook (beg end old-len)
5355   (setq cperl-update-start (min beg (or cperl-update-start (point-max))))
5356   (setq cperl-update-end (max end (or cperl-update-end (point-min)))))
5357
5358 (defun cperl-indent-region (start end)
5359   "Simple variant of indentation of region in CPerl mode.
5360 Should be slow.  Will not indent comment if it starts at `comment-indent'
5361 or looks like continuation of the comment on the previous line.
5362 Indents all the lines whose first character is between START and END
5363 inclusive.
5364
5365 If `cperl-indent-region-fix-constructs', will improve spacing on
5366 conditional/loop constructs."
5367   (interactive "r")
5368   (cperl-update-syntaxification end end)
5369   (save-excursion
5370     (let (cperl-update-start cperl-update-end (h-a-c after-change-functions))
5371       (let ((indent-info (if cperl-emacs-can-parse
5372                              (list nil nil nil) ; Cannot use '(), since will modify
5373                            nil))
5374             (pm 0) (imenu-scanning-message "Indenting... (%3d%%)")
5375             after-change-functions      ; Speed it up!
5376             st comm old-comm-indent new-comm-indent p pp i empty)
5377         (if h-a-c (add-hook 'after-change-functions 'cperl-delay-update-hook))
5378         (goto-char start)
5379         (setq old-comm-indent (and (cperl-to-comment-or-eol)
5380                                    (current-column))
5381               new-comm-indent old-comm-indent)
5382         (goto-char start)
5383         (setq end (set-marker (make-marker) end)) ; indentation changes pos
5384         (or (bolp) (beginning-of-line 2))
5385         (or (fboundp 'imenu-progress-message)
5386             (message "Indenting... For feedback load `imenu'..."))
5387         (while (and (<= (point) end) (not (eobp))) ; bol to check start
5388           (and (fboundp 'imenu-progress-message)
5389                (imenu-progress-message
5390                 pm (/ (* 100 (- (point) start)) (- end start -1))))
5391           (setq st (point))
5392           (if (or
5393                (setq empty (looking-at "[ \t]*\n"))
5394                (and (setq comm (looking-at "[ \t]*#"))
5395                     (or (eq (current-indentation) (or old-comm-indent
5396                                                       comment-column))
5397                         (setq old-comm-indent nil))))
5398               (if (and old-comm-indent
5399                        (not empty)
5400                        (= (current-indentation) old-comm-indent)
5401                        (not (eq (get-text-property (point) 'syntax-type) 'pod))
5402                        (not (eq (get-text-property (point) 'syntax-table)
5403                                 cperl-st-cfence)))
5404                   (let ((comment-column new-comm-indent))
5405                     (indent-for-comment)))
5406             (progn
5407               (setq i (cperl-indent-line indent-info))
5408               (or comm
5409                   (not i)
5410                   (progn
5411                     (if cperl-indent-region-fix-constructs
5412                         (goto-char (cperl-fix-line-spacing end indent-info)))
5413                     (if (setq old-comm-indent
5414                               (and (cperl-to-comment-or-eol)
5415                                    (not (memq (get-text-property (point)
5416                                                                  'syntax-type)
5417                                               '(pod here-doc)))
5418                                    (not (eq (get-text-property (point)
5419                                                                'syntax-table)
5420                                             cperl-st-cfence))
5421                                    (current-column)))
5422                         (progn (indent-for-comment)
5423                                (skip-chars-backward " \t")
5424                                (skip-chars-backward "#")
5425                                (setq new-comm-indent (current-column))))))))
5426           (beginning-of-line 2))
5427         (if (fboundp 'imenu-progress-message)
5428             (imenu-progress-message pm 100)
5429           (message nil)))
5430       ;; Now run the update hooks
5431       (and after-change-functions
5432            cperl-update-end
5433            (save-excursion
5434              (goto-char cperl-update-end)
5435              (insert " ")
5436              (delete-char -1)
5437              (goto-char cperl-update-start)
5438              (insert " ")
5439              (delete-char -1))))))
5440
5441 ;; Stolen from lisp-mode with a lot of improvements
5442
5443 (defun cperl-fill-paragraph (&optional justify iteration)
5444   "Like \\[fill-paragraph], but handle CPerl comments.
5445 If any of the current line is a comment, fill the comment or the
5446 block of it that point is in, preserving the comment's initial
5447 indentation and initial hashes.  Behaves usually outside of comment."
5448   (interactive "P")
5449   (let (;; Non-nil if the current line contains a comment.
5450         has-comment
5451
5452         ;; If has-comment, the appropriate fill-prefix for the comment.
5453         comment-fill-prefix
5454         ;; Line that contains code and comment (or nil)
5455         start
5456         c spaces len dc (comment-column comment-column))
5457     ;; Figure out what kind of comment we are looking at.
5458     (save-excursion
5459       (beginning-of-line)
5460       (cond
5461
5462        ;; A line with nothing but a comment on it?
5463        ((looking-at "[ \t]*#[# \t]*")
5464         (setq has-comment t
5465               comment-fill-prefix (buffer-substring (match-beginning 0)
5466                                                     (match-end 0))))
5467
5468        ;; A line with some code, followed by a comment?  Remember that the
5469        ;; semi which starts the comment shouldn't be part of a string or
5470        ;; character.
5471        ((cperl-to-comment-or-eol)
5472         (setq has-comment t)
5473         (looking-at "#+[ \t]*")
5474         (setq start (point) c (current-column)
5475               comment-fill-prefix
5476               (concat (make-string (current-column) ?\ )
5477                       (buffer-substring (match-beginning 0) (match-end 0)))
5478               spaces (progn (skip-chars-backward " \t")
5479                             (buffer-substring (point) start))
5480               dc (- c (current-column)) len (- start (point))
5481               start (point-marker))
5482         (delete-char len)
5483         (insert (make-string dc ?-)))))
5484     (if (not has-comment)
5485         (fill-paragraph justify)       ; Do the usual thing outside of comment
5486       ;; Narrow to include only the comment, and then fill the region.
5487       (save-restriction
5488         (narrow-to-region
5489          ;; Find the first line we should include in the region to fill.
5490          (if start (progn (beginning-of-line) (point))
5491            (save-excursion
5492              (while (and (zerop (forward-line -1))
5493                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
5494              ;; We may have gone to far.  Go forward again.
5495              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
5496                  (forward-line 1))
5497              (point)))
5498          ;; Find the beginning of the first line past the region to fill.
5499          (save-excursion
5500            (while (progn (forward-line 1)
5501                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
5502            (point)))
5503         ;; Remove existing hashes
5504         (goto-char (point-min))
5505         (while (progn (forward-line 1) (< (point) (point-max)))
5506           (skip-chars-forward " \t")
5507           (and (looking-at "#+")
5508                (delete-char (- (match-end 0) (match-beginning 0)))))
5509
5510         ;; Lines with only hashes on them can be paragraph boundaries.
5511         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
5512               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
5513               (fill-prefix comment-fill-prefix))
5514           (fill-paragraph justify)))
5515       (if (and start)
5516           (progn
5517             (goto-char start)
5518             (if (> dc 0)
5519                 (progn (delete-char dc) (insert spaces)))
5520             (if (or (= (current-column) c) iteration) nil
5521               (setq comment-column c)
5522               (indent-for-comment)
5523               ;; Repeat once more, flagging as iteration
5524               (cperl-fill-paragraph justify t)))))))
5525
5526 (defun cperl-do-auto-fill ()
5527   ;; Break out if the line is short enough
5528   (if (> (save-excursion
5529            (end-of-line)
5530            (current-column))
5531          fill-column)
5532       (let ((c (save-excursion (beginning-of-line)
5533                                (cperl-to-comment-or-eol) (point)))
5534             (s (memq (following-char) '(?\ ?\t))) marker)
5535         (if (>= c (point)) nil
5536           (setq marker (point-marker))
5537           (cperl-fill-paragraph)
5538           (goto-char marker)
5539           ;; Is not enough, sometimes marker is a start of line
5540           (if (bolp) (progn (re-search-forward "#+[ \t]*")
5541                             (goto-char (match-end 0))))
5542           ;; Following space could have gone:
5543           (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
5544             (insert " ")
5545             (backward-char 1))
5546           ;; Previous space could have gone:
5547           (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
5548
5549 (defun cperl-imenu-addback (lst &optional isback name)
5550   ;; We suppose that the lst is a DAG, unless the first element only
5551   ;; loops back, and ISBACK is set.  Thus this function cannot be
5552   ;; applied twice without ISBACK set.
5553   (cond ((not cperl-imenu-addback) lst)
5554         (t
5555          (or name
5556              (setq name "+++BACK+++"))
5557          (mapcar (lambda (elt)
5558                    (if (and (listp elt) (listp (cdr elt)))
5559                        (progn
5560                          ;; In the other order it goes up
5561                          ;; one level only ;-(
5562                          (setcdr elt (cons (cons name lst)
5563                                            (cdr elt)))
5564                          (cperl-imenu-addback (cdr elt) t name))))
5565                  (if isback (cdr lst) lst))
5566          lst)))
5567
5568 (defun cperl-imenu--create-perl-index (&optional regexp)
5569   (require 'cl)
5570   (require 'imenu)                      ; May be called from TAGS creator
5571   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '())
5572         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
5573         (index-meth-alist '()) meth
5574         packages ends-ranges p marker
5575         (prev-pos 0) char fchar index index1 name (end-range 0) package)
5576     (goto-char (point-min))
5577     (if noninteractive
5578         (message "Scanning Perl for index")
5579       (imenu-progress-message prev-pos 0))
5580     (cperl-update-syntaxification (point-max) (point-max))
5581     ;; Search for the function
5582     (progn ;;save-match-data
5583       (while (re-search-forward
5584               (or regexp cperl-imenu--function-name-regexp-perl)
5585               nil t)
5586         (or noninteractive
5587             (imenu-progress-message prev-pos))
5588         (cond
5589          ((and                          ; Skip some noise if building tags
5590            (match-beginning 2)          ; package or sub
5591            (eq (char-after (match-beginning 2)) ?p) ; package
5592            (not (save-match-data
5593                   (looking-at "[ \t\n]*;")))) ; Plain text word 'package'
5594           nil)
5595          ((and
5596            (match-beginning 2)          ; package or sub
5597            ;; Skip if quoted (will not skip multi-line ''-strings :-():
5598            (null (get-text-property (match-beginning 1) 'syntax-table))
5599            (null (get-text-property (match-beginning 1) 'syntax-type))
5600            (null (get-text-property (match-beginning 1) 'in-pod)))
5601           (save-excursion
5602             (goto-char (match-beginning 2))
5603             (setq fchar (following-char)))
5604           ;; (if (looking-at "([^()]*)[ \t\n\f]*")
5605           ;;    (goto-char (match-end 0)))      ; Messes what follows
5606           (setq char (following-char)   ; ?\; for "sub foo () ;"
5607                 meth nil
5608                 p (point))
5609           (while (and ends-ranges (>= p (car ends-ranges)))
5610             ;; delete obsolete entries
5611             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
5612           (setq package (or (car packages) "")
5613                 end-range (or (car ends-ranges) 0))
5614           (if (eq fchar ?p)
5615               (setq name (buffer-substring (match-beginning 3) (match-end 3))
5616                     name (progn
5617                            (set-text-properties 0 (length name) nil name)
5618                            name)
5619                     package (concat name "::")
5620                     name (concat "package " name)
5621                     end-range
5622                     (save-excursion
5623                       (parse-partial-sexp (point) (point-max) -1) (point))
5624                     ends-ranges (cons end-range ends-ranges)
5625                     packages (cons package packages)))
5626           ;;   )
5627           ;; Skip this function name if it is a prototype declaration.
5628           (if (and (eq fchar ?s) (eq char ?\;)) nil
5629             (setq name (buffer-substring (match-beginning 3) (match-end 3))
5630                   marker (make-marker))
5631             (set-text-properties 0 (length name) nil name)
5632             (set-marker marker (match-end 3))
5633             (if (eq fchar ?p)
5634                 (setq name (concat "package " name))
5635               (cond ((string-match "[:']" name)
5636                      (setq meth t))
5637                     ((> p end-range) nil)
5638                     (t
5639                      (setq name (concat package name) meth t))))
5640             (setq index (cons name marker))
5641             (if (eq fchar ?p)
5642                 (push index index-pack-alist)
5643               (push index index-alist))
5644             (if meth (push index index-meth-alist))
5645             (push index index-unsorted-alist)))
5646          ((match-beginning 5)           ; POD section
5647           ;; (beginning-of-line)
5648           (setq index (imenu-example--name-and-position)
5649                 name (buffer-substring (match-beginning 6) (match-end 6)))
5650           (set-text-properties 0 (length name) nil name)
5651           (if (eq (char-after (match-beginning 5)) ?2)
5652               (setq name (concat "   " name)))
5653           (setcar index name)
5654           (setq index1 (cons (concat "=" name) (cdr index)))
5655           (push index index-pod-alist)
5656           (push index1 index-unsorted-alist)))))
5657     (or noninteractive
5658         (imenu-progress-message prev-pos 100))
5659     (setq index-alist
5660           (if (default-value 'imenu-sort-function)
5661               (sort index-alist (default-value 'imenu-sort-function))
5662             (nreverse index-alist)))
5663     (and index-pod-alist
5664          (push (cons "+POD headers+..."
5665                      (nreverse index-pod-alist))
5666                index-alist))
5667     (and (or index-pack-alist index-meth-alist)
5668          (let ((lst index-pack-alist) hier-list pack elt group name)
5669            ;; Remove "package ", reverse and uniquify.
5670            (while lst
5671              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
5672              (if (assoc name hier-list) nil
5673                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
5674            (setq lst index-meth-alist)
5675            (while lst
5676              (setq elt (car lst) lst (cdr lst))
5677              (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
5678                     (setq pack (substring (car elt) 0 (match-beginning 0)))
5679                     (if (setq group (assoc pack hier-list))
5680                         (if (listp (cdr group))
5681                             ;; Have some functions already
5682                             (setcdr group
5683                                     (cons (cons (substring
5684                                                  (car elt)
5685                                                  (+ 2 (match-beginning 0)))
5686                                                 (cdr elt))
5687                                           (cdr group)))
5688                           (setcdr group (list (cons (substring
5689                                                      (car elt)
5690                                                      (+ 2 (match-beginning 0)))
5691                                                     (cdr elt)))))
5692                       (setq hier-list
5693                             (cons (cons pack
5694                                         (list (cons (substring
5695                                                      (car elt)
5696                                                      (+ 2 (match-beginning 0)))
5697                                                     (cdr elt))))
5698                                   hier-list))))))
5699            (push (cons "+Hierarchy+..."
5700                        hier-list)
5701                  index-alist)))
5702     (and index-pack-alist
5703          (push (cons "+Packages+..."
5704                      (nreverse index-pack-alist))
5705                index-alist))
5706     (and (or index-pack-alist index-pod-alist
5707              (default-value 'imenu-sort-function))
5708          index-unsorted-alist
5709          (push (cons "+Unsorted List+..."
5710                      (nreverse index-unsorted-alist))
5711                index-alist))
5712     (cperl-imenu-addback index-alist)))
5713
5714 \f
5715 ;; Suggested by Mark A. Hershberger
5716 (defun cperl-outline-level ()
5717   (looking-at outline-regexp)
5718   (cond ((not (match-beginning 1)) 0)   ; beginning-of-file
5719         ((match-beginning 2)
5720          (if (eq (char-after (match-beginning 2)) ?p)
5721              0                          ; package
5722            1))                          ; sub
5723         ((match-beginning 5)
5724          (if (eq (char-after (match-beginning 5)) ?1)
5725              1                          ; head1
5726            2))                          ; head2
5727         (t 3)))                         ; should not happen
5728
5729 \f
5730 (defvar cperl-compilation-error-regexp-alist
5731   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
5732   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
5733      2 3))
5734   "Alist that specifies how to match errors in perl output.")
5735
5736 (if (fboundp 'eval-after-load)
5737     (eval-after-load
5738         "mode-compile"
5739       '(setq perl-compilation-error-regexp-alist
5740              cperl-compilation-error-regexp-alist)))
5741
5742
5743 (defun cperl-windowed-init ()
5744   "Initialization under windowed version."
5745   (if (or (featurep 'ps-print) cperl-faces-init)
5746       ;; Need to init anyway:
5747       (or cperl-faces-init (cperl-init-faces))
5748     (add-hook 'font-lock-mode-hook
5749               (function
5750                (lambda ()
5751                  (if (memq major-mode '(perl-mode cperl-mode))
5752                      (progn
5753                        (or cperl-faces-init (cperl-init-faces)))))))
5754     (if (fboundp 'eval-after-load)
5755         (eval-after-load
5756             "ps-print"
5757           '(or cperl-faces-init (cperl-init-faces))))))
5758
5759 (defun cperl-load-font-lock-keywords ()
5760   (or cperl-faces-init (cperl-init-faces))
5761   perl-font-lock-keywords)
5762
5763 (defun cperl-load-font-lock-keywords-1 ()
5764   (or cperl-faces-init (cperl-init-faces))
5765   perl-font-lock-keywords-1)
5766
5767 (defun cperl-load-font-lock-keywords-2 ()
5768   (or cperl-faces-init (cperl-init-faces))
5769   perl-font-lock-keywords-2)
5770
5771 (defvar perl-font-lock-keywords-1 nil
5772   "Additional expressions to highlight in Perl mode.  Minimal set.")
5773 (defvar perl-font-lock-keywords nil
5774   "Additional expressions to highlight in Perl mode.  Default set.")
5775 (defvar perl-font-lock-keywords-2 nil
5776   "Additional expressions to highlight in Perl mode.  Maximal set")
5777
5778 (defvar font-lock-background-mode)
5779 (defvar font-lock-display-type)
5780 (defun cperl-init-faces-weak ()
5781   ;; Allow `cperl-find-pods-heres' to run.
5782   (or (boundp 'font-lock-constant-face)
5783       (cperl-force-face font-lock-constant-face
5784                         "Face for constant and label names")
5785       ;;(setq font-lock-constant-face 'font-lock-constant-face)
5786       ))
5787
5788 (defun cperl-init-faces ()
5789   (condition-case errs
5790       (progn
5791         (require 'font-lock)
5792         (and (fboundp 'font-lock-fontify-anchored-keywords)
5793              (featurep 'font-lock-extra)
5794              (message "You have an obsolete package `font-lock-extra'.  Install `choose-color'."))
5795         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
5796           (if (fboundp 'font-lock-fontify-anchored-keywords)
5797               (setq font-lock-anchored t))
5798           (setq
5799            t-font-lock-keywords
5800            (list
5801             (list "[ \t]+$" 0 cperl-invalid-face t)
5802             (cons
5803              (concat
5804               "\\(^\\|[^$@%&\\]\\)\\<\\("
5805               (mapconcat
5806                'identity
5807                '("if" "until" "while" "elsif" "else" "unless" "for"
5808                  "foreach" "continue" "exit" "die" "last" "goto" "next"
5809                  "redo" "return" "local" "exec" "sub" "do" "dump" "use"
5810                  "require" "package" "eval" "my" "BEGIN" "END" "CHECK" "INIT")
5811                "\\|")                   ; Flow control
5812               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
5813                                         ; In what follows we use `type' style
5814                                         ; for overwritable builtins
5815             (list
5816              (concat
5817               "\\(^\\|[^$@%&\\]\\)\\<\\("
5818               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm"
5819               ;; "and" "atan2" "bind" "binmode" "bless" "caller"
5820               ;; "chdir" "chmod" "chown" "chr" "chroot" "close"
5821               ;; "closedir" "cmp" "connect" "continue" "cos" "crypt"
5822               ;; "dbmclose" "dbmopen" "die" "dump" "endgrent"
5823               ;; "endhostent" "endnetent" "endprotoent" "endpwent"
5824               ;; "endservent" "eof" "eq" "exec" "exit" "exp" "fcntl"
5825               ;; "fileno" "flock" "fork" "formline" "ge" "getc"
5826               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr"
5827               ;; "gethostbyname" "gethostent" "getlogin"
5828               ;; "getnetbyaddr" "getnetbyname" "getnetent"
5829               ;; "getpeername" "getpgrp" "getppid" "getpriority"
5830               ;; "getprotobyname" "getprotobynumber" "getprotoent"
5831               ;; "getpwent" "getpwnam" "getpwuid" "getservbyname"
5832               ;; "getservbyport" "getservent" "getsockname"
5833               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int"
5834               ;; "ioctl" "join" "kill" "lc" "lcfirst" "le" "length"
5835               ;; "link" "listen" "localtime" "lock" "log" "lstat" "lt"
5836               ;; "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd" "ne"
5837               ;; "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
5838               ;; "quotemeta" "rand" "read" "readdir" "readline"
5839               ;; "readlink" "readpipe" "recv" "ref" "rename" "require"
5840               ;; "reset" "reverse" "rewinddir" "rindex" "rmdir" "seek"
5841               ;; "seekdir" "select" "semctl" "semget" "semop" "send"
5842               ;; "setgrent" "sethostent" "setnetent" "setpgrp"
5843               ;; "setpriority" "setprotoent" "setpwent" "setservent"
5844               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite"
5845               ;; "shutdown" "sin" "sleep" "socket" "socketpair"
5846               ;; "sprintf" "sqrt" "srand" "stat" "substr" "symlink"
5847               ;; "syscall" "sysopen" "sysread" "system" "syswrite" "tell"
5848               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst"
5849               ;; "umask" "unlink" "unpack" "utime" "values" "vec"
5850               ;; "wait" "waitpid" "wantarray" "warn" "write" "x" "xor"
5851               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|"
5852               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
5853               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
5854               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
5855               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
5856               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
5857               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
5858               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
5859               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
5860               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
5861               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
5862               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
5863               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
5864               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
5865               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
5866               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
5867               "\\(\\|ngth\\)\\|o\\(c\\(altime\\|k\\)\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
5868               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
5869               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
5870               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
5871               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
5872               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
5873               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
5874               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
5875               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
5876               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|open\\|tem\\|write\\)\\|"
5877               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
5878               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
5879               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
5880               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
5881               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\|PACKAGE__\\)"
5882               "\\)\\>") 2 'font-lock-type-face)
5883             ;; In what follows we use `other' style
5884             ;; for nonoverwritable builtins
5885             ;; Somehow 's', 'm' are not auto-generated???
5886             (list
5887              (concat
5888               "\\(^\\|[^$@%&\\]\\)\\<\\("
5889               ;; "AUTOLOAD" "BEGIN" "CHECK" "DESTROY" "END" "INIT" "__END__" "chomp"
5890               ;; "chop" "defined" "delete" "do" "each" "else" "elsif"
5891               ;; "eval" "exists" "for" "foreach" "format" "goto"
5892               ;; "grep" "if" "keys" "last" "local" "map" "my" "next"
5893               ;; "no" "package" "pop" "pos" "print" "printf" "push"
5894               ;; "q" "qq" "qw" "qx" "redo" "return" "scalar" "shift"
5895               ;; "sort" "splice" "split" "study" "sub" "tie" "tr"
5896               ;; "undef" "unless" "unshift" "untie" "until" "use"
5897               ;; "while" "y"
5898               "AUTOLOAD\\|BEGIN\\|CHECK\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
5899               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
5900               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|INIT\\|if\\|keys\\|"
5901               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|our\\|"
5902               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
5903               "q\\(\\|q\\|w\\|x\\|r\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
5904               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
5905               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
5906               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
5907               "\\|[sm]"                 ; Added manually
5908               "\\)\\>") 2 'cperl-nonoverridable-face)
5909             ;;          (mapconcat 'identity
5910             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
5911             ;;                       "#include" "#define" "#undef")
5912             ;;                     "\\|")
5913             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
5914               font-lock-function-name-face keep) ; Not very good, triggers at "[a-z]"
5915             '("\\<sub[ \t]+\\([^ \t{;()]+\\)[ \t]*\\(([^()]*)[ \t]*\\)?[#{\n]" 1
5916               font-lock-function-name-face)
5917             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
5918               2 font-lock-function-name-face)
5919             '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
5920               1 font-lock-function-name-face)
5921             (cond ((featurep 'font-lock-extra)
5922                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5923                      (2 font-lock-string-face t)
5924                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
5925                   (font-lock-anchored
5926                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5927                      (2 font-lock-string-face t)
5928                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5929                       nil nil
5930                       (1 font-lock-string-face t))))
5931                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5932                        2 font-lock-string-face t)))
5933             '("[\[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
5934               font-lock-string-face t)
5935             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1
5936               font-lock-constant-face)  ; labels
5937             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
5938               2 font-lock-constant-face)
5939             ;; Uncomment to get perl-mode-like vars
5940             ;;; '("[$*]{?\\(\\sw+\\)" 1 font-lock-variable-name-face)
5941             ;;; '("\\([@%]\\|\\$#\\)\\(\\sw+\\)"
5942             ;;;  (2 (cons font-lock-variable-name-face '(underline))))
5943             (cond ((featurep 'font-lock-extra)
5944                    '("^[ \t]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
5945                      (3 font-lock-variable-name-face)
5946                      (4 '(another 4 nil
5947                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
5948                                    (1 font-lock-variable-name-face)
5949                                    (2 '(restart 2 nil) nil t)))
5950                         nil t)))        ; local variables, multiple
5951                   (font-lock-anchored
5952                    '("^[ \t{}]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
5953                      (3 font-lock-variable-name-face)
5954                      ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)"
5955                       nil nil
5956                       (1 font-lock-variable-name-face))))
5957                   (t '("^[ \t{}]*\\(my\\|local\\our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
5958                        3 font-lock-variable-name-face)))
5959             '("\\<for\\(each\\)?\\([ \t]+\\(my\\|local\\|our\\)\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
5960               4 font-lock-variable-name-face)))
5961           (setq
5962            t-font-lock-keywords-1
5963            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
5964                 (not cperl-xemacs-p)    ; not yet as of XEmacs 19.12
5965                 '(
5966                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
5967                    (if (eq (char-after (match-beginning 2)) ?%)
5968                        cperl-hash-face
5969                      cperl-array-face)
5970                    t)                   ; arrays and hashes
5971                   ("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
5972                    1
5973                    (if (= (- (match-end 2) (match-beginning 2)) 1)
5974                        (if (eq (char-after (match-beginning 3)) ?{)
5975                            cperl-hash-face
5976                          cperl-array-face) ; arrays and hashes
5977                      font-lock-variable-name-face) ; Just to put something
5978                    t)
5979                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
5980                        ;;; Too much noise from \s* @s[ and friends
5981                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)"
5982                   ;;(3 font-lock-function-name-face t t)
5983                   ;;(4
5984                   ;; (if (cperl-slash-is-regexp)
5985                   ;;    font-lock-function-name-face 'default) nil t))
5986                   )))
5987           (if cperl-highlight-variables-indiscriminately
5988               (setq t-font-lock-keywords-1
5989                     (append t-font-lock-keywords-1
5990                             (list '("[$*]{?\\(\\sw+\\)" 1
5991                                     font-lock-variable-name-face)))))
5992           (setq perl-font-lock-keywords-1 
5993                 (if cperl-syntaxify-by-font-lock
5994                     (cons 'cperl-fontify-update
5995                           t-font-lock-keywords)
5996                   t-font-lock-keywords)
5997                 perl-font-lock-keywords perl-font-lock-keywords-1
5998                 perl-font-lock-keywords-2 (append
5999                                            perl-font-lock-keywords-1
6000                                            t-font-lock-keywords-1)))
6001         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
6002         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
6003             (eval                       ; Avoid a warning
6004              '(font-lock-require-faces
6005                (list
6006                 ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
6007                 (list 'font-lock-comment-face
6008                       ["Firebrick"      "OrangeRed"     "DimGray"       "Gray80"]
6009                       nil
6010                       [nil              nil             t               t       t]
6011                       [nil              nil             t               t       t]
6012                       nil)
6013                 (list 'font-lock-string-face
6014                       ["RosyBrown"      "LightSalmon"   "Gray50"        "LightGray"]
6015                       nil
6016                       nil
6017                       [nil              nil             t               t       t]
6018                       nil)
6019                 (list 'font-lock-function-name-face
6020                       (vector
6021                        "Blue"           "LightSkyBlue"  "Gray50"        "LightGray"
6022                        (cdr (assq 'background-color ; if mono
6023                                   (frame-parameters))))
6024                       (vector
6025                        nil              nil             nil             nil
6026                        (cdr (assq 'foreground-color ; if mono
6027                                   (frame-parameters))))
6028                       [nil              nil             t               t       t]
6029                       nil
6030                       nil)
6031                 (list 'font-lock-variable-name-face
6032                       ["DarkGoldenrod"  "LightGoldenrod" "DimGray"      "Gray90"]
6033                       nil
6034                       [nil              nil             t               t       t]
6035                       [nil              nil             t               t       t]
6036                       nil)
6037                 (list 'font-lock-type-face
6038                       ["DarkOliveGreen" "PaleGreen"     "DimGray"       "Gray80"]
6039                       nil
6040                       [nil              nil             t               t       t]
6041                       nil
6042                       [nil              nil             t               t       t])
6043                 (list 'font-lock-constant-face
6044                       ["CadetBlue"      "Aquamarine"    "Gray50"        "LightGray"]
6045                       nil
6046                       [nil              nil             t               t       t]
6047                       nil
6048                       [nil              nil             t               t       t])
6049                 (list 'cperl-nonoverridable-face
6050                       ["chartreuse3"    ("orchid1" "orange")
6051                        nil              "Gray80"]
6052                       [nil              nil             "gray90"]
6053                       [nil              nil             nil             t       t]
6054                       [nil              nil             t               t]
6055                       [nil              nil             t               t       t])
6056                 (list 'cperl-array-face
6057                       ["blue"           "yellow"        nil             "Gray80"]
6058                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
6059                        "gray90"]
6060                       t
6061                       nil
6062                       nil)
6063                 (list 'cperl-hash-face
6064                       ["red"            "red"           nil             "Gray80"]
6065                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
6066                        "gray90"]
6067                       t
6068                       t
6069                       nil))))
6070           ;; Do it the dull way, without choose-color
6071           (defvar cperl-guessed-background nil
6072             "Display characteristics as guessed by cperl.")
6073           ;;      (or (fboundp 'x-color-defined-p)
6074           ;;          (defalias 'x-color-defined-p 
6075           ;;            (cond ((fboundp 'color-defined-p) 'color-defined-p)
6076           ;;                  ;; XEmacs >= 19.12
6077           ;;                  ((fboundp 'valid-color-name-p) 'valid-color-name-p)
6078           ;;                  ;; XEmacs 19.11
6079           ;;                  (t 'x-valid-color-name-p))))
6080           (cperl-force-face font-lock-constant-face
6081                             "Face for constant and label names")
6082           (cperl-force-face font-lock-variable-name-face
6083                             "Face for variable names")
6084           (cperl-force-face font-lock-type-face
6085                             "Face for data types")
6086           (cperl-force-face cperl-nonoverridable-face
6087                             "Face for data types from another group")
6088           (cperl-force-face font-lock-comment-face
6089                             "Face for comments")
6090           (cperl-force-face font-lock-function-name-face
6091                             "Face for function names")
6092           (cperl-force-face cperl-hash-face
6093                             "Face for hashes")
6094           (cperl-force-face cperl-array-face
6095                             "Face for arrays")
6096           ;;(defvar font-lock-constant-face 'font-lock-constant-face)
6097           ;;(defvar font-lock-variable-name-face 'font-lock-variable-name-face)
6098           ;;(or (boundp 'font-lock-type-face)
6099           ;;    (defconst font-lock-type-face
6100           ;;    'font-lock-type-face
6101           ;;    "Face to use for data types."))
6102           ;;(or (boundp 'cperl-nonoverridable-face)
6103           ;;    (defconst cperl-nonoverridable-face
6104           ;;    'cperl-nonoverridable-face
6105           ;;    "Face to use for data types from another group."))
6106           ;;(if (not cperl-xemacs-p) nil
6107           ;;  (or (boundp 'font-lock-comment-face)
6108           ;;    (defconst font-lock-comment-face
6109           ;;      'font-lock-comment-face
6110           ;;      "Face to use for comments."))
6111           ;;  (or (boundp 'font-lock-keyword-face)
6112           ;;    (defconst font-lock-keyword-face
6113           ;;      'font-lock-keyword-face
6114           ;;      "Face to use for keywords."))
6115           ;;  (or (boundp 'font-lock-function-name-face)
6116           ;;    (defconst font-lock-function-name-face
6117           ;;      'font-lock-function-name-face
6118           ;;      "Face to use for function names.")))
6119           (if (and
6120                (not (cperl-is-face 'cperl-array-face))
6121                (cperl-is-face 'font-lock-emphasized-face))
6122               (copy-face 'font-lock-emphasized-face 'cperl-array-face))
6123           (if (and
6124                (not (cperl-is-face 'cperl-hash-face))
6125                (cperl-is-face 'font-lock-other-emphasized-face))
6126               (copy-face 'font-lock-other-emphasized-face
6127                          'cperl-hash-face))
6128           (if (and
6129                (not (cperl-is-face 'cperl-nonoverridable-face))
6130                (cperl-is-face 'font-lock-other-type-face))
6131               (copy-face 'font-lock-other-type-face
6132                          'cperl-nonoverridable-face))
6133           ;;(or (boundp 'cperl-hash-face)
6134           ;;    (defconst cperl-hash-face
6135           ;;    'cperl-hash-face
6136           ;;    "Face to use for hashes."))
6137           ;;(or (boundp 'cperl-array-face)
6138           ;;    (defconst cperl-array-face
6139           ;;    'cperl-array-face
6140           ;;    "Face to use for arrays."))
6141           ;; Here we try to guess background
6142           (let ((background
6143                  (if (boundp 'font-lock-background-mode)
6144                      font-lock-background-mode
6145                    'light))
6146                 (face-list (and (fboundp 'face-list) (face-list))))
6147 ;;;;        (fset 'cperl-is-face
6148 ;;;;              (cond ((fboundp 'find-face)
6149 ;;;;                     (symbol-function 'find-face))
6150 ;;;;                    (face-list
6151 ;;;;                     (function (lambda (face) (member face face-list))))
6152 ;;;;                    (t
6153 ;;;;                     (function (lambda (face) (boundp face))))))
6154             (defvar cperl-guessed-background
6155               (if (and (boundp 'font-lock-display-type)
6156                        (eq font-lock-display-type 'grayscale))
6157                   'gray
6158                 background)
6159               "Background as guessed by CPerl mode")
6160             (and (not (cperl-is-face 'font-lock-constant-face))
6161                  (cperl-is-face 'font-lock-reference-face)
6162                  (copy-face 'font-lock-reference-face 'font-lock-constant-face))
6163             (if (cperl-is-face 'font-lock-type-face) nil
6164               (copy-face 'default 'font-lock-type-face)
6165               (cond
6166                ((eq background 'light)
6167                 (set-face-foreground 'font-lock-type-face
6168                                      (if (x-color-defined-p "seagreen")
6169                                          "seagreen"
6170                                        "sea green")))
6171                ((eq background 'dark)
6172                 (set-face-foreground 'font-lock-type-face
6173                                      (if (x-color-defined-p "os2pink")
6174                                          "os2pink"
6175                                        "pink")))
6176                (t
6177                 (set-face-background 'font-lock-type-face "gray90"))))
6178             (if (cperl-is-face 'cperl-nonoverridable-face)
6179                 nil
6180               (copy-face 'font-lock-type-face 'cperl-nonoverridable-face)
6181               (cond
6182                ((eq background 'light)
6183                 (set-face-foreground 'cperl-nonoverridable-face
6184                                      (if (x-color-defined-p "chartreuse3")
6185                                          "chartreuse3"
6186                                        "chartreuse")))
6187                ((eq background 'dark)
6188                 (set-face-foreground 'cperl-nonoverridable-face
6189                                      (if (x-color-defined-p "orchid1")
6190                                          "orchid1"
6191                                        "orange")))))
6192 ;;;         (if (cperl-is-face 'font-lock-other-emphasized-face) nil
6193 ;;;           (copy-face 'bold-italic 'font-lock-other-emphasized-face)
6194 ;;;           (cond
6195 ;;;            ((eq background 'light)
6196 ;;;             (set-face-background 'font-lock-other-emphasized-face
6197 ;;;                                  (if (x-color-defined-p "lightyellow2")
6198 ;;;                                      "lightyellow2"
6199 ;;;                                    (if (x-color-defined-p "lightyellow")
6200 ;;;                                        "lightyellow"
6201 ;;;                                      "light yellow"))))
6202 ;;;            ((eq background 'dark)
6203 ;;;             (set-face-background 'font-lock-other-emphasized-face
6204 ;;;                                  (if (x-color-defined-p "navy")
6205 ;;;                                      "navy"
6206 ;;;                                    (if (x-color-defined-p "darkgreen")
6207 ;;;                                        "darkgreen"
6208 ;;;                                      "dark green"))))
6209 ;;;            (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
6210 ;;;         (if (cperl-is-face 'font-lock-emphasized-face) nil
6211 ;;;           (copy-face 'bold 'font-lock-emphasized-face)
6212 ;;;           (cond
6213 ;;;            ((eq background 'light)
6214 ;;;             (set-face-background 'font-lock-emphasized-face
6215 ;;;                                  (if (x-color-defined-p "lightyellow2")
6216 ;;;                                      "lightyellow2"
6217 ;;;                                    "lightyellow")))
6218 ;;;            ((eq background 'dark)
6219 ;;;             (set-face-background 'font-lock-emphasized-face
6220 ;;;                                  (if (x-color-defined-p "navy")
6221 ;;;                                      "navy"
6222 ;;;                                    (if (x-color-defined-p "darkgreen")
6223 ;;;                                        "darkgreen"
6224 ;;;                                      "dark green"))))
6225 ;;;            (t (set-face-background 'font-lock-emphasized-face "gray90"))))
6226             (if (cperl-is-face 'font-lock-variable-name-face) nil
6227               (copy-face 'italic 'font-lock-variable-name-face))
6228             (if (cperl-is-face 'font-lock-constant-face) nil
6229               (copy-face 'italic 'font-lock-constant-face))))
6230         (setq cperl-faces-init t))
6231     (error (message "cperl-init-faces (ignored): %s" errs))))
6232
6233
6234 (defun cperl-ps-print-init ()
6235   "Initialization of `ps-print' components for faces used in CPerl."
6236   (eval-after-load "ps-print"
6237     '(setq ps-bold-faces
6238            ;;                   font-lock-variable-name-face
6239            ;;                   font-lock-constant-face
6240            (append '(cperl-array-face
6241                      cperl-hash-face)
6242                    ps-bold-faces)
6243            ps-italic-faces
6244            ;;                   font-lock-constant-face
6245            (append '(cperl-nonoverridable-face
6246                      cperl-hash-face)
6247                    ps-italic-faces)
6248            ps-underlined-faces
6249            ;;        font-lock-type-face
6250            (append '(cperl-array-face
6251                      cperl-hash-face
6252                      underline
6253                      cperl-nonoverridable-face)
6254                    ps-underlined-faces))))
6255
6256 (defvar ps-print-face-extension-alist)
6257
6258 (defun cperl-ps-print (&optional file)
6259   "Pretty-print in CPerl style.
6260 If optional argument FILE is an empty string, prints to printer, otherwise
6261 to the file FILE.  If FILE is nil, prompts for a file name.
6262
6263 Style of printout regulated by the variable `cperl-ps-print-face-properties'."
6264   (interactive)
6265   (or file
6266       (setq file (read-from-minibuffer
6267                   "Print to file (if empty - to printer): "
6268                   (concat (buffer-file-name) ".ps")
6269                   nil nil 'file-name-history)))
6270   (or (> (length file) 0)
6271       (setq file nil))
6272   (require 'ps-print)                   ; To get ps-print-face-extension-alist
6273   (let ((ps-print-color-p t)
6274         (ps-print-face-extension-alist ps-print-face-extension-alist))
6275     (cperl-ps-extend-face-list cperl-ps-print-face-properties)
6276     (ps-print-buffer-with-faces file)))
6277
6278 ;;; (defun cperl-ps-print-init ()
6279 ;;;   "Initialization of `ps-print' components for faces used in CPerl."
6280 ;;;   ;; Guard against old versions
6281 ;;;   (defvar ps-underlined-faces nil)
6282 ;;;   (defvar ps-bold-faces nil)
6283 ;;;   (defvar ps-italic-faces nil)
6284 ;;;   (setq ps-bold-faces
6285 ;;;     (append '(font-lock-emphasized-face
6286 ;;;               cperl-array-face
6287 ;;;               font-lock-keyword-face
6288 ;;;               font-lock-variable-name-face
6289 ;;;               font-lock-constant-face
6290 ;;;               font-lock-reference-face
6291 ;;;               font-lock-other-emphasized-face
6292 ;;;               cperl-hash-face)
6293 ;;;             ps-bold-faces))
6294 ;;;   (setq ps-italic-faces
6295 ;;;     (append '(cperl-nonoverridable-face
6296 ;;;               font-lock-constant-face
6297 ;;;               font-lock-reference-face
6298 ;;;               font-lock-other-emphasized-face
6299 ;;;               cperl-hash-face)
6300 ;;;             ps-italic-faces))
6301 ;;;   (setq ps-underlined-faces
6302 ;;;     (append '(font-lock-emphasized-face
6303 ;;;               cperl-array-face
6304 ;;;               font-lock-other-emphasized-face
6305 ;;;               cperl-hash-face
6306 ;;;               cperl-nonoverridable-face font-lock-type-face)
6307 ;;;             ps-underlined-faces))
6308 ;;;   (cons 'font-lock-type-face ps-underlined-faces))
6309
6310
6311 (if (cperl-enable-font-lock) (cperl-windowed-init))
6312
6313 (defconst cperl-styles-entries
6314   '(cperl-indent-level cperl-brace-offset cperl-continued-brace-offset
6315     cperl-label-offset cperl-extra-newline-before-brace
6316     cperl-merge-trailing-else
6317     cperl-continued-statement-offset))
6318
6319 (defconst cperl-style-alist
6320   '(("CPerl"                         ; =GNU without extra-newline-before-brace
6321      (cperl-indent-level               .  2)
6322      (cperl-brace-offset               .  0)
6323      (cperl-continued-brace-offset     .  0)
6324      (cperl-label-offset               . -2)
6325      (cperl-extra-newline-before-brace .  nil)
6326      (cperl-merge-trailing-else        .  t)
6327      (cperl-continued-statement-offset .  2))
6328     ("PerlStyle"                        ; CPerl with 4 as indent
6329      (cperl-indent-level               .  4)
6330      (cperl-brace-offset               .  0)
6331      (cperl-continued-brace-offset     .  0)
6332      (cperl-label-offset               . -4)
6333      (cperl-extra-newline-before-brace .  nil)
6334      (cperl-merge-trailing-else        .  t)
6335      (cperl-continued-statement-offset .  4))
6336     ("GNU"
6337      (cperl-indent-level               .  2)
6338      (cperl-brace-offset               .  0)
6339      (cperl-continued-brace-offset     .  0)
6340      (cperl-label-offset               . -2)
6341      (cperl-extra-newline-before-brace .  t)
6342      (cperl-merge-trailing-else        .  nil)
6343      (cperl-continued-statement-offset .  2))
6344     ("K&R"
6345      (cperl-indent-level               .  5)
6346      (cperl-brace-offset               .  0)
6347      (cperl-continued-brace-offset     . -5)
6348      (cperl-label-offset               . -5)
6349      ;;(cperl-extra-newline-before-brace .  nil) ; ???
6350      (cperl-merge-trailing-else        .  nil)
6351      (cperl-continued-statement-offset .  5))
6352     ("BSD"
6353      (cperl-indent-level               .  4)
6354      (cperl-brace-offset               .  0)
6355      (cperl-continued-brace-offset     . -4)
6356      (cperl-label-offset               . -4)
6357      ;;(cperl-extra-newline-before-brace .  nil) ; ???
6358      (cperl-continued-statement-offset .  4))
6359     ("C++"
6360      (cperl-indent-level               .  4)
6361      (cperl-brace-offset               .  0)
6362      (cperl-continued-brace-offset     . -4)
6363      (cperl-label-offset               . -4)
6364      (cperl-continued-statement-offset .  4)
6365      (cperl-merge-trailing-else        .  nil)
6366      (cperl-extra-newline-before-brace .  t))
6367     ("Current")
6368     ("Whitesmith"
6369      (cperl-indent-level               .  4)
6370      (cperl-brace-offset               .  0)
6371      (cperl-continued-brace-offset     .  0)
6372      (cperl-label-offset               . -4)
6373      ;;(cperl-extra-newline-before-brace .  nil) ; ???
6374      (cperl-continued-statement-offset .  4)))
6375   "(Experimental) list of variables to set to get a particular indentation style.
6376 Should be used via `cperl-set-style' or via Perl menu.")
6377
6378 (defun cperl-set-style (style)
6379   "Set CPerl mode variables to use one of several different indentation styles.
6380 The arguments are a string representing the desired style.
6381 The list of styles is in `cperl-style-alist', available styles
6382 are GNU, K&R, BSD, C++ and Whitesmith.
6383
6384 The current value of style is memorized (unless there is a memorized
6385 data already), may be restored by `cperl-set-style-back'.
6386
6387 Chosing \"Current\" style will not change style, so this may be used for
6388 side-effect of memorizing only."
6389   (interactive
6390    (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
6391                        cperl-style-alist)))
6392      (list (completing-read "Enter style: " list nil 'insist))))
6393   (or cperl-old-style
6394       (setq cperl-old-style
6395             (mapcar (function
6396                      (lambda (name)
6397                        (cons name (eval name))))
6398                     cperl-styles-entries)))
6399   (let ((style (cdr (assoc style cperl-style-alist))) setting str sym)
6400     (while style
6401       (setq setting (car style) style (cdr style))
6402       (set (car setting) (cdr setting)))))
6403
6404 (defun cperl-set-style-back ()
6405   "Restore a style memorised by `cperl-set-style'."
6406   (interactive)
6407   (or cperl-old-style (error "The style was not changed"))
6408   (let (setting)
6409     (while cperl-old-style
6410       (setq setting (car cperl-old-style)
6411             cperl-old-style (cdr cperl-old-style))
6412       (set (car setting) (cdr setting)))))
6413
6414 (defun cperl-check-syntax ()
6415   (interactive)
6416   (require 'mode-compile)
6417   (let ((perl-dbg-flags (concat cperl-extra-perl-args " -wc")))
6418     (eval '(mode-compile))))            ; Avoid a warning
6419
6420 (defun cperl-info-buffer (type)
6421   ;; Returns buffer with documentation.  Creates if missing.
6422   ;; If TYPE, this vars buffer.
6423   ;; Special care is taken to not stomp over an existing info buffer
6424   (let* ((bname (if type "*info-perl-var*" "*info-perl*"))
6425          (info (get-buffer bname))
6426          (oldbuf (get-buffer "*info*")))
6427     (if info info
6428       (save-window-excursion
6429         ;; Get Info running
6430         (require 'info)
6431         (cond (oldbuf
6432                (set-buffer oldbuf)
6433                (rename-buffer "*info-perl-tmp*")))
6434         (save-window-excursion
6435           (info))
6436         (Info-find-node cperl-info-page (if type "perlvar" "perlfunc"))
6437         (set-buffer "*info*")
6438         (rename-buffer bname)
6439         (cond (oldbuf
6440                (set-buffer "*info-perl-tmp*")
6441                (rename-buffer "*info*")
6442                (set-buffer bname)))
6443         (make-local-variable 'window-min-height)
6444         (setq window-min-height 2)
6445         (current-buffer)))))
6446
6447 (defun cperl-word-at-point (&optional p)
6448   "Return the word at point or at P."
6449   (save-excursion
6450     (if p (goto-char p))
6451     (or (cperl-word-at-point-hard)
6452         (progn
6453           (require 'etags)
6454           (funcall (or (and (boundp 'find-tag-default-function)
6455                             find-tag-default-function)
6456                        (get major-mode 'find-tag-default-function)
6457                        ;; XEmacs 19.12 has `find-tag-default-hook'; it is
6458                        ;; automatically used within `find-tag-default':
6459                        'find-tag-default))))))
6460
6461 (defun cperl-info-on-command (command)
6462   "Show documentation for Perl command COMMAND in other window.
6463 If perl-info buffer is shown in some frame, uses this frame.
6464 Customized by setting variables `cperl-shrink-wrap-info-frame',
6465 `cperl-max-help-size'."
6466   (interactive
6467    (let* ((default (cperl-word-at-point))
6468           (read (read-string
6469                  (format "Find doc for Perl function (default %s): "
6470                          default))))
6471      (list (if (equal read "")
6472                default
6473              read))))
6474
6475   (let ((buffer (current-buffer))
6476         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
6477         pos isvar height iniheight frheight buf win fr1 fr2 iniwin not-loner
6478         max-height char-height buf-list)
6479     (if (string-match "^-[a-zA-Z]$" command)
6480         (setq cmd-desc "^-X[ \t\n]"))
6481     (setq isvar (string-match "^[$@%]" command)
6482           buf (cperl-info-buffer isvar)
6483           iniwin (selected-window)
6484           fr1 (window-frame iniwin))
6485     (set-buffer buf)
6486     (beginning-of-buffer)
6487     (or isvar
6488         (progn (re-search-forward "^-X[ \t\n]")
6489                (forward-line -1)))
6490     (if (re-search-forward cmd-desc nil t)
6491         (progn
6492           ;; Go back to beginning of the group (ex, for qq)
6493           (if (re-search-backward "^[ \t\n\f]")
6494               (forward-line 1))
6495           (beginning-of-line)
6496           ;; Get some of
6497           (setq pos (point)
6498                 buf-list (list buf "*info-perl-var*" "*info-perl*"))
6499           (while (and (not win) buf-list)
6500             (setq win (get-buffer-window (car buf-list) t))
6501             (setq buf-list (cdr buf-list)))
6502           (or (not win)
6503               (eq (window-buffer win) buf)
6504               (set-window-buffer win buf))
6505           (and win (setq fr2 (window-frame win)))
6506           (if (or (not fr2) (eq fr1 fr2))
6507               (pop-to-buffer buf)
6508             (special-display-popup-frame buf) ; Make it visible
6509             (select-window win))
6510           (goto-char pos)               ; Needed (?!).
6511           ;; Resize
6512           (setq iniheight (window-height)
6513                 frheight (frame-height)
6514                 not-loner (< iniheight (1- frheight))) ; Are not alone
6515           (cond ((if not-loner cperl-max-help-size
6516                    cperl-shrink-wrap-info-frame)
6517                  (setq height
6518                        (+ 2
6519                           (count-lines
6520                            pos
6521                            (save-excursion
6522                              (if (re-search-forward
6523                                   "^[ \t][^\n]*\n+\\([^ \t\n\f]\\|\\'\\)" nil t)
6524                                  (match-beginning 0) (point-max)))))
6525                        max-height
6526                        (if not-loner
6527                            (/ (* (- frheight 3) cperl-max-help-size) 100)
6528                          (setq char-height (frame-char-height))
6529                          ;; Non-functioning under OS/2:
6530                          (if (eq char-height 1) (setq char-height 18))
6531                          ;; Title, menubar, + 2 for slack
6532                          (- (/ (x-display-pixel-height) char-height) 4)))
6533                  (if (> height max-height) (setq height max-height))
6534                  ;;(message "was %s doing %s" iniheight height)
6535                  (if not-loner
6536                      (enlarge-window (- height iniheight))
6537                    (set-frame-height (window-frame win) (1+ height)))))
6538           (set-window-start (selected-window) pos))
6539       (message "No entry for %s found." command))
6540     ;;(pop-to-buffer buffer)
6541     (select-window iniwin)))
6542
6543 (defun cperl-info-on-current-command ()
6544   "Show documentation for Perl command at point in other window."
6545   (interactive)
6546   (cperl-info-on-command (cperl-word-at-point)))
6547
6548 (defun cperl-imenu-info-imenu-search ()
6549   (if (looking-at "^-X[ \t\n]") nil
6550     (re-search-backward
6551      "^\n\\([-a-zA-Z_]+\\)[ \t\n]")
6552     (forward-line 1)))
6553
6554 (defun cperl-imenu-info-imenu-name ()
6555   (buffer-substring
6556    (match-beginning 1) (match-end 1)))
6557
6558 (defun cperl-imenu-on-info ()
6559   (interactive)
6560   (let* ((buffer (current-buffer))
6561          imenu-create-index-function
6562          imenu-prev-index-position-function
6563          imenu-extract-index-name-function
6564          (index-item (save-restriction
6565                        (save-window-excursion
6566                          (set-buffer (cperl-info-buffer nil))
6567                          (setq imenu-create-index-function
6568                                'imenu-default-create-index-function
6569                                imenu-prev-index-position-function
6570                                'cperl-imenu-info-imenu-search
6571                                imenu-extract-index-name-function
6572                                'cperl-imenu-info-imenu-name)
6573                          (imenu-choose-buffer-index)))))
6574     (and index-item
6575          (progn
6576            (push-mark)
6577            (pop-to-buffer "*info-perl*")
6578            (cond
6579             ((markerp (cdr index-item))
6580              (goto-char (marker-position (cdr index-item))))
6581             (t
6582              (goto-char (cdr index-item))))
6583            (set-window-start (selected-window) (point))
6584            (pop-to-buffer buffer)))))
6585
6586 (defun cperl-lineup (beg end &optional step minshift)
6587   "Lineup construction in a region.
6588 Beginning of region should be at the start of a construction.
6589 All first occurrences of this construction in the lines that are
6590 partially contained in the region are lined up at the same column.
6591
6592 MINSHIFT is the minimal amount of space to insert before the construction.
6593 STEP is the tabwidth to position constructions.
6594 If STEP is nil, `cperl-lineup-step' will be used
6595 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
6596 Will not move the position at the start to the left."
6597   (interactive "r")
6598   (let (search col tcol seen b e)
6599     (save-excursion
6600       (goto-char end)
6601       (end-of-line)
6602       (setq end (point-marker))
6603       (goto-char beg)
6604       (skip-chars-forward " \t\f")
6605       (setq beg (point-marker))
6606       (indent-region beg end nil)
6607       (goto-char beg)
6608       (setq col (current-column))
6609       (if (looking-at "[a-zA-Z0-9_]")
6610           (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
6611               (setq search
6612                     (concat "\\<"
6613                             (regexp-quote
6614                              (buffer-substring (match-beginning 0)
6615                                                (match-end 0))) "\\>"))
6616             (error "Cannot line up in a middle of the word"))
6617         (if (looking-at "$")
6618             (error "Cannot line up end of line"))
6619         (setq search (regexp-quote (char-to-string (following-char)))))
6620       (setq step (or step cperl-lineup-step cperl-indent-level))
6621       (or minshift (setq minshift 1))
6622       (while (progn
6623                (beginning-of-line 2)
6624                (and (< (point) end)
6625                     (re-search-forward search end t)
6626                     (goto-char (match-beginning 0))))
6627         (setq tcol (current-column) seen t)
6628         (if (> tcol col) (setq col tcol)))
6629       (or seen
6630           (error "The construction to line up occurred only once"))
6631       (goto-char beg)
6632       (setq col (+ col minshift))
6633       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
6634       (while
6635           (progn
6636             (setq e (point))
6637             (skip-chars-backward " \t")
6638             (delete-region (point) e)
6639             (indent-to-column col) ;(make-string (- col (current-column)) ?\ ))
6640             (beginning-of-line 2)
6641             (and (< (point) end)
6642                  (re-search-forward search end t)
6643                  (goto-char (match-beginning 0)))))))) ; No body
6644
6645 (defun cperl-etags (&optional add all files)
6646   "Run etags with appropriate options for Perl files.
6647 If optional argument ALL is `recursive', will process Perl files
6648 in subdirectories too."
6649   (interactive)
6650   (let ((cmd "etags")
6651         (args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\(([^()]*)[ \t]*\\)?\\([{#]\\|$\\)\\)/\\4/"))
6652         res)
6653     (if add (setq args (cons "-a" args)))
6654     (or files (setq files (list buffer-file-name)))
6655     (cond
6656      ((eq all 'recursive)
6657       ;;(error "Not implemented: recursive")
6658       (setq args (append (list "-e"
6659                                "sub wanted {push @ARGV, $File::Find::name if /\\.[pP][Llm]$/}
6660                                 use File::Find;
6661                                 find(\\&wanted, '.');
6662                                 exec @ARGV;"
6663                                cmd) args)
6664             cmd "perl"))
6665      (all
6666       ;;(error "Not implemented: all")
6667       (setq args (append (list "-e"
6668                                "push @ARGV, <*.PL *.pl *.pm>;
6669                                 exec @ARGV;"
6670                                cmd) args)
6671             cmd "perl"))
6672      (t
6673       (setq args (append args files))))
6674     (setq res (apply 'call-process cmd nil nil nil args))
6675     (or (eq res 0)
6676         (message "etags returned \"%s\"" res))))
6677
6678 (defun cperl-toggle-auto-newline ()
6679   "Toggle the state of `cperl-auto-newline'."
6680   (interactive)
6681   (setq cperl-auto-newline (not cperl-auto-newline))
6682   (message "Newlines will %sbe auto-inserted now."
6683            (if cperl-auto-newline "" "not ")))
6684
6685 (defun cperl-toggle-abbrev ()
6686   "Toggle the state of automatic keyword expansion in CPerl mode."
6687   (interactive)
6688   (abbrev-mode (if abbrev-mode 0 1))
6689   (message "Perl control structure will %sbe auto-inserted now."
6690            (if abbrev-mode "" "not ")))
6691
6692
6693 (defun cperl-toggle-electric ()
6694   "Toggle the state of parentheses doubling in CPerl mode."
6695   (interactive)
6696   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
6697   (message "Parentheses will %sbe auto-doubled now."
6698            (if (cperl-val 'cperl-electric-parens) "" "not ")))
6699
6700 (defun cperl-toggle-autohelp ()
6701   "Toggle the state of Auto-Help on Perl constructs (put in the message area).
6702 Delay of auto-help controlled by `cperl-lazy-help-time'."
6703   (interactive)
6704   (if (fboundp 'run-with-idle-timer)
6705       (progn
6706         (if cperl-lazy-installed
6707             (cperl-lazy-unstall)
6708           (cperl-lazy-install))
6709         (message "Perl help messages will %sbe automatically shown now."
6710                  (if cperl-lazy-installed "" "not ")))
6711     (message "Cannot automatically show Perl help messages - run-with-idle-timer missing.")))
6712
6713 (defun cperl-toggle-construct-fix ()
6714   "Toggle whether `indent-region'/`indent-sexp' fix whitespace too."
6715   (interactive)
6716   (setq cperl-indent-region-fix-constructs
6717         (if cperl-indent-region-fix-constructs
6718             nil
6719           1))
6720   (message "indent-region/indent-sexp will %sbe automatically fix whitespace."
6721            (if cperl-indent-region-fix-constructs "" "not ")))
6722
6723 ;;;; Tags file creation.
6724
6725 (defvar cperl-tmp-buffer " *cperl-tmp*")
6726
6727 (defun cperl-setup-tmp-buf ()
6728   (set-buffer (get-buffer-create cperl-tmp-buffer))
6729   (set-syntax-table cperl-mode-syntax-table)
6730   (buffer-disable-undo)
6731   (auto-fill-mode 0)
6732   (if cperl-use-syntax-table-text-property-for-tags
6733       (progn
6734         (make-local-variable 'parse-sexp-lookup-properties)
6735         ;; Do not introduce variable if not needed, we check it!
6736         (set 'parse-sexp-lookup-properties t))))
6737
6738 (defun cperl-xsub-scan ()
6739   (require 'cl)
6740   (require 'imenu)
6741   (let ((index-alist '())
6742         (prev-pos 0) index index1 name package prefix)
6743     (goto-char (point-min))
6744     (if noninteractive
6745         (message "Scanning XSUB for index")
6746       (imenu-progress-message prev-pos 0))
6747     ;; Search for the function
6748     (progn ;;save-match-data
6749       (while (re-search-forward
6750               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
6751               nil t)
6752         (or noninteractive
6753             (imenu-progress-message prev-pos))
6754         (cond
6755          ((match-beginning 2)           ; SECTION
6756           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
6757           (goto-char (match-beginning 0))
6758           (skip-chars-forward " \t")
6759           (forward-char 1)
6760           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
6761               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
6762             (setq prefix nil)))
6763          ((not package) nil)            ; C language section
6764          ((match-beginning 3)           ; XSUB
6765           (goto-char (1+ (match-beginning 3)))
6766           (setq index (imenu-example--name-and-position))
6767           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
6768           (if (and prefix (string-match (concat "^" prefix) name))
6769               (setq name (substring name (length prefix))))
6770           (cond ((string-match "::" name) nil)
6771                 (t
6772                  (setq index1 (cons (concat package "::" name) (cdr index)))
6773                  (push index1 index-alist)))
6774           (setcar index name)
6775           (push index index-alist))
6776          (t                             ; BOOT: section
6777           ;; (beginning-of-line)
6778           (setq index (imenu-example--name-and-position))
6779           (setcar index (concat package "::BOOT:"))
6780           (push index index-alist)))))
6781     (or noninteractive
6782         (imenu-progress-message prev-pos 100))
6783     index-alist))
6784
6785 (defvar cperl-unreadable-ok nil)
6786
6787 (defun cperl-find-tags (ifile xs topdir)
6788   (let ((b (get-buffer cperl-tmp-buffer)) ind lst elt pos ret rel
6789         (cperl-pod-here-fontify nil) f file)
6790     (save-excursion
6791       (if b (set-buffer b)
6792         (cperl-setup-tmp-buf))
6793       (erase-buffer)
6794       (condition-case err
6795           (setq file (car (insert-file-contents ifile)))
6796         (error (if cperl-unreadable-ok nil
6797                  (if (y-or-n-p
6798                       (format "File %s unreadable.  Continue? " ifile))
6799                      (setq cperl-unreadable-ok t)
6800                    (error "Aborting: unreadable file %s" ifile)))))
6801       (if (not file)
6802           (message "Unreadable file %s" ifile)
6803         (message "Scanning file %s ..." file)
6804         (if (and cperl-use-syntax-table-text-property-for-tags
6805                  (not xs))
6806             (condition-case err         ; after __END__ may have garbage
6807                 (cperl-find-pods-heres nil nil noninteractive)
6808               (error (message "While scanning for syntax: %s" err))))
6809         (if xs
6810             (setq lst (cperl-xsub-scan))
6811           (setq ind (cperl-imenu--create-perl-index))
6812           (setq lst (cdr (assoc "+Unsorted List+..." ind))))
6813         (setq lst
6814               (mapcar
6815                (function
6816                 (lambda (elt)
6817                   (cond ((string-match "^[_a-zA-Z]" (car elt))
6818                          (goto-char (cdr elt))
6819                          (beginning-of-line) ; pos should be of the start of the line
6820                          (list (car elt)
6821                                (point)
6822                                (1+ (count-lines 1 (point))) ; 1+ since at beg-o-l
6823                                (buffer-substring (progn
6824                                                    (goto-char (cdr elt))
6825                                                    ;; After name now...
6826                                                    (or (eolp) (forward-char 1))
6827                                                    (point))
6828                                                  (progn
6829                                                    (beginning-of-line)
6830                                                    (point))))))))
6831                lst))
6832         (erase-buffer)
6833         (while lst
6834           (setq elt (car lst) lst (cdr lst))
6835           (if elt
6836               (progn
6837                 (insert (elt elt 3)
6838                         127
6839                         (if (string-match "^package " (car elt))
6840                             (substring (car elt) 8)
6841                           (car elt) )
6842                         1
6843                         (number-to-string (elt elt 2)) ; Line
6844                         ","
6845                         (number-to-string (1- (elt elt 1))) ; Char pos 0-based
6846                         "\n")
6847                 (if (and (string-match "^[_a-zA-Z]+::" (car elt))
6848                          (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
6849                                        (elt elt 3)))
6850                     ;; Need to insert the name without package as well
6851                     (setq lst (cons (cons (substring (elt elt 3) 
6852                                                      (match-beginning 1)
6853                                                      (match-end 1))
6854                                           (cdr elt))
6855                                     lst))))))
6856         (setq pos (point))
6857         (goto-char 1)
6858         (setq rel file)
6859         ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
6860         (set-text-properties 0 (length rel) nil rel)
6861         (and (equal topdir (substring rel 0 (length topdir)))
6862              (setq rel (substring file (length topdir))))
6863         (insert "\f\n" rel "," (number-to-string (1- pos)) "\n")
6864         (setq ret (buffer-substring 1 (point-max)))
6865         (erase-buffer)
6866         (or noninteractive
6867             (message "Scanning file %s finished" file))
6868         ret))))
6869
6870 (defun cperl-add-tags-recurse-noxs ()
6871   "Add to TAGS data for Perl and XSUB files in the current directory and kids.
6872 Use as
6873   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
6874         -f cperl-add-tags-recurse
6875 "
6876   (cperl-write-tags nil nil t t nil t))
6877
6878 (defun cperl-add-tags-recurse ()
6879   "Add to TAGS file data for Perl files in the current directory and kids.
6880 Use as
6881   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
6882         -f cperl-add-tags-recurse
6883 "
6884   (cperl-write-tags nil nil t t))
6885
6886 (defun cperl-write-tags (&optional file erase recurse dir inbuffer noxs topdir)
6887   ;; If INBUFFER, do not select buffer, and do not save
6888   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
6889   (require 'etags)
6890   (if file nil
6891     (setq file (if dir default-directory (buffer-file-name)))
6892     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
6893   (or topdir
6894       (setq topdir default-directory))
6895   (let ((tags-file-name "TAGS")
6896         (case-fold-search (eq system-type 'emx))
6897         xs rel tm)
6898     (save-excursion
6899       (cond (inbuffer nil)              ; Already there
6900             ((file-exists-p tags-file-name)
6901              (if cperl-xemacs-p
6902                  (visit-tags-table-buffer)
6903                (visit-tags-table-buffer tags-file-name)))
6904             (t (set-buffer (find-file-noselect tags-file-name))))
6905       (cond
6906        (dir
6907         (cond ((eq erase 'ignore))
6908               (erase
6909                (erase-buffer)
6910                (setq erase 'ignore)))
6911         (let ((files
6912                (condition-case err
6913                    (directory-files file t
6914                                     (if recurse nil cperl-scan-files-regexp)
6915                                     t)
6916                  (error
6917                   (if cperl-unreadable-ok nil
6918                     (if (y-or-n-p
6919                          (format "Directory %s unreadable.  Continue? " file))
6920                         (setq cperl-unreadable-ok t
6921                               tm nil)   ; Return empty list
6922                       (error "Aborting: unreadable directory %s" file)))))))
6923           (mapcar (function 
6924                    (lambda (file)
6925                      (cond
6926                       ((string-match cperl-noscan-files-regexp file)
6927                        nil)
6928                       ((not (file-directory-p file))
6929                        (if (string-match cperl-scan-files-regexp file)
6930                            (cperl-write-tags file erase recurse nil t noxs topdir)))
6931                       ((not recurse) nil)
6932                       (t (cperl-write-tags file erase recurse t t noxs topdir)))))
6933                   files)))
6934        (t
6935         (setq xs (string-match "\\.xs$" file))
6936         (if (not (and xs noxs))
6937             (progn
6938               (cond ((eq erase 'ignore) (goto-char (point-max)))
6939                     (erase (erase-buffer))
6940                     (t
6941                      (goto-char 1)
6942                      (setq rel file)
6943                      ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
6944                      (set-text-properties 0 (length rel) nil rel)
6945                      (and (equal topdir (substring rel 0 (length topdir)))
6946                           (setq rel (substring file (length topdir))))
6947                      (if (search-forward (concat "\f\n" rel ",") nil t)
6948                          (progn
6949                            (search-backward "\f\n")
6950                            (delete-region (point)
6951                                           (save-excursion
6952                                             (forward-char 1)
6953                                             (if (search-forward "\f\n"
6954                                                                 nil 'toend)
6955                                                 (- (point) 2)
6956                                               (point-max)))))
6957                        (goto-char (point-max)))))
6958               (insert (cperl-find-tags file xs topdir))))))
6959       (if inbuffer nil                  ; Delegate to the caller
6960         (save-buffer 0)                 ; No backup
6961         (if (fboundp 'initialize-new-tags-table) ; Do we need something special in XEmacs?
6962             (initialize-new-tags-table))))))
6963
6964 (defvar cperl-tags-hier-regexp-list
6965   (concat
6966    "^\\("
6967       "\\(package\\)\\>"
6968      "\\|"
6969       "sub\\>[^\n]+::"
6970      "\\|"
6971       "[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::" ; XSUB?
6972      "\\|"
6973       "[ \t]*BOOT:\C-?[^\n]+::"         ; BOOT section
6974    "\\)"))
6975
6976 (defvar cperl-hierarchy '(() ())
6977   "Global hierarchy of classes.")
6978
6979 (defun cperl-tags-hier-fill ()
6980   ;; Suppose we are in a tag table cooked by cperl.
6981   (goto-char 1)
6982   (let (type pack name pos line chunk ord cons1 file str info fileind)
6983     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
6984       (setq pos (match-beginning 0)
6985             pack (match-beginning 2))
6986       (beginning-of-line)
6987       (if (looking-at (concat
6988                        "\\([^\n]+\\)"
6989                        "\C-?"
6990                        "\\([^\n]+\\)"
6991                        "\C-a"
6992                        "\\([0-9]+\\)"
6993                        ","
6994                        "\\([0-9]+\\)"))
6995           (progn
6996             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
6997                   name (buffer-substring (match-beginning 2) (match-end 2))
6998                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
6999                   line (buffer-substring (match-beginning 3) (match-end 3))
7000                   ord (if pack 1 0)
7001                   file (file-of-tag)
7002                   fileind (format "%s:%s" file line)
7003                   ;; Moves to beginning of the next line:
7004                   info (cperl-etags-snarf-tag file line))
7005             ;; Move back
7006             (forward-char -1)
7007             ;; Make new member of hierarchy name ==> file ==> pos if needed
7008             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
7009                 ;; Name known
7010                 (setcdr cons1 (cons (cons fileind (vector file info))
7011                                     (cdr cons1)))
7012               ;; First occurrence of the name, start alist
7013               (setq cons1 (cons name (list (cons fileind (vector file info)))))
7014               (if pack
7015                   (setcar (cdr cperl-hierarchy)
7016                           (cons cons1 (nth 1 cperl-hierarchy)))
7017                 (setcar cperl-hierarchy
7018                         (cons cons1 (car cperl-hierarchy)))))))
7019       (end-of-line))))
7020
7021 (defun cperl-tags-hier-init (&optional update)
7022   "Show hierarchical menu of classes and methods.
7023 Finds info about classes by a scan of loaded TAGS files.
7024 Supposes that the TAGS files contain fully qualified function names.
7025 One may build such TAGS files from CPerl mode menu."
7026   (interactive)
7027   (require 'etags)
7028   (require 'imenu)
7029   (if (or update (null (nth 2 cperl-hierarchy)))
7030       (let ((remover (function (lambda (elt) ; (name (file1...) (file2..))
7031                                  (or (nthcdr 2 elt)
7032                                      ;; Only in one file
7033                                      (setcdr elt (cdr (nth 1 elt)))))))
7034             pack name cons1 to l1 l2 l3 l4 b)
7035         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
7036         (setq cperl-hierarchy (list l1 l2 l3))
7037         (if cperl-xemacs-p              ; Not checked
7038             (progn
7039               (or tags-file-name
7040                   ;; Does this work in XEmacs?
7041                   (call-interactively 'visit-tags-table))
7042               (message "Updating list of classes...")
7043               (set-buffer (get-file-buffer tags-file-name))
7044               (cperl-tags-hier-fill))
7045           (or tags-table-list
7046               (call-interactively 'visit-tags-table))
7047           (mapcar 
7048            (function
7049             (lambda (tagsfile)
7050               (message "Updating list of classes... %s" tagsfile)
7051               (set-buffer (get-file-buffer tagsfile))
7052               (cperl-tags-hier-fill)))
7053            tags-table-list)
7054           (message "Updating list of classes... postprocessing..."))
7055         (mapcar remover (car cperl-hierarchy))
7056         (mapcar remover (nth 1 cperl-hierarchy))
7057         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
7058                        (cons "Methods: " (car cperl-hierarchy))))
7059         (cperl-tags-treeify to 1)
7060         (setcar (nthcdr 2 cperl-hierarchy)
7061                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
7062         (message "Updating list of classes: done, requesting display...")
7063         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
7064         ))
7065   (or (nth 2 cperl-hierarchy)
7066       (error "No items found"))
7067   (setq update
7068 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
7069         (if (if (boundp 'display-popup-menus-p)
7070                 (let ((f 'display-popup-menus-p))
7071                   (funcall f))
7072               window-system)
7073             (x-popup-menu t (nth 2 cperl-hierarchy))
7074           (require 'tmm)
7075           (tmm-prompt (nth 2 cperl-hierarchy))))
7076   (if (and update (listp update))
7077       (progn (while (cdr update) (setq update (cdr update)))
7078              (setq update (car update)))) ; Get the last from the list
7079   (if (vectorp update)
7080       (progn
7081         (find-file (elt update 0))
7082         (cperl-etags-goto-tag-location (elt update 1))))
7083   (if (eq update -999) (cperl-tags-hier-init t)))
7084
7085 (defun cperl-tags-treeify (to level)
7086   ;; cadr of `to' is read-write.  On start it is a cons
7087   (let* ((regexp (concat "^\\(" (mapconcat
7088                                  'identity
7089                                  (make-list level "[_a-zA-Z0-9]+")
7090                                  "::")
7091                          "\\)\\(::\\)?"))
7092          (packages (cdr (nth 1 to)))
7093          (methods (cdr (nth 2 to)))
7094          l1 head tail cons1 cons2 ord writeto packs recurse
7095          root-packages root-functions ms many_ms same_name ps
7096          (move-deeper
7097           (function 
7098            (lambda (elt)
7099              (cond ((and (string-match regexp (car elt))
7100                          (or (eq ord 1) (match-end 2)))
7101                     (setq head (substring (car elt) 0 (match-end 1))
7102                           tail (if (match-end 2) (substring (car elt) 
7103                                                             (match-end 2)))
7104                           recurse t)
7105                     (if (setq cons1 (assoc head writeto)) nil
7106                       ;; Need to init new head
7107                       (setcdr writeto (cons (list head (list "Packages: ")
7108                                                   (list "Methods: "))
7109                                             (cdr writeto)))
7110                       (setq cons1 (nth 1 writeto)))
7111                     (setq cons2 (nth ord cons1)) ; Either packs or meths
7112                     (setcdr cons2 (cons elt (cdr cons2))))
7113                    ((eq ord 2)
7114                     (setq root-functions (cons elt root-functions)))
7115                    (t
7116                     (setq root-packages (cons elt root-packages))))))))
7117     (setcdr to l1)                      ; Init to dynamic space
7118     (setq writeto to)
7119     (setq ord 1)
7120     (mapcar move-deeper packages)
7121     (setq ord 2)
7122     (mapcar move-deeper methods)
7123     (if recurse
7124         (mapcar (function (lambda (elt)
7125                           (cperl-tags-treeify elt (1+ level))))
7126                 (cdr to)))
7127     ;;Now clean up leaders with one child only
7128     (mapcar (function (lambda (elt)
7129                         (if (not (and (listp (cdr elt)) 
7130                                       (eq (length elt) 2))) nil
7131                             (setcar elt (car (nth 1 elt)))
7132                             (setcdr elt (cdr (nth 1 elt))))))
7133             (cdr to))
7134     ;; Sort the roots of subtrees
7135     (if (default-value 'imenu-sort-function)
7136         (setcdr to
7137                 (sort (cdr to) (default-value 'imenu-sort-function))))
7138     ;; Now add back functions removed from display
7139     (mapcar (function (lambda (elt)
7140                         (setcdr to (cons elt (cdr to)))))
7141             (if (default-value 'imenu-sort-function)
7142                 (nreverse
7143                  (sort root-functions (default-value 'imenu-sort-function)))
7144               root-functions))
7145     ;; Now add back packages removed from display
7146     (mapcar (function (lambda (elt)
7147                         (setcdr to (cons (cons (concat "package " (car elt)) 
7148                                                (cdr elt)) 
7149                                          (cdr to)))))
7150             (if (default-value 'imenu-sort-function)
7151                 (nreverse
7152                  (sort root-packages (default-value 'imenu-sort-function)))
7153               root-packages))))
7154
7155 ;;;(x-popup-menu t
7156 ;;;   '(keymap "Name1"
7157 ;;;         ("Ret1" "aa")
7158 ;;;         ("Head1" "ab"
7159 ;;;          keymap "Name2"
7160 ;;;          ("Tail1" "x") ("Tail2" "y"))))
7161
7162 (defun cperl-list-fold (list name limit)
7163   (let (list1 list2 elt1 (num 0))
7164     (if (<= (length list) limit) list
7165       (setq list1 nil list2 nil)
7166       (while list
7167         (setq num (1+ num)
7168               elt1 (car list)
7169               list (cdr list))
7170         (if (<= num imenu-max-items)
7171             (setq list2 (cons elt1 list2))
7172           (setq list1 (cons (cons name
7173                                   (nreverse list2))
7174                             list1)
7175                 list2 (list elt1)
7176                 num 1)))
7177       (nreverse (cons (cons name
7178                             (nreverse list2))
7179                       list1)))))
7180
7181 (defun cperl-menu-to-keymap (menu &optional name)
7182   (let (list)
7183     (cons 'keymap
7184           (mapcar
7185            (function
7186             (lambda (elt)
7187               (cond ((listp (cdr elt))
7188                      (setq list (cperl-list-fold
7189                                  (cdr elt) (car elt) imenu-max-items))
7190                      (cons nil
7191                            (cons (car elt)
7192                                  (cperl-menu-to-keymap list))))
7193                     (t
7194                      (list (cdr elt) (car elt) t))))) ; t is needed in 19.34
7195            (cperl-list-fold menu "Root" imenu-max-items)))))
7196
7197 \f
7198 (defvar cperl-bad-style-regexp
7199   (mapconcat 'identity
7200              '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
7201                "[-<>=+^&|]+[^- \t\n=+<>~]") ; sign+ char 
7202              "\\|")
7203   "Finds places such that insertion of a whitespace may help a lot.")
7204
7205 (defvar cperl-not-bad-style-regexp
7206   (mapconcat 
7207    'identity
7208    '("[^-\t <>=+]\\(--\\|\\+\\+\\)"     ; var-- var++
7209      "[a-zA-Z0-9_][|&][a-zA-Z0-9_$]"    ; abc|def abc&def are often used.
7210      "&[(a-zA-Z0-9_$]"                  ; &subroutine &(var->field)
7211      "<\\$?\\sw+\\(\\.\\sw+\\)?>"       ; <IN> <stdin.h>
7212      "-[a-zA-Z][ \t]+[_$\"'`a-zA-Z]"    ; -f file, -t STDIN
7213      "-[0-9]"                           ; -5
7214      "\\+\\+"                           ; ++var
7215      "--"                               ; --var
7216      ".->"                              ; a->b
7217      "->"                               ; a SPACE ->b
7218      "\\[-"                             ; a[-1]
7219      "\\\\[&$@*\\\\]"                   ; \&func
7220      "^="                               ; =head
7221      "\\$."                             ; $|
7222      "<<[a-zA-Z_'\"`]"                  ; <<FOO, <<'FOO'
7223      "||"
7224      "&&"
7225      "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
7226      "-[a-zA-Z_0-9]+[ \t]*=>"           ; -option => value
7227      ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
7228      ;;"[*/+-|&<.]+="
7229      )
7230    "\\|")
7231   "If matches at the start of match found by `my-bad-c-style-regexp',
7232 insertion of a whitespace will not help.")
7233
7234 (defvar found-bad)
7235
7236 (defun cperl-find-bad-style ()
7237   "Find places in the buffer where insertion of a whitespace may help.
7238 Prompts user for insertion of spaces.
7239 Currently it is tuned to C and Perl syntax."
7240   (interactive)
7241   (let (found-bad (p (point)))
7242     (setq last-nonmenu-event 13)        ; To disable popup
7243     (beginning-of-buffer)
7244     (map-y-or-n-p "Insert space here? "
7245                   (lambda (arg) (insert " "))
7246                   'cperl-next-bad-style
7247                   '("location" "locations" "insert a space into")
7248                   '((?\C-r (lambda (arg)
7249                              (let ((buffer-quit-function
7250                                     'exit-recursive-edit))
7251                                (message "Exit with Esc Esc")
7252                                (recursive-edit)
7253                                t))      ; Consider acted upon
7254                            "edit, exit with Esc Esc")
7255                     (?e (lambda (arg)
7256                           (let ((buffer-quit-function
7257                                  'exit-recursive-edit))
7258                             (message "Exit with Esc Esc")
7259                             (recursive-edit)
7260                             t))         ; Consider acted upon
7261                         "edit, exit with Esc Esc"))
7262                   t)
7263     (if found-bad (goto-char found-bad)
7264       (goto-char p)
7265       (message "No appropriate place found"))))
7266
7267 (defun cperl-next-bad-style ()
7268   (let (p (not-found t) (point (point)) found)
7269     (while (and not-found
7270                 (re-search-forward cperl-bad-style-regexp nil 'to-end))
7271       (setq p (point))
7272       (goto-char (match-beginning 0))
7273       (if (or
7274            (looking-at cperl-not-bad-style-regexp)
7275            ;; Check for a < -b and friends
7276            (and (eq (following-char) ?\-)
7277                 (save-excursion
7278                   (skip-chars-backward " \t\n")
7279                   (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\( ?\[ ?\{))))
7280            ;; Now check for syntax type
7281            (save-match-data
7282              (setq found (point))
7283              (beginning-of-defun)
7284              (let ((pps (parse-partial-sexp (point) found)))
7285                (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
7286           (goto-char (match-end 0))
7287         (goto-char (1- p))
7288         (setq not-found nil
7289               found-bad found)))
7290     (not not-found)))
7291
7292 \f
7293 ;;; Getting help
7294 (defvar cperl-have-help-regexp
7295   ;;(concat "\\("
7296   (mapconcat
7297    'identity
7298    '("[$@%*&][0-9a-zA-Z_:]+\\([ \t]*[[{]\\)?" ; Usual variable
7299      "[$@]\\^[a-zA-Z]"                  ; Special variable
7300      "[$@][^ \n\t]"                     ; Special variable
7301      "-[a-zA-Z]"                        ; File test
7302      "\\\\[a-zA-Z0]"                    ; Special chars
7303      "^=[a-z][a-zA-Z0-9_]*"             ; POD sections
7304      "[-!&*+,-./<=>?\\\\^|~]+"          ; Operator
7305      "[a-zA-Z_0-9:]+"                   ; symbol or number
7306      "x="
7307      "#!")
7308    ;;"\\)\\|\\("
7309    "\\|")
7310   ;;"\\)"
7311   ;;)
7312   "Matches places in the buffer we can find help for.")
7313
7314 (defvar cperl-message-on-help-error t)
7315 (defvar cperl-help-from-timer nil)
7316
7317 (defun cperl-word-at-point-hard ()
7318   ;; Does not save-excursion
7319   ;; Get to the something meaningful
7320   (or (eobp) (eolp) (forward-char 1))
7321   (re-search-backward "[-a-zA-Z0-9_:!&*+,-./<=>?\\\\^|~$%@]"
7322                       (save-excursion (beginning-of-line) (point))
7323                       'to-beg)
7324   ;;  (cond
7325   ;;   ((or (eobp) (looking-at "[][ \t\n{}();,]")) ; Not at a symbol
7326   ;;    (skip-chars-backward " \n\t\r({[]});,")
7327   ;;    (or (bobp) (backward-char 1))))
7328   ;; Try to backtrace
7329   (cond
7330    ((looking-at "[a-zA-Z0-9_:]")        ; symbol
7331     (skip-chars-backward "a-zA-Z0-9_:")
7332     (cond
7333      ((and (eq (preceding-char) ?^)     ; $^I
7334            (eq (char-after (- (point) 2)) ?\$))
7335       (forward-char -2))
7336      ((memq (preceding-char) (append "*$@%&\\" nil)) ; *glob
7337       (forward-char -1))
7338      ((and (eq (preceding-char) ?\=)
7339            (eq (current-column) 1))
7340       (forward-char -1)))               ; =head1
7341     (if (and (eq (preceding-char) ?\<)
7342              (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <FH>
7343         (forward-char -1)))
7344    ((and (looking-at "=") (eq (preceding-char) ?x)) ; x=
7345     (forward-char -1))
7346    ((and (looking-at "\\^") (eq (preceding-char) ?\$)) ; $^I
7347     (forward-char -1))
7348    ((looking-at "[-!&*+,-./<=>?\\\\^|~]")
7349     (skip-chars-backward "-!&*+,-./<=>?\\\\^|~")
7350     (cond
7351      ((and (eq (preceding-char) ?\$)
7352            (not (eq (char-after (- (point) 2)) ?\$))) ; $-
7353       (forward-char -1))
7354      ((and (eq (following-char) ?\>)
7355            (string-match "[a-zA-Z0-9_]" (char-to-string (preceding-char)))
7356            (save-excursion
7357              (forward-sexp -1)
7358              (and (eq (preceding-char) ?\<)
7359                   (looking-at "\\$?[a-zA-Z0-9_:]+>")))) ; <FH>
7360       (search-backward "<"))))
7361    ((and (eq (following-char) ?\$)
7362          (eq (preceding-char) ?\<)
7363          (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <$fh>
7364     (forward-char -1)))
7365   (if (looking-at cperl-have-help-regexp)
7366       (buffer-substring (match-beginning 0) (match-end 0))))
7367
7368 (defun cperl-get-help ()
7369   "Get one-line docs on the symbol at the point.
7370 The data for these docs is a little bit obsolete and may be in fact longer
7371 than a line.  Your contribution to update/shorten it is appreciated."
7372   (interactive)
7373   (save-match-data                      ; May be called "inside" query-replace
7374     (save-excursion
7375       (let ((word (cperl-word-at-point-hard)))
7376         (if word
7377             (if (and cperl-help-from-timer ; Bail out if not in mainland
7378                      (not (string-match "^#!\\|\\\\\\|^=" word)) ; Show help even in comments/strings.
7379                      (or (memq (get-text-property (point) 'face)
7380                                '(font-lock-comment-face font-lock-string-face))
7381                          (memq (get-text-property (point) 'syntax-type)
7382                                '(pod here-doc format))))
7383                 nil
7384               (cperl-describe-perl-symbol word))
7385           (if cperl-message-on-help-error
7386               (message "Nothing found for %s..."
7387                        (buffer-substring (point) (min (+ 5 (point)) (point-max))))))))))
7388
7389 ;;; Stolen from perl-descr.el by Johan Vromans:
7390
7391 (defvar cperl-doc-buffer " *perl-doc*"
7392   "Where the documentation can be found.")
7393
7394 (defun cperl-describe-perl-symbol (val)
7395   "Display the documentation of symbol at point, a Perl operator."
7396   (let ((enable-recursive-minibuffers t)
7397         args-file regexp)
7398     (cond
7399      ((string-match "^[&*][a-zA-Z_]" val)
7400       (setq val (concat (substring val 0 1) "NAME")))
7401      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*\\[" val)
7402       (setq val (concat "@" (substring val 1 (match-end 1)))))
7403      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*{" val)
7404       (setq val (concat "%" (substring val 1 (match-end 1)))))
7405      ((and (string= val "x") (string-match "^x=" val))
7406       (setq val "x="))
7407      ((string-match "^\\$[\C-a-\C-z]" val)
7408       (setq val (concat "$^" (char-to-string (+ ?A -1 (aref val 1))))))
7409      ((string-match "^CORE::" val)
7410       (setq val "CORE::"))
7411      ((string-match "^SUPER::" val)
7412       (setq val "SUPER::"))
7413      ((and (string= "<" val) (string-match "^<\\$?[a-zA-Z0-9_:]+>" val))
7414       (setq val "<NAME>")))
7415     (setq regexp (concat "^"
7416                          "\\([^a-zA-Z0-9_:]+[ \t]+\\)?"
7417                          (regexp-quote val)
7418                          "\\([ \t([/]\\|$\\)"))
7419
7420     ;; get the buffer with the documentation text
7421     (cperl-switch-to-doc-buffer)
7422
7423     ;; lookup in the doc
7424     (goto-char (point-min))
7425     (let ((case-fold-search nil))
7426       (list
7427        (if (re-search-forward regexp (point-max) t)
7428            (save-excursion
7429              (beginning-of-line 1)
7430              (let ((lnstart (point)))
7431                (end-of-line)
7432                (message "%s" (buffer-substring lnstart (point)))))
7433          (if cperl-message-on-help-error
7434              (message "No definition for %s" val)))))))
7435
7436 (defvar cperl-short-docs 'please-ignore-this-line
7437   ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl)
7438   "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5]
7439 ...     Range (list context); flip/flop [no flop when flip] (scalar context).
7440 ! ...   Logical negation.
7441 ... != ...      Numeric inequality.
7442 ... !~ ...      Search pattern, substitution, or translation (negated).
7443 $!      In numeric context: errno.  In a string context: error string.
7444 $\"     The separator which joins elements of arrays interpolated in strings.
7445 $#      The output format for printed numbers.  Default is %.15g or close.
7446 $$      Process number of this script.  Changes in the fork()ed child process.
7447 $%      The current page number of the currently selected output channel.
7448
7449         The following variables are always local to the current block:
7450
7451 $1      Match of the 1st set of parentheses in the last match (auto-local).
7452 $2      Match of the 2nd set of parentheses in the last match (auto-local).
7453 $3      Match of the 3rd set of parentheses in the last match (auto-local).
7454 $4      Match of the 4th set of parentheses in the last match (auto-local).
7455 $5      Match of the 5th set of parentheses in the last match (auto-local).
7456 $6      Match of the 6th set of parentheses in the last match (auto-local).
7457 $7      Match of the 7th set of parentheses in the last match (auto-local).
7458 $8      Match of the 8th set of parentheses in the last match (auto-local).
7459 $9      Match of the 9th set of parentheses in the last match (auto-local).
7460 $&      The string matched by the last pattern match (auto-local).
7461 $'      The string after what was matched by the last match (auto-local).
7462 $`      The string before what was matched by the last match (auto-local).
7463
7464 $(      The real gid of this process.
7465 $)      The effective gid of this process.
7466 $*      Deprecated: Set to 1 to do multiline matching within a string.
7467 $+      The last bracket matched by the last search pattern.
7468 $,      The output field separator for the print operator.
7469 $-      The number of lines left on the page.
7470 $.      The current input line number of the last filehandle that was read.
7471 $/      The input record separator, newline by default.
7472 $0      Name of the file containing the current perl script (read/write).
7473 $:     String may be broken after these characters to fill ^-lines in a format.
7474 $;      Subscript separator for multi-dim array emulation.  Default \"\\034\".
7475 $<      The real uid of this process.
7476 $=      The page length of the current output channel.  Default is 60 lines.
7477 $>      The effective uid of this process.
7478 $?      The status returned by the last ``, pipe close or `system'.
7479 $@      The perl error message from the last eval or do @var{EXPR} command.
7480 $ARGV   The name of the current file used with <> .
7481 $[      Deprecated: The index of the first element/char in an array/string.
7482 $\\     The output record separator for the print operator.
7483 $]      The perl version string as displayed with perl -v.
7484 $^      The name of the current top-of-page format.
7485 $^A     The current value of the write() accumulator for format() lines.
7486 $^D     The value of the perl debug (-D) flags.
7487 $^E     Information about the last system error other than that provided by $!.
7488 $^F     The highest system file descriptor, ordinarily 2.
7489 $^H     The current set of syntax checks enabled by `use strict'.
7490 $^I     The value of the in-place edit extension (perl -i option).
7491 $^L     What formats output to perform a formfeed.  Default is \f.
7492 $^M     A buffer for emergency memory allocation when running out of memory.
7493 $^O     The operating system name under which this copy of Perl was built.
7494 $^P     Internal debugging flag.
7495 $^T     The time the script was started.  Used by -A/-M/-C file tests.
7496 $^W     True if warnings are requested (perl -w flag).
7497 $^X     The name under which perl was invoked (argv[0] in C-speech).
7498 $_      The default input and pattern-searching space.
7499 $|      Auto-flush after write/print on current output channel?  Default 0.
7500 $~      The name of the current report format.
7501 ... % ...       Modulo division.
7502 ... %= ...      Modulo division assignment.
7503 %ENV    Contains the current environment.
7504 %INC    List of files that have been require-d or do-ne.
7505 %SIG    Used to set signal handlers for various signals.
7506 ... & ...       Bitwise and.
7507 ... && ...      Logical and.
7508 ... &&= ...     Logical and assignment.
7509 ... &= ...      Bitwise and assignment.
7510 ... * ...       Multiplication.
7511 ... ** ...      Exponentiation.
7512 *NAME   Glob: all objects refered by NAME.  *NAM1 = *NAM2 aliases NAM1 to NAM2.
7513 &NAME(arg0, ...)        Subroutine call.  Arguments go to @_.
7514 ... + ...       Addition.               +EXPR   Makes EXPR into scalar context.
7515 ++      Auto-increment (magical on strings).    ++EXPR  EXPR++
7516 ... += ...      Addition assignment.
7517 ,       Comma operator.
7518 ... - ...       Subtraction.
7519 --      Auto-decrement (NOT magical on strings).        --EXPR  EXPR--
7520 ... -= ...      Subtraction assignment.
7521 -A      Access time in days since script started.
7522 -B      File is a non-text (binary) file.
7523 -C      Inode change time in days since script started.
7524 -M      Age in days since script started.
7525 -O      File is owned by real uid.
7526 -R      File is readable by real uid.
7527 -S      File is a socket .
7528 -T      File is a text file.
7529 -W      File is writable by real uid.
7530 -X      File is executable by real uid.
7531 -b      File is a block special file.
7532 -c      File is a character special file.
7533 -d      File is a directory.
7534 -e      File exists .
7535 -f      File is a plain file.
7536 -g      File has setgid bit set.
7537 -k      File has sticky bit set.
7538 -l      File is a symbolic link.
7539 -o      File is owned by effective uid.
7540 -p      File is a named pipe (FIFO).
7541 -r      File is readable by effective uid.
7542 -s      File has non-zero size.
7543 -t      Tests if filehandle (STDIN by default) is opened to a tty.
7544 -u      File has setuid bit set.
7545 -w      File is writable by effective uid.
7546 -x      File is executable by effective uid.
7547 -z      File has zero size.
7548 .       Concatenate strings.
7549 ..      Range (list context); flip/flop (scalar context) operator.
7550 .=      Concatenate assignment strings
7551 ... / ...       Division.       /PATTERN/ioxsmg Pattern match
7552 ... /= ...      Division assignment.
7553 /PATTERN/ioxsmg Pattern match.
7554 ... < ...    Numeric less than. <pattern>       Glob.   See <NAME>, <> as well.
7555 <NAME>  Reads line from filehandle NAME (a bareword or dollar-bareword).
7556 <pattern>       Glob (Unless pattern is bareword/dollar-bareword - see <NAME>).
7557 <>      Reads line from union of files in @ARGV (= command line) and STDIN.
7558 ... << ...      Bitwise shift left.     <<      start of HERE-DOCUMENT.
7559 ... <= ...      Numeric less than or equal to.
7560 ... <=> ...     Numeric compare.
7561 ... = ...       Assignment.
7562 ... == ...      Numeric equality.
7563 ... =~ ...      Search pattern, substitution, or translation
7564 ... > ...       Numeric greater than.
7565 ... >= ...      Numeric greater than or equal to.
7566 ... >> ...      Bitwise shift right.
7567 ... >>= ...     Bitwise shift right assignment.
7568 ... ? ... : ... Condition=if-then-else operator.   ?PAT? One-time pattern match.
7569 ?PATTERN?       One-time pattern match.
7570 @ARGV   Command line arguments (not including the command name - see $0).
7571 @INC    List of places to look for perl scripts during do/include/use.
7572 @_    Parameter array for subroutines; result of split() unless in list context.
7573 \\  Creates reference to what follows, like \$var, or quotes non-\w in strings.
7574 \\0     Octal char, e.g. \\033.
7575 \\E     Case modification terminator.  See \\Q, \\L, and \\U.
7576 \\L     Lowercase until \\E .  See also \l, lc.
7577 \\U     Upcase until \\E .  See also \u, uc.
7578 \\Q     Quote metacharacters until \\E .  See also quotemeta.
7579 \\a     Alarm character (octal 007).
7580 \\b     Backspace character (octal 010).
7581 \\c     Control character, e.g. \\c[ .
7582 \\e     Escape character (octal 033).
7583 \\f     Formfeed character (octal 014).
7584 \\l     Lowercase the next character.  See also \\L and \\u, lcfirst.
7585 \\n     Newline character (octal 012 on most systems).
7586 \\r     Return character (octal 015 on most systems).
7587 \\t     Tab character (octal 011).
7588 \\u     Upcase the next character.  See also \\U and \\l, ucfirst.
7589 \\x     Hex character, e.g. \\x1b.
7590 ... ^ ...       Bitwise exclusive or.
7591 __END__ Ends program source.
7592 __DATA__        Ends program source.
7593 __FILE__        Current (source) filename.
7594 __LINE__        Current line in current source.
7595 __PACKAGE__     Current package.
7596 ARGV    Default multi-file input filehandle.  <ARGV> is a synonym for <>.
7597 ARGVOUT Output filehandle with -i flag.
7598 BEGIN { ... }   Immediately executed (during compilation) piece of code.
7599 END { ... }     Pseudo-subroutine executed after the script finishes.
7600 CHECK { ... }   Pseudo-subroutine executed after the script is compiled.
7601 INIT { ... }    Pseudo-subroutine executed before the script starts running.
7602 DATA    Input filehandle for what follows after __END__ or __DATA__.
7603 accept(NEWSOCKET,GENERICSOCKET)
7604 alarm(SECONDS)
7605 atan2(X,Y)
7606 bind(SOCKET,NAME)
7607 binmode(FILEHANDLE)
7608 caller[(LEVEL)]
7609 chdir(EXPR)
7610 chmod(LIST)
7611 chop[(LIST|VAR)]
7612 chown(LIST)
7613 chroot(FILENAME)
7614 close(FILEHANDLE)
7615 closedir(DIRHANDLE)
7616 ... cmp ...     String compare.
7617 connect(SOCKET,NAME)
7618 continue of { block } continue { block }.  Is executed after `next' or at end.
7619 cos(EXPR)
7620 crypt(PLAINTEXT,SALT)
7621 dbmclose(%HASH)
7622 dbmopen(%HASH,DBNAME,MODE)
7623 defined(EXPR)
7624 delete($HASH{KEY})
7625 die(LIST)
7626 do { ... }|SUBR while|until EXPR        executes at least once
7627 do(EXPR|SUBR([LIST]))   (with while|until executes at least once)
7628 dump LABEL
7629 each(%HASH)
7630 endgrent
7631 endhostent
7632 endnetent
7633 endprotoent
7634 endpwent
7635 endservent
7636 eof[([FILEHANDLE])]
7637 ... eq ...      String equality.
7638 eval(EXPR) or eval { BLOCK }
7639 exec(LIST)
7640 exit(EXPR)
7641 exp(EXPR)
7642 fcntl(FILEHANDLE,FUNCTION,SCALAR)
7643 fileno(FILEHANDLE)
7644 flock(FILEHANDLE,OPERATION)
7645 for (EXPR;EXPR;EXPR) { ... }
7646 foreach [VAR] (@ARRAY) { ... }
7647 fork
7648 ... ge ...      String greater than or equal.
7649 getc[(FILEHANDLE)]
7650 getgrent
7651 getgrgid(GID)
7652 getgrnam(NAME)
7653 gethostbyaddr(ADDR,ADDRTYPE)
7654 gethostbyname(NAME)
7655 gethostent
7656 getlogin
7657 getnetbyaddr(ADDR,ADDRTYPE)
7658 getnetbyname(NAME)
7659 getnetent
7660 getpeername(SOCKET)
7661 getpgrp(PID)
7662 getppid
7663 getpriority(WHICH,WHO)
7664 getprotobyname(NAME)
7665 getprotobynumber(NUMBER)
7666 getprotoent
7667 getpwent
7668 getpwnam(NAME)
7669 getpwuid(UID)
7670 getservbyname(NAME,PROTO)
7671 getservbyport(PORT,PROTO)
7672 getservent
7673 getsockname(SOCKET)
7674 getsockopt(SOCKET,LEVEL,OPTNAME)
7675 gmtime(EXPR)
7676 goto LABEL
7677 ... gt ...      String greater than.
7678 hex(EXPR)
7679 if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXPR if EXPR
7680 index(STR,SUBSTR[,OFFSET])
7681 int(EXPR)
7682 ioctl(FILEHANDLE,FUNCTION,SCALAR)
7683 join(EXPR,LIST)
7684 keys(%HASH)
7685 kill(LIST)
7686 last [LABEL]
7687 ... le ...      String less than or equal.
7688 length(EXPR)
7689 link(OLDFILE,NEWFILE)
7690 listen(SOCKET,QUEUESIZE)
7691 local(LIST)
7692 localtime(EXPR)
7693 log(EXPR)
7694 lstat(EXPR|FILEHANDLE|VAR)
7695 ... lt ...      String less than.
7696 m/PATTERN/iogsmx
7697 mkdir(FILENAME,MODE)
7698 msgctl(ID,CMD,ARG)
7699 msgget(KEY,FLAGS)
7700 msgrcv(ID,VAR,SIZE,TYPE.FLAGS)
7701 msgsnd(ID,MSG,FLAGS)
7702 my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, or %HASH).
7703 our VAR or our (VAR1,...) Lexically enable a global variable ($V, @A, or %H).
7704 ... ne ...      String inequality.
7705 next [LABEL]
7706 oct(EXPR)
7707 open(FILEHANDLE[,EXPR])
7708 opendir(DIRHANDLE,EXPR)
7709 ord(EXPR)       ASCII value of the first char of the string.
7710 pack(TEMPLATE,LIST)
7711 package NAME    Introduces package context.
7712 pipe(READHANDLE,WRITEHANDLE)    Create a pair of filehandles on ends of a pipe.
7713 pop(ARRAY)
7714 print [FILEHANDLE] [(LIST)]
7715 printf [FILEHANDLE] (FORMAT,LIST)
7716 push(ARRAY,LIST)
7717 q/STRING/       Synonym for 'STRING'
7718 qq/STRING/      Synonym for \"STRING\"
7719 qx/STRING/      Synonym for `STRING`
7720 rand[(EXPR)]
7721 read(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
7722 readdir(DIRHANDLE)
7723 readlink(EXPR)
7724 recv(SOCKET,SCALAR,LEN,FLAGS)
7725 redo [LABEL]
7726 rename(OLDNAME,NEWNAME)
7727 require [FILENAME | PERL_VERSION]
7728 reset[(EXPR)]
7729 return(LIST)
7730 reverse(LIST)
7731 rewinddir(DIRHANDLE)
7732 rindex(STR,SUBSTR[,OFFSET])
7733 rmdir(FILENAME)
7734 s/PATTERN/REPLACEMENT/gieoxsm
7735 scalar(EXPR)
7736 seek(FILEHANDLE,POSITION,WHENCE)
7737 seekdir(DIRHANDLE,POS)
7738 select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT)
7739 semctl(ID,SEMNUM,CMD,ARG)
7740 semget(KEY,NSEMS,SIZE,FLAGS)
7741 semop(KEY,...)
7742 send(SOCKET,MSG,FLAGS[,TO])
7743 setgrent
7744 sethostent(STAYOPEN)
7745 setnetent(STAYOPEN)
7746 setpgrp(PID,PGRP)
7747 setpriority(WHICH,WHO,PRIORITY)
7748 setprotoent(STAYOPEN)
7749 setpwent
7750 setservent(STAYOPEN)
7751 setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
7752 shift[(ARRAY)]
7753 shmctl(ID,CMD,ARG)
7754 shmget(KEY,SIZE,FLAGS)
7755 shmread(ID,VAR,POS,SIZE)
7756 shmwrite(ID,STRING,POS,SIZE)
7757 shutdown(SOCKET,HOW)
7758 sin(EXPR)
7759 sleep[(EXPR)]
7760 socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
7761 socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
7762 sort [SUBROUTINE] (LIST)
7763 splice(ARRAY,OFFSET[,LENGTH[,LIST]])
7764 split[(/PATTERN/[,EXPR[,LIMIT]])]
7765 sprintf(FORMAT,LIST)
7766 sqrt(EXPR)
7767 srand(EXPR)
7768 stat(EXPR|FILEHANDLE|VAR)
7769 study[(SCALAR)]
7770 sub [NAME [(format)]] { BODY }  sub NAME [(format)];    sub [(format)] {...}
7771 substr(EXPR,OFFSET[,LEN])
7772 symlink(OLDFILE,NEWFILE)
7773 syscall(LIST)
7774 sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
7775 system(LIST)
7776 syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
7777 tell[(FILEHANDLE)]
7778 telldir(DIRHANDLE)
7779 time
7780 times
7781 tr/SEARCHLIST/REPLACEMENTLIST/cds
7782 truncate(FILE|EXPR,LENGTH)
7783 umask[(EXPR)]
7784 undef[(EXPR)]
7785 unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR
7786 unlink(LIST)
7787 unpack(TEMPLATE,EXPR)
7788 unshift(ARRAY,LIST)
7789 until (EXPR) { ... }                                    EXPR until EXPR
7790 utime(LIST)
7791 values(%HASH)
7792 vec(EXPR,OFFSET,BITS)
7793 wait
7794 waitpid(PID,FLAGS)
7795 wantarray       Returns true if the sub/eval is called in list context.
7796 warn(LIST)
7797 while  (EXPR) { ... }                                   EXPR while EXPR
7798 write[(EXPR|FILEHANDLE)]
7799 ... x ...       Repeat string or array.
7800 x= ...  Repetition assignment.
7801 y/SEARCHLIST/REPLACEMENTLIST/
7802 ... | ...       Bitwise or.
7803 ... || ...      Logical or.
7804 ~ ...           Unary bitwise complement.
7805 #!      OS interpreter indicator.  If contains `perl', used for options, and -x.
7806 AUTOLOAD {...}  Shorthand for `sub AUTOLOAD {...}'.
7807 CORE::          Prefix to access builtin function if imported sub obscures it.
7808 SUPER::         Prefix to lookup for a method in @ISA classes.
7809 DESTROY         Shorthand for `sub DESTROY {...}'.
7810 ... EQ ...      Obsolete synonym of `eq'.
7811 ... GE ...      Obsolete synonym of `ge'.
7812 ... GT ...      Obsolete synonym of `gt'.
7813 ... LE ...      Obsolete synonym of `le'.
7814 ... LT ...      Obsolete synonym of `lt'.
7815 ... NE ...      Obsolete synonym of `ne'.
7816 abs [ EXPR ]    absolute value
7817 ... and ...             Low-precedence synonym for &&.
7818 bless REFERENCE [, PACKAGE]     Makes reference into an object of a package.
7819 chomp [LIST]    Strips $/ off LIST/$_.  Returns count.  Special if $/ eq ''!
7820 chr             Converts a number to char with the same ordinal.
7821 else            Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
7822 elsif           Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
7823 exists $HASH{KEY}       True if the key exists.
7824 format [NAME] =  Start of output format.  Ended by a single dot (.) on a line.
7825 formline PICTURE, LIST  Backdoor into \"format\" processing.
7826 glob EXPR       Synonym of <EXPR>.
7827 lc [ EXPR ]     Returns lowercased EXPR.
7828 lcfirst [ EXPR ]        Returns EXPR with lower-cased first letter.
7829 grep EXPR,LIST  or grep {BLOCK} LIST    Filters LIST via EXPR/BLOCK.
7830 map EXPR, LIST  or map {BLOCK} LIST     Applies EXPR/BLOCK to elts of LIST.
7831 no PACKAGE [SYMBOL1, ...]  Partial reverse for `use'.  Runs `unimport' method.
7832 not ...         Low-precedence synonym for ! - negation.
7833 ... or ...              Low-precedence synonym for ||.
7834 pos STRING    Set/Get end-position of the last match over this string, see \\G.
7835 quotemeta [ EXPR ]      Quote regexp metacharacters.
7836 qw/WORD1 .../           Synonym of split('', 'WORD1 ...')
7837 readline FH     Synonym of <FH>.
7838 readpipe CMD    Synonym of `CMD`.
7839 ref [ EXPR ]    Type of EXPR when dereferenced.
7840 sysopen FH, FILENAME, MODE [, PERM]     (MODE is numeric, see Fcntl.)
7841 tie VAR, PACKAGE, LIST  Hide an object behind a simple Perl variable.
7842 tied            Returns internal object for a tied data.
7843 uc [ EXPR ]     Returns upcased EXPR.
7844 ucfirst [ EXPR ]        Returns EXPR with upcased first letter.
7845 untie VAR       Unlink an object from a simple Perl variable.
7846 use PACKAGE [SYMBOL1, ...]  Compile-time `require' with consequent `import'.
7847 ... xor ...             Low-precedence synonym for exclusive or.
7848 prototype \&SUB Returns prototype of the function given a reference.
7849 =head1          Top-level heading.
7850 =head2          Second-level heading.
7851 =head3          Third-level heading (is there such?).
7852 =over [ NUMBER ]        Start list.
7853 =item [ TITLE ]         Start new item in the list.
7854 =back           End list.
7855 =cut            Switch from POD to Perl.
7856 =pod            Switch from Perl to POD.
7857 ")
7858
7859 (defun cperl-switch-to-doc-buffer ()
7860   "Go to the perl documentation buffer and insert the documentation."
7861   (interactive)
7862   (let ((buf (get-buffer-create cperl-doc-buffer)))
7863     (if (interactive-p)
7864         (switch-to-buffer-other-window buf)
7865       (set-buffer buf))
7866     (if (= (buffer-size) 0)
7867         (progn
7868           (insert (documentation-property 'cperl-short-docs
7869                                           'variable-documentation))
7870           (setq buffer-read-only t)))))
7871
7872 (defun cperl-beautify-regexp-piece (b e embed level)
7873   ;; b is before the starting delimiter, e before the ending
7874   ;; e should be a marker, may be changed, but remains "correct".
7875   ;; EMBED is nil iff we process the whole REx.
7876   ;; The REx is guarantied to have //x
7877   ;; LEVEL shows how many levels deep to go
7878   ;; position at enter and at leave is not defined
7879   (let (s c tmp (m (make-marker)) (m1 (make-marker)) c1 spaces inline code pos)
7880     (if (not embed)
7881         (goto-char (1+ b))
7882       (goto-char b)
7883       (cond ((looking-at "(\\?\\\\#")   ;  (?#) wrongly commented when //x-ing
7884              (forward-char 2)
7885              (delete-char 1)
7886              (forward-char 1))
7887             ((looking-at "(\\?[^a-zA-Z]")
7888              (forward-char 3))
7889             ((looking-at "(\\?")        ; (?i)
7890              (forward-char 2))
7891             (t
7892              (forward-char 1))))
7893     (setq c (if embed (current-indentation) (1- (current-column)))
7894           c1 (+ c (or cperl-regexp-indent-step cperl-indent-level)))
7895     (or (looking-at "[ \t]*[\n#]")
7896         (progn
7897           (insert "\n")))
7898     (goto-char e)
7899     (beginning-of-line)
7900     (if (re-search-forward "[^ \t]" e t)
7901         (progn                         ; Something before the ending delimiter
7902           (goto-char e)
7903           (delete-horizontal-space)
7904           (insert "\n")
7905           (indent-to-column c)
7906           (set-marker e (point))))
7907     (goto-char b)
7908     (end-of-line 2)
7909     (while (< (point) (marker-position e))
7910       (beginning-of-line)
7911       (setq s (point)
7912             inline t)
7913       (skip-chars-forward " \t")
7914       (delete-region s (point))
7915       (indent-to-column c1)
7916       (while (and
7917               inline
7918               (looking-at
7919                (concat "\\([a-zA-Z0-9]+[^*+{?]\\)" ; 1 word
7920                        "\\|"            ; Embedded variable
7921                        "\\$\\([a-zA-Z0-9_]+\\([[{]\\)?\\|[^\n \t)|]\\)" ; 2 3
7922                        "\\|"            ; $ ^
7923                        "[$^]"
7924                        "\\|"            ; simple-code simple-code*?
7925                        "\\(\\\\.\\|[^][()#|*+?\n]\\)\\([*+{?]\\??\\)?" ; 4 5
7926                        "\\|"            ; Class
7927                        "\\(\\[\\)"      ; 6
7928                        "\\|"            ; Grouping
7929                        "\\((\\(\\?\\)?\\)" ; 7 8
7930                        "\\|"            ; |
7931                        "\\(|\\)")))     ; 9
7932         (goto-char (match-end 0))
7933         (setq spaces t)
7934         (cond ((match-beginning 1)      ; Alphanum word + junk
7935                (forward-char -1))
7936               ((or (match-beginning 3)  ; $ab[12]
7937                    (and (match-beginning 5) ; X* X+ X{2,3}
7938                         (eq (preceding-char) ?\{)))
7939                (forward-char -1)
7940                (forward-sexp 1))
7941               ((match-beginning 6)      ; []
7942                (setq tmp (point))
7943                (if (looking-at "\\^?\\]")
7944                    (goto-char (match-end 0)))
7945                ;; XXXX POSIX classes?!
7946                (while (and (not pos)
7947                            (re-search-forward "\\[:\\|\\]" e t))
7948                  (if (eq (preceding-char) ?:)
7949                      (or (re-search-forward ":\\]" e t)
7950                          (error "[:POSIX:]-group in []-group not terminated"))
7951                    (setq pos t)))
7952                (or (eq (preceding-char) ?\])
7953                    (error "[]-group not terminated"))
7954                (if (eq (following-char) ?\{)
7955                    (progn
7956                      (forward-sexp 1)
7957                      (and (eq (following-char) ??)
7958                           (forward-char 1)))
7959                  (re-search-forward "\\=\\([*+?]\\??\\)" e t)))
7960               ((match-beginning 7)      ; ()
7961                (goto-char (match-beginning 0))
7962                (setq pos (current-column))
7963                (or (eq pos c1)
7964                    (progn
7965                      (delete-horizontal-space)
7966                      (insert "\n")
7967                      (indent-to-column c1)))
7968                (setq tmp (point))
7969                (forward-sexp 1)
7970                ;;              (or (forward-sexp 1)
7971                ;;                  (progn
7972                ;;                    (goto-char tmp)
7973                ;;                    (error "()-group not terminated")))
7974                (set-marker m (1- (point)))
7975                (set-marker m1 (point))
7976                (if (= level 1)
7977                    (if (progn           ; indent rigidly if multiline
7978                          ;; In fact does not make a lot of sense, since
7979                          ;; the starting position can be already lost due
7980                          ;; to insertion of "\n" and " "
7981                          (goto-char tmp)
7982                          (search-forward "\n" m1 t))
7983                        (indent-rigidly (point) m1 (- c1 pos)))
7984                  (setq level (1- level))
7985                  (cond
7986                   ((not (match-beginning 8))
7987                    (cperl-beautify-regexp-piece tmp m t level))
7988                   ((eq (char-after (+ 2 tmp)) ?\{) ; Code
7989                    t)
7990                   ((eq (char-after (+ 2 tmp)) ?\() ; Conditional
7991                    (goto-char (+ 2 tmp))
7992                    (forward-sexp 1)
7993                    (cperl-beautify-regexp-piece (point) m t level))
7994                   ((eq (char-after (+ 2 tmp)) ?<) ; Lookbehind
7995                    (goto-char (+ 3 tmp))
7996                    (cperl-beautify-regexp-piece (point) m t level))
7997                   (t
7998                    (cperl-beautify-regexp-piece tmp m t level))))
7999                (goto-char m1)
8000                (cond ((looking-at "[*+?]\\??")
8001                       (goto-char (match-end 0)))
8002                      ((eq (following-char) ?\{)
8003                       (forward-sexp 1)
8004                       (if (eq (following-char) ?\?)
8005                           (forward-char))))
8006                (skip-chars-forward " \t")
8007                (setq spaces nil)
8008                (if (looking-at "[#\n]")
8009                    (progn
8010                      (or (eolp) (indent-for-comment))
8011                      (beginning-of-line 2))
8012                  (delete-horizontal-space)
8013                  (insert "\n"))
8014                (end-of-line)
8015                (setq inline nil))
8016               ((match-beginning 9)      ; |
8017                (forward-char -1)
8018                (setq tmp (point))
8019                (beginning-of-line)
8020                (if (re-search-forward "[^ \t]" tmp t)
8021                    (progn
8022                      (goto-char tmp)
8023                      (delete-horizontal-space)
8024                      (insert "\n"))
8025                  ;; first at line
8026                  (delete-region (point) tmp))
8027                (indent-to-column c)
8028                (forward-char 1)
8029                (skip-chars-forward " \t")
8030                (setq spaces nil)
8031                (if (looking-at "[#\n]")
8032                    (beginning-of-line 2)
8033                  (delete-horizontal-space)
8034                  (insert "\n"))
8035                (end-of-line)
8036                (setq inline nil)))
8037         (or (looking-at "[ \t\n]")
8038             (not spaces)
8039             (insert " "))
8040         (skip-chars-forward " \t"))
8041       (or (looking-at "[#\n]")
8042           (error "Unknown code `%s' in a regexp"
8043                  (buffer-substring (point) (1+ (point)))))
8044       (and inline (end-of-line 2)))
8045     ;; Special-case the last line of group
8046     (if (and (>= (point) (marker-position e))
8047              (/= (current-indentation) c))
8048         (progn
8049           (beginning-of-line)
8050           (setq s (point))
8051           (skip-chars-forward " \t")
8052           (delete-region s (point))
8053           (indent-to-column c)))))
8054
8055 (defun cperl-make-regexp-x ()
8056   ;; Returns position of the start
8057   ;; XXX this is called too often!  Need to cache the result!
8058   (save-excursion
8059     (or cperl-use-syntax-table-text-property
8060         (error "I need to have a regexp marked!"))
8061     ;; Find the start
8062     (if (looking-at "\\s|")
8063         nil                             ; good already
8064       (if (looking-at "\\([smy]\\|qr\\)\\s|")
8065           (forward-char 1)
8066         (re-search-backward "\\s|")))   ; Assume it is scanned already.
8067     ;;(forward-char 1)
8068     (let ((b (point)) (e (make-marker)) have-x delim (c (current-column))
8069           (sub-p (eq (preceding-char) ?s)) s)
8070       (forward-sexp 1)
8071       (set-marker e (1- (point)))
8072       (setq delim (preceding-char))
8073       (if (and sub-p (eq delim (char-after (- (point) 2))))
8074           (error "Possible s/blah// - do not know how to deal with"))
8075       (if sub-p (forward-sexp 1))
8076       (if (looking-at "\\sw*x")
8077           (setq have-x t)
8078         (insert "x"))
8079       ;; Protect fragile " ", "#"
8080       (if have-x nil
8081         (goto-char (1+ b))
8082         (while (re-search-forward "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*[ \t\n#]" e t) ; Need to include (?#) too?
8083           (forward-char -1)
8084           (insert "\\")
8085           (forward-char 1)))
8086       b)))
8087
8088 (defun cperl-beautify-regexp (&optional deep)
8089   "Do it.  (Experimental, may change semantics, recheck the result.)
8090 We suppose that the regexp is scanned already."
8091   (interactive "P")
8092   (setq deep (if deep (prefix-numeric-value deep) -1))
8093   (save-excursion
8094     (goto-char (cperl-make-regexp-x))
8095     (let ((b (point)) (e (make-marker)))
8096       (forward-sexp 1)
8097       (set-marker e (1- (point)))
8098       (cperl-beautify-regexp-piece b e nil deep))))
8099
8100 (defun cperl-regext-to-level-start ()
8101   "Goto start of an enclosing group in regexp.
8102 We suppose that the regexp is scanned already."
8103   (interactive)
8104   (let ((limit (cperl-make-regexp-x)) done)
8105     (while (not done)
8106       (or (eq (following-char) ?\()
8107           (search-backward "(" (1+ limit) t)
8108           (error "Cannot find `(' which starts a group"))
8109       (setq done
8110             (save-excursion
8111               (skip-chars-backward "\\")
8112               (looking-at "\\(\\\\\\\\\\)*(")))
8113       (or done (forward-char -1)))))
8114
8115 (defun cperl-contract-level ()
8116   "Find an enclosing group in regexp and contract it.
8117 \(Experimental, may change semantics, recheck the result.)
8118 We suppose that the regexp is scanned already."
8119   (interactive)
8120   ;; (save-excursion            ; Can't, breaks `cperl-contract-levels'
8121   (cperl-regext-to-level-start)
8122   (let ((b (point)) (e (make-marker)) s c)
8123     (forward-sexp 1)
8124     (set-marker e (1- (point)))
8125     (goto-char b)
8126     (while (re-search-forward "\\(#\\)\\|\n" e 'to-end)
8127       (cond
8128        ((match-beginning 1)             ; #-comment
8129         (or c (setq c (current-indentation)))
8130         (beginning-of-line 2)           ; Skip
8131         (setq s (point))
8132         (skip-chars-forward " \t")
8133         (delete-region s (point))
8134         (indent-to-column c))
8135        (t
8136         (delete-char -1)
8137         (just-one-space))))))
8138
8139 (defun cperl-contract-levels ()
8140   "Find an enclosing group in regexp and contract all the kids.
8141 \(Experimental, may change semantics, recheck the result.)
8142 We suppose that the regexp is scanned already."
8143   (interactive)
8144   (save-excursion
8145     (condition-case nil
8146         (cperl-regext-to-level-start)
8147       (error                            ; We are outside outermost group
8148        (goto-char (cperl-make-regexp-x))))
8149     (let ((b (point)) (e (make-marker)) s c)
8150       (forward-sexp 1)
8151       (set-marker e (1- (point)))
8152       (goto-char (1+ b))
8153       (while (re-search-forward "\\(\\\\\\\\\\)\\|(" e t)
8154         (cond
8155          ((match-beginning 1)           ; Skip
8156           nil)
8157          (t                             ; Group
8158           (cperl-contract-level)))))))
8159
8160 (defun cperl-beautify-level (&optional deep)
8161   "Find an enclosing group in regexp and beautify it.
8162 \(Experimental, may change semantics, recheck the result.)
8163 We suppose that the regexp is scanned already."
8164   (interactive "P")
8165   (setq deep (if deep (prefix-numeric-value deep) -1))
8166   (save-excursion
8167     (cperl-regext-to-level-start)
8168     (let ((b (point)) (e (make-marker)))
8169       (forward-sexp 1)
8170       (set-marker e (1- (point)))
8171       (cperl-beautify-regexp-piece b e nil deep))))
8172
8173 (defun cperl-invert-if-unless ()
8174   "Change `if (A) {B}' into `B if A;' etc if possible."
8175   (interactive)
8176   (or (looking-at "\\<")
8177       (forward-sexp -1))
8178   (if (looking-at "\\<\\(if\\|unless\\|while\\|until\\|for\\|foreach\\)\\>")
8179       (let ((pos1 (point))
8180             pos2 pos3 pos4 pos5 s1 s2 state p pos45
8181             (s0 (buffer-substring (match-beginning 0) (match-end 0))))
8182         (forward-sexp 2)
8183         (setq pos3 (point))
8184         (forward-sexp -1)
8185         (setq pos2 (point))
8186         (if (eq (following-char) ?\( )
8187             (progn
8188               (goto-char pos3)
8189               (forward-sexp 1)
8190               (setq pos5 (point))
8191               (forward-sexp -1)
8192               (setq pos4 (point))
8193               ;; XXXX In fact may be `A if (B); {C}' ...
8194               (if (and (eq (following-char) ?\{ )
8195                        (progn
8196                          (cperl-backward-to-noncomment pos3)
8197                          (eq (preceding-char) ?\) )))
8198                   (if (condition-case nil
8199                           (progn
8200                             (goto-char pos5)
8201                             (forward-sexp 1)
8202                             (forward-sexp -1)
8203                             (looking-at "\\<els\\(e\\|if\\)\\>"))
8204                         (error nil))
8205                       (error
8206                        "`%s' (EXPR) {BLOCK} with `else'/`elsif'" s0)
8207                     (goto-char (1- pos5))
8208                     (cperl-backward-to-noncomment pos4)
8209                     (if (eq (preceding-char) ?\;)
8210                         (forward-char -1))
8211                     (setq pos45 (point))
8212                     (goto-char pos4)
8213                     (while (re-search-forward "\\<\\(for\\|foreach\\|if\\|unless\\|while\\|until\\)\\>\\|;" pos45 t)
8214                       (setq p (match-beginning 0)
8215                             s1 (buffer-substring p (match-end 0))
8216                             state (parse-partial-sexp pos4 p))
8217                       (or (nth 3 state)
8218                           (nth 4 state)
8219                           (nth 5 state)
8220                           (error "`%s' inside `%s' BLOCK" s1 s0))
8221                       (goto-char (match-end 0)))
8222                     ;; Finally got it
8223                     (goto-char (1+ pos4))
8224                     (skip-chars-forward " \t\n")
8225                     (setq s2 (buffer-substring (point) pos45))
8226                     (goto-char pos45)
8227                     (or (looking-at ";?[ \t\n]*}")
8228                         (progn
8229                           (skip-chars-forward "; \t\n")
8230                           (setq s2 (concat s2 "\n" (buffer-substring (point) (1- pos5))))))
8231                     (and (equal s2 "")
8232                          (setq s2 "1"))
8233                     (goto-char (1- pos3))
8234                     (cperl-backward-to-noncomment pos2)
8235                     (or (looking-at "[ \t\n]*)")
8236                         (goto-char (1- pos3)))
8237                     (setq p (point))
8238                     (goto-char (1+ pos2))
8239                     (skip-chars-forward " \t\n")
8240                     (setq s1 (buffer-substring (point) p))
8241                     (delete-region pos4 pos5)
8242                     (delete-region pos2 pos3)
8243                     (goto-char pos1)
8244                     (insert s2 " ")
8245                     (just-one-space)
8246                     (forward-word 1)
8247                     (setq pos1 (point))
8248                     (insert " " s1 ";")
8249                     (delete-horizontal-space)
8250                     (forward-char -1)
8251                     (delete-horizontal-space)
8252                     (goto-char pos1)
8253                     (just-one-space)
8254                     (cperl-indent-line))
8255                 (error "`%s' (EXPR) not with an {BLOCK}" s0)))
8256           (error "`%s' not with an (EXPR)" s0)))
8257     (error "Not at `if', `unless', `while', `until', `for' or `foreach'")))
8258
8259 ;;; By Anthony Foiani <afoiani@uswest.com>
8260 ;;; Getting help on modules in C-h f ?
8261 ;;; This is a modified version of `man'.
8262 ;;; Need to teach it how to lookup functions
8263 (defun cperl-perldoc (word)
8264   "Run `perldoc' on WORD."
8265   (interactive
8266    (list (let* ((default-entry (cperl-word-at-point))
8267                 (input (read-string
8268                         (format "perldoc entry%s: "
8269                                 (if (string= default-entry "")
8270                                     ""
8271                                   (format " (default %s)" default-entry))))))
8272            (if (string= input "")
8273                (if (string= default-entry "")
8274                    (error "No perldoc args given")
8275                  default-entry)
8276              input))))
8277   (require 'man)
8278   (let* ((case-fold-search nil)
8279          (is-func (and
8280                    (string-match "^[a-z]+$" word)
8281                    (string-match (concat "^" word "\\>")
8282                                  (documentation-property
8283                                   'cperl-short-docs
8284                                   'variable-documentation))))
8285          (manual-program (if is-func "perldoc -f" "perldoc")))
8286     (cond
8287      (cperl-xemacs-p
8288       (let ((Manual-program "perldoc")
8289             (Manual-switches (if is-func (list "-f"))))
8290         (manual-entry word)))
8291      (t
8292       (Man-getpage-in-background word)))))
8293
8294 (defun cperl-perldoc-at-point ()
8295   "Run a `perldoc' on the word around point."
8296   (interactive)
8297   (cperl-perldoc (cperl-word-at-point)))
8298
8299 (defcustom pod2man-program "pod2man"
8300   "*File name for `pod2man'."
8301   :type 'file
8302   :group 'cperl)
8303
8304 ;;; By Nick Roberts <Nick.Roberts@src.bae.co.uk> (with changes)
8305 (defun cperl-pod-to-manpage ()
8306   "Create a virtual manpage in Emacs from the Perl Online Documentation."
8307   (interactive)
8308   (require 'man)
8309   (let* ((pod2man-args (concat buffer-file-name " | nroff -man "))
8310          (bufname (concat "Man " buffer-file-name))
8311          (buffer (generate-new-buffer bufname)))
8312     (save-excursion
8313       (set-buffer buffer)
8314       (let ((process-environment (copy-sequence process-environment)))
8315         ;; Prevent any attempt to use display terminal fanciness.
8316         (setenv "TERM" "dumb")
8317         (set-process-sentinel
8318          (start-process pod2man-program buffer "sh" "-c"
8319                         (format (cperl-pod2man-build-command) pod2man-args))
8320          'Man-bgproc-sentinel)))))
8321
8322 ;;; Updated version by him too
8323 (defun cperl-build-manpage ()
8324   "Create a virtual manpage in Emacs from the POD in the file."
8325   (interactive)
8326   (require 'man)
8327   (cond
8328    (cperl-xemacs-p
8329     (let ((Manual-program "perldoc"))
8330       (manual-entry buffer-file-name)))
8331    (t
8332     (let* ((manual-program "perldoc"))
8333       (Man-getpage-in-background buffer-file-name)))))
8334
8335 (defun cperl-pod2man-build-command ()
8336   "Builds the entire background manpage and cleaning command."
8337   (let ((command (concat pod2man-program " %s 2>/dev/null"))
8338         (flist Man-filter-list))
8339     (while (and flist (car flist))
8340       (let ((pcom (car (car flist)))
8341             (pargs (cdr (car flist))))
8342         (setq command
8343               (concat command " | " pcom " "
8344                       (mapconcat '(lambda (phrase)
8345                                     (if (not (stringp phrase))
8346                                         (error "Malformed Man-filter-list"))
8347                                     phrase)
8348                                  pargs " ")))
8349         (setq flist (cdr flist))))
8350     command))
8351
8352 (defun cperl-lazy-install ())           ; Avoid a warning
8353 (defun cperl-lazy-unstall ())           ; Avoid a warning
8354
8355 (if (fboundp 'run-with-idle-timer)
8356     (progn
8357       (defvar cperl-help-shown nil
8358         "Non-nil means that the help was already shown now.")
8359
8360       (defvar cperl-lazy-installed nil
8361         "Non-nil means that the lazy-help handlers are installed now.")
8362
8363       (defun cperl-lazy-install ()
8364         "Switches on Auto-Help on Perl constructs (put in the message area).
8365 Delay of auto-help controlled by `cperl-lazy-help-time'."
8366         (interactive)
8367         (make-variable-buffer-local 'cperl-help-shown)
8368         (if (and (cperl-val 'cperl-lazy-help-time)
8369                  (not cperl-lazy-installed))
8370             (progn
8371               (add-hook 'post-command-hook 'cperl-lazy-hook)
8372               (run-with-idle-timer
8373                (cperl-val 'cperl-lazy-help-time 1000000 5)
8374                t
8375                'cperl-get-help-defer)
8376               (setq cperl-lazy-installed t))))
8377
8378       (defun cperl-lazy-unstall ()
8379         "Switches off Auto-Help on Perl constructs (put in the message area).
8380 Delay of auto-help controlled by `cperl-lazy-help-time'."
8381         (interactive)
8382         (remove-hook 'post-command-hook 'cperl-lazy-hook)
8383         (cancel-function-timers 'cperl-get-help-defer)
8384         (setq cperl-lazy-installed nil))
8385
8386       (defun cperl-lazy-hook ()
8387         (setq cperl-help-shown nil))
8388
8389       (defun cperl-get-help-defer ()
8390         (if (not (memq major-mode '(perl-mode cperl-mode))) nil
8391           (let ((cperl-message-on-help-error nil) (cperl-help-from-timer t))
8392             (cperl-get-help)
8393             (setq cperl-help-shown t))))
8394       (cperl-lazy-install)))
8395
8396
8397 ;;; Plug for wrong font-lock:
8398
8399 (defun cperl-font-lock-unfontify-region-function (beg end)
8400   (let* ((modified (buffer-modified-p)) (buffer-undo-list t)
8401          (inhibit-read-only t) (inhibit-point-motion-hooks t)
8402          before-change-functions after-change-functions
8403          deactivate-mark buffer-file-name buffer-file-truename)
8404     (remove-text-properties beg end '(face nil))
8405     (when (and (not modified) (buffer-modified-p))
8406       (set-buffer-modified-p nil))))
8407
8408 (defvar cperl-d-l nil)
8409 (defun cperl-fontify-syntaxically (end)
8410   ;; Some vars for debugging only
8411   ;; (message "Syntaxifying...")
8412   (let ((dbg (point)) (iend end)
8413         (istate (car cperl-syntax-state))
8414         start)
8415     (and cperl-syntaxify-unwind
8416          (setq end (cperl-unwind-to-safe t end)))
8417     (setq start (point))
8418     (or cperl-syntax-done-to
8419         (setq cperl-syntax-done-to (point-min)))
8420     (if (or (not (boundp 'font-lock-hot-pass))
8421             (eval 'font-lock-hot-pass)
8422             t)                          ; Not debugged otherwise
8423         ;; Need to forget what is after `start'
8424         (setq start (min cperl-syntax-done-to start))
8425       ;; Fontification without a change
8426       (setq start (max cperl-syntax-done-to start)))
8427     (and (> end start)
8428          (setq cperl-syntax-done-to start) ; In case what follows fails
8429          (cperl-find-pods-heres start end t nil t))
8430     (if (eq cperl-syntaxify-by-font-lock 'message)
8431         (message "Syntaxified %s..%s from %s to %s(%s), state %s-->%s"
8432                  dbg iend
8433                  start end cperl-syntax-done-to
8434                  istate (car cperl-syntax-state))) ; For debugging
8435     nil))                               ; Do not iterate
8436
8437 (defun cperl-fontify-update (end)
8438   (let ((pos (point)) prop posend)
8439     (while (< pos end)
8440       (setq prop (get-text-property pos 'cperl-postpone))
8441       (setq posend (next-single-property-change pos 'cperl-postpone nil end))
8442       (and prop (put-text-property pos posend (car prop) (cdr prop)))
8443       (setq pos posend)))
8444   nil)                                  ; Do not iterate
8445
8446 (defun cperl-update-syntaxification (from to)
8447   (if (and cperl-use-syntax-table-text-property
8448            cperl-syntaxify-by-font-lock
8449            (or (null cperl-syntax-done-to)
8450                (< cperl-syntax-done-to to)))
8451       (progn
8452         (save-excursion
8453           (goto-char from)
8454           (cperl-fontify-syntaxically to)))))
8455
8456 (defvar cperl-version
8457   (let ((v  "$Revision: 5.0 $"))
8458     (string-match ":\\s *\\([0-9.]+\\)" v)
8459     (substring v (match-beginning 1) (match-end 1)))
8460   "Version of IZ-supported CPerl package this file is based on.")
8461
8462 (provide 'cperl-mode)
8463
8464 ;;; cperl-mode.el ends here