]> git.donarmstrong.com Git - lib.git/blob - emacs_el/cperl-mode.el
update the version of cperl mode
[lib.git] / emacs_el / 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,
4 ;;               2000, 2003, 2005
5 ;;     Free Software Foundation, Inc.
6
7 ;; Author: Ilya Zakharevich and Bob Olson
8 ;; Maintainer: Ilya Zakharevich <cperl@ilyaz.org>
9 ;; Keywords: languages, Perl
10
11 ;; This file is part of GNU Emacs.
12
13 ;;; This code started from the following message of long time ago
14 ;;; (IZ), but Bob does not maintain this mode any more:
15
16 ;;; From: olson@mcs.anl.gov (Bob Olson)
17 ;;; Newsgroups: comp.lang.perl
18 ;;; Subject: cperl-mode: Another perl mode for Gnuemacs
19 ;;; Date: 14 Aug 91 15:20:01 GMT
20
21 ;; Copyright (C) Ilya Zakharevich and Bob Olson
22
23 ;; This file may be distributed
24 ;; either under the same terms as GNU Emacs, or under the same terms
25 ;; as Perl. You should have received a copy of Perl Artistic license
26 ;; along with the Perl distribution.
27
28 ;; GNU Emacs is free software; you can redistribute it and/or modify
29 ;; it under the terms of the GNU General Public License as published by
30 ;; the Free Software Foundation; either version 2, or (at your option)
31 ;; any later version.
32
33 ;; GNU Emacs is distributed in the hope that it will be useful,
34 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
35 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
36 ;; GNU General Public License for more details.
37
38 ;; You should have received a copy of the GNU General Public License
39 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
40 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
41 ;; Boston, MA 02111-1307, USA.
42
43 ;;; Corrections made by Ilya Zakharevich cperl@ilyaz.org
44 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
45
46 ;;; Commentary:
47
48 ;; $Id: cperl-mode.el,v 5.16 2006/02/21 11:18:21 vera Exp vera $
49
50 ;;; If your Emacs does not default to `cperl-mode' on Perl files:
51 ;;; To use this mode put the following into
52 ;;; your .emacs file:
53
54 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
55
56 ;; You can either fine-tune the bells and whistles of this mode or
57 ;; bulk enable them by putting
58
59 ;; (setq cperl-hairy t)
60
61 ;; in your .emacs file.  (Emacs rulers do not consider it politically
62 ;; correct to make whistles enabled by default.)
63
64 ;; DO NOT FORGET to read micro-docs (available from `Perl' menu)   <<<<<<
65 ;; or as help on variables `cperl-tips', `cperl-problems',         <<<<<<
66 ;; `cperl-non-problems', `cperl-praise', `cperl-speed'.            <<<<<<
67
68 ;; Additional useful commands to put into your .emacs file (before
69 ;; RMS Emacs 20.3):
70
71 ;; (setq auto-mode-alist
72 ;;      (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
73 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
74 ;;                                      '(("miniperl" . perl-mode))))
75
76 ;; The mode information (on C-h m) provides some customization help.
77 ;; If you use font-lock feature of this mode, it is advisable to use
78 ;; either lazy-lock-mode or fast-lock-mode.  I prefer lazy-lock.
79
80 ;; Faces used now: three faces for first-class and second-class keywords
81 ;; and control flow words, one for each: comments, string, labels,
82 ;; functions definitions and packages, arrays, hashes, and variable
83 ;; definitions.  If you do not see all these faces, your font-lock does
84 ;; not define them, so you need to define them manually.
85 ;; Maybe you have an obsolete font-lock from 19.28 or earlier.  Upgrade.
86
87 ;; If you have a grayscale monitor, and do not have the variable
88 ;; font-lock-display-type bound to 'grayscale, insert
89
90 ;; (setq font-lock-display-type 'grayscale)
91
92 ;; into your .emacs file (this is relevant before RMS Emacs 20).
93
94 ;; This mode supports font-lock, imenu and mode-compile.  In the
95 ;; hairy version font-lock is on, but you should activate imenu
96 ;; yourself (note that mode-compile is not standard yet).  Well, you
97 ;; can use imenu from keyboard anyway (M-x imenu), but it is better
98 ;; to bind it like that:
99
100 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
101
102 ;;; Font lock bugs as of v4.32:
103
104 ;; The following kinds of Perl code erroneously start strings:
105 ;; \$`  \$'  \$"
106 ;; $opt::s  $opt_s  $opt{s}  (s => ...)  /\s+.../
107 ;; likewise with m, tr, y, q, qX instead of s
108
109 ;;; In fact the version of font-lock that this version supports can be
110 ;;; much newer than the version you actually have. This means that a
111 ;;; lot of faces can be set up, but are not visible on your screen
112 ;;; since the coloring rules for this faces are not defined.
113
114 ;;; Updates: ========================================
115
116 ;;; Made less hairy by default: parentheses not electric,
117 ;;; linefeed not magic. Bug with abbrev-mode corrected.
118
119 ;;;; After 1.4:
120 ;;;  Better indentation:
121 ;;;  subs inside braces should work now,
122 ;;;  Toplevel braces obey customization.
123 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
124 ;;;  moves cursor to a correct place.
125 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-(
126 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
127 ;;;  Minor documentation fixes.
128 ;;;  Imenu understands packages as prefixes (including nested).
129 ;;;  Hairy options can be switched off one-by-one by setting to null.
130 ;;;  Names of functions and variables changed to conform to `cperl-' style.
131
132 ;;;; After 1.5:
133 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
134 ;;;  `cperl-indent-region' done (slow :-()).
135 ;;;  `cperl-fill-paragraph' done.
136 ;;;  Better package support for `imenu'.
137 ;;;  Progress indicator for indentation (with `imenu' loaded).
138 ;;;  `Cperl-set' was busted, now setting the individual hairy option
139 ;;;     should be better.
140
141 ;;;; After 1.6:
142 ;;; `cperl-set-style' done.
143 ;;; `cperl-check-syntax' done.
144 ;;; Menu done.
145 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
146 ;;; Bugs with `cperl-auto-newline' corrected.
147 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation
148 ;;; like $hash{.
149
150 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
151 ;;; - use `next-command-event', if `next-command-events' does not exist
152 ;;; - use `find-face' as def. of `is-face'
153 ;;; - corrected def. of `x-color-defined-p'
154 ;;; - added const defs for font-lock-comment-face,
155 ;;;   font-lock-keyword-face and font-lock-function-name-face
156 ;;; - added def. of font-lock-variable-name-face
157 ;;; - added (require 'easymenu) inside an `eval-when-compile'
158 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
159 ;;;   `define-key's
160 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
161 ;;; Todo (at least):
162 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
163 ;;;   for portable code?
164 ;;; - should `cperl-mode' do a
165 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
166 ;;;   or should this be left to the user's `cperl-mode-hook'?
167
168 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
169 ;;; Some bugs under XEmacs introduced by the correction corrected.
170
171 ;;; Some more can remain since there are two many different variants.
172 ;;; Please feedback!
173
174 ;;; We do not support fontification of arrays and hashes under
175 ;;; obsolete font-lock any more. Upgrade.
176
177 ;;;; after 1.8 Minor bug with parentheses.
178 ;;;; after 1.9 Improvements from Joe Marzot.
179 ;;;; after 1.10
180 ;;;  Does not need easymenu to compile under XEmacs.
181 ;;;  `vc-insert-headers' should work better.
182 ;;;  Should work with 19.29 and 19.12.
183 ;;;  Small improvements to fontification.
184 ;;;  Expansion of keywords does not depend on C-? being backspace.
185
186 ;;; after 1.10+
187 ;;; 19.29 and 19.12 supported.
188 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
189 ;;; Support for font-lock-extra.el.
190
191 ;;;; After 1.11:
192 ;;; Tools submenu.
193 ;;; Support for perl5-info.
194 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
195 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
196 ;;; Fontifies `require a if b;', __DATA__.
197 ;;; Arglist for auto-fill-mode was incorrect.
198
199 ;;;; After 1.12:
200 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions
201 ;;; vertically.
202 ;;; `cperl-do-auto-fill' updated for 19.29 style.
203 ;;; `cperl-info-on-command' now has a default.
204 ;;; Workaround for broken C-h on XEmacs.
205 ;;; VC strings escaped.
206 ;;; C-h f now may prompt for function name instead of going on,
207 ;;; controlled by `cperl-info-on-command-no-prompt'.
208
209 ;;;; After 1.13:
210 ;;; Msb buffer list includes perl files
211 ;;; Indent-for-comment uses indent-to
212 ;;; Can write tag files using etags.
213
214 ;;;; After 1.14:
215 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
216 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
217 ;;; Bug with auto-filling comments started with "##" corrected.
218
219 ;;;; Very slow now: on DB::DB 0.91, 486/66:
220
221 ;;;Function Name                             Call Count  Elapsed Time  Average Time
222 ;;;========================================  ==========  ============  ============
223 ;;;cperl-block-p                             469         3.7799999999  0.0080597014
224 ;;;cperl-get-state                           505         163.39000000  0.3235445544
225 ;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
226 ;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
227 ;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
228 ;;;cperl-indent-line                         505         172.88000000  0.3423366336
229 ;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
230 ;;;cperl-indent-exp                          1           177.97000000  177.97000000
231 ;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
232 ;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
233 ;;;cperl-indent-region                       1           177.94000000  177.94000000
234
235 ;;;; After 1.15:
236 ;;; Takes into account white space after opening parentheses during indent.
237 ;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
238 ;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
239 ;;; for indentation so far.
240 ;;; Fontification updated to 19.30 style.
241 ;;; The change 19.29->30 did not add all the required functionality,
242 ;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
243 ;;;       http://ilyaz.org/software/emacs
244
245 ;;;; After 1.16:
246 ;;;       else # comment
247 ;;;    recognized as a start of a block.
248 ;;;  Two different font-lock-levels provided.
249 ;;;  `cperl-pod-head-face' introduced. Used for highlighting.
250 ;;;  `imenu' marks pods, +Packages moved to the head.
251
252 ;;;; After 1.17:
253 ;;;  Scan for pods highlights here-docs too.
254 ;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
255 ;;;  Only one here-doc-tag per line is supported, and one in comment
256 ;;;  or a string may break fontification.
257 ;;;  POD headers were supposed to fill one line only.
258
259 ;;;; After 1.18:
260 ;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme
261 ;;;    may  break under XEmacs.
262 ;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
263 ;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
264 ;;;    compatibility with older lazy-lock.el) (older one overfontifies
265 ;;;    something nevertheless :-().
266 ;;;  Will not indent something inside pod and here-documents.
267 ;;;  Fontifies the package name after import/no/bootstrap.
268 ;;;  Added new entry to menu with meta-info about the mode.
269
270 ;;;; After 1.19:
271 ;;;  Prefontification works much better with 19.29. Should be checked
272 ;;;   with 19.30 as well.
273 ;;;  Some misprints in docs corrected.
274 ;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
275 ;;;  Now the pod search is much stricter, so it can help you to find
276 ;;;    pod sections which are broken because of whitespace before =blah
277 ;;;    - just observe the fontification.
278
279 ;;;; After 1.20
280 ;;;  Anonymous subs are indented with respect to the level of
281 ;;;    indentation of `sub' now.
282 ;;;  {} is recognized as hash after `bless' and `return'.
283 ;;;  Anonymous subs are split by `cperl-linefeed' as well.
284 ;;;  Electric parens embrace a region if present.
285 ;;;  To make `cperl-auto-newline' useful,
286 ;;;    `cperl-auto-newline-after-colon' is introduced.
287 ;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
288 ;;;  `cperl-electric-parens-string'.
289 ;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
290 ;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
291 ;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
292 ;;;  Beginning-of-defun-regexp was not anchored.
293
294 ;;;; After 1.21
295 ;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
296 ;;;    after ")".
297 ;;;  {} is recognized as expression after `tr' and friends.
298
299 ;;;; After 1.22
300 ;;;  Entry Hierarchy added to imenu. Very primitive so far.
301 ;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
302 ;;;  Writes its own TAGS files.
303 ;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
304 ;;;  19.31: Problems with scan for PODs corrected.
305 ;;;  First POD header correctly fontified.
306 ;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
307 ;;;  Apparently it makes a lot of hierarchy code obsolete...
308
309 ;;;; After 1.23
310 ;;;  Tags filler now scans *.xs as well.
311 ;;;  The info from *.xs scan is used by the hierarchy viewer.
312 ;;;  Hierarchy viewer documented.
313 ;;;  Bug in 19.31 imenu documented.
314
315 ;;;; After 1.24
316 ;;;  New location for info-files mentioned,
317 ;;;  Electric-; should work better.
318 ;;;  Minor bugs with POD marking.
319
320 ;;;; After 1.25 (probably not...)
321 ;;;  `cperl-info-page' introduced.
322 ;;;  To make `uncomment-region' working, `comment-region' would
323 ;;;  not insert extra space.
324 ;;;  Here documents delimiters better recognized
325 ;;;  (empty one, and non-alphanums in quotes handled). May be wrong with 1<<14?
326 ;;;  `cperl-db' added, used in menu.
327 ;;;  imenu scan removes text-properties, for better debugging
328 ;;;    - but the bug is in 19.31 imenu.
329 ;;;  formats highlighted by font-lock and prescan, embedded comments
330 ;;;  are not treated.
331 ;;;  POD/friends scan merged in one pass.
332 ;;;  Syntax class is not used for analyzing the code, only char-syntax
333 ;;;  may be checked against _ or'ed with w.
334 ;;;  Syntax class of `:' changed to be _.
335 ;;;  `cperl-find-bad-style' added.
336
337 ;;;; After 1.25
338 ;;;  When search for here-documents, we ignore commented << in simplest cases.
339 ;;;  `cperl-get-help' added, available on C-h v and from menu.
340 ;;;  Auto-help added. Default with `cperl-hairy', switchable on/off
341 ;;;   with startup variable `cperl-lazy-help-time' and from
342 ;;;   menu. Requires `run-with-idle-timer'.
343 ;;;  Highlighting of @abc{@efg} was wrong - interchanged two regexps.
344
345 ;;;; After 1.27
346 ;;;  Indentation: At toplevel after a label - fixed.
347 ;;;  1.27 was put to archives in binary mode ===> DOSish :-(
348
349 ;;;; After 1.28
350 ;;;  Thanks to Martin Buchholz <mrb@Eng.Sun.COM>: misprints in
351 ;;;  comments and docstrings corrected, XEmacs support cleaned up.
352 ;;;  The closing parenths would enclose the region into matching
353 ;;;  parens under the same conditions as the opening ones.
354 ;;;  Minor updates to `cperl-short-docs'.
355 ;;;  Will not consider <<= as start of here-doc.
356
357 ;;;; After 1.29
358 ;;;  Added an extra advice to look into Micro-docs. ;-).
359 ;;;  Enclosing of region when you press a closing parenth is regulated by
360 ;;;  `cperl-electric-parens-string'.
361 ;;;  Minor updates to `cperl-short-docs'.
362 ;;;  `initialize-new-tags-table' called only if present (Does this help
363 ;;;     with generation of tags under XEmacs?).
364 ;;;  When creating/updating tag files, new info is written at the old place,
365 ;;;     or at the end (is this a wanted behaviour? I need this in perl build directory).
366
367 ;;;; After 1.30
368 ;;;  All the keywords from keywords.pl included (maybe with dummy explanation).
369 ;;;  No auto-help inside strings, comment, here-docs, formats, and pods.
370 ;;;  Shrinkwrapping of info, regulated by `cperl-max-help-size',
371 ;;;  `cperl-shrink-wrap-info-frame'.
372 ;;;  Info on variables as well.
373 ;;;  Recognision of HERE-DOCS improved yet more.
374 ;;;  Autonewline works on `}' without warnings.
375 ;;;  Autohelp works again on $_[0].
376
377 ;;;; After 1.31
378 ;;;  perl-descr.el found its author - hi, Johan!
379 ;;;  Some support for correct indent after here-docs and friends (may
380 ;;;  be superseeded by eminent change to Emacs internals).
381 ;;;  Should work with older Emaxen as well ( `-style stuff removed).
382
383 ;;;; After 1.32
384
385 ;;;  Started to add support for `syntax-table' property (should work
386 ;;;  with patched Emaxen), controlled by
387 ;;;  `cperl-use-syntax-table-text-property'. Currently recognized:
388 ;;;    All quote-like operators: m, s, y, tr, qq, qw, qx, q,
389 ;;;    // in most frequent context:
390 ;;;          after block or
391 ;;;                    ~ { ( = | & + - * ! , ;
392 ;;;          or
393 ;;;                    while if unless until and or not xor split grep map
394 ;;;    Here-documents, formats, PODs,
395 ;;;    ${...}
396 ;;;    'abc$'
397 ;;;    sub a ($); sub a ($) {}
398 ;;;  (provide 'cperl-mode) was missing!
399 ;;;  `cperl-after-expr-p' is now much smarter after `}'.
400 ;;;  `cperl-praise' added to mini-docs.
401 ;;;  Utilities try to support subs-with-prototypes.
402
403 ;;;; After 1.32.1
404 ;;;  `cperl-after-expr-p' is now much smarter after "() {}" and "word {}":
405 ;;;     if word is "else, map, grep".
406 ;;;  Updated for new values of syntax-table constants.
407 ;;;  Uses `help-char' (at last!) (disabled, does not work?!)
408 ;;;  A couple of regexps where missing _ in character classes.
409 ;;;  -s could be considered as start of regexp, 1../blah/ was not,
410 ;;;  as was not /blah/ at start of file.
411
412 ;;;; After 1.32.2
413 ;;;  "\C-hv" was wrongly "\C-hf"
414 ;;;  C-hv was not working on `[index()]' because of [] in skip-chars-*.
415 ;;;  `__PACKAGE__' supported.
416 ;;;  Thanks for Greg Badros: `cperl-lazy-unstall' is more complete,
417 ;;;  `cperl-get-help' is made compatible with `query-replace'.
418
419 ;;;; As of Apr 15, development version of 19.34 supports
420 ;;;; `syntax-table' text properties. Try setting
421 ;;;; `cperl-use-syntax-table-text-property'.
422
423 ;;;; After 1.32.3
424 ;;;  We scan for s{}[] as well (in simplest situations).
425 ;;;  We scan for $blah'foo as well.
426 ;;;  The default is to use `syntax-table' text property if Emacs is good enough.
427 ;;;  `cperl-lineup' is put on C-M-| (=C-M-S-\\).
428 ;;;  Start of `cperl-beautify-regexp'.
429
430 ;;;; After 1.32.4
431 ;;; `cperl-tags-hier-init' did not work in text-mode.
432 ;;; `cperl-noscan-files-regexp' had a misprint.
433 ;;; Generation of Class Hierarchy was broken due to a bug in `x-popup-menu'
434 ;;;  in 19.34.
435
436 ;;;; After 1.33:
437 ;;; my,local highlight vars after {} too.
438 ;;; TAGS could not be created before imenu was loaded.
439 ;;; `cperl-indent-left-aligned-comments' created.
440 ;;; Logic of `cperl-indent-exp' changed a little bit, should be more
441 ;;;  robust w.r.t. multiline strings.
442 ;;; Recognition of blah'foo takes into account strings.
443 ;;; Added '.al' to the list of Perl extensions.
444 ;;; Class hierarchy is "mostly" sorted (need to rethink algorthm
445 ;;;  of pruning one-root-branch subtrees to get yet better sorting.)
446 ;;; Regeneration of TAGS was busted.
447 ;;; Can use `syntax-table' property when generating TAGS
448 ;;;  (governed by  `cperl-use-syntax-table-text-property-for-tags').
449
450 ;;;; After 1.35:
451 ;;; Can process several =pod/=cut sections one after another.
452 ;;; Knows of `extproc' when under `emx', indents with `__END__' and `__DATA__'.
453 ;;; `cperl-under-as-char' implemented (XEmacs people like broken behaviour).
454 ;;; Beautifier for regexps fixed.
455 ;;; `cperl-beautify-level', `cperl-contract-level' coded
456 ;;;
457 ;;;; Emacs's 20.2 problems:
458 ;;; `imenu.el' has bugs, `imenu-add-to-menubar' does not work.
459 ;;; Couple of others problems with 20.2 were reported, my ability to check/fix
460 ;;; them is very reduced now.
461
462 ;;;; After 1.36:
463 ;;;  'C-M-|' in XEmacs fixed
464
465 ;;;; After 1.37:
466 ;;;  &&s was not recognized as start of regular expression;
467 ;;;  Will "preprocess" the contents of //e part of s///e too;
468 ;;;  What to do with s# blah # foo #e ?
469 ;;;  Should handle s;blah;foo;; better.
470 ;;;  Now the only known problems with regular expression recognition:
471 ;;;;;;;  s<foo>/bar/    - different delimiters (end ignored)
472 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into one chunk)
473 ;;;;;;;  s/foo//        - empty subst (made into one chunk + '/')
474 ;;;;;;;  s/foo/(bar)/   - start-group at start of subst (internal group will not match backwards)
475
476 ;;;; After 1.38:
477 ;;;  We highlight closing / of s/blah/foo/e;
478 ;;;  This handles s# blah # foo #e too;
479 ;;;  s//blah/, s///, s/blah// works again, and s#blah## too, the algorithm
480 ;;;   is much simpler now;
481 ;;;  Next round of changes: s\\\ works, s<blah>/foo/,
482 ;;;   comments between the first and the second part allowed
483 ;;;  Another problem discovered:
484 ;;;;;;;  s[foo] <blah>e - e part delimited by different <> (will not match)
485 ;;;  `cperl-find-pods-heres' somehow maybe called when string-face is undefined
486 ;;;   - put a stupid workaround for 20.1
487
488 ;;;; After 1.39:
489 ;;;  Could indent here-docs for comments;
490 ;;;  These problems fixed:
491 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into two chunk)
492 ;;;;;;;  s[foo] <blah>e - "e" part delimited by "different" <> (will match)
493 ;;;  Matching brackets honor prefices, may expand abbreviations;
494 ;;;  When expanding abbrevs, will remove last char only after
495 ;;;    self-inserted whitespace;
496 ;;;  More convenient "Refress hard constructs" in menu;
497 ;;;  `cperl-add-tags-recurse', `cperl-add-tags-recurse-noxs'
498 ;;;    added (for -batch mode);
499 ;;;  Better handling of errors when scanning for Perl constructs;
500 ;;;;;;;  Possible "problem" with class hierarchy in Perl distribution
501 ;;;;;;;    directory: ./ext duplicates ./lib;
502 ;;;  Write relative paths for generated TAGS;
503
504 ;;;; After 1.40:
505 ;;;  s  /// may be separated by "\n\f" too;
506 ;;;  `s  #blah' recognized as a comment;
507 ;;;  Would highlight s/abc//s wrong;
508 ;;;  Debugging code in `cperl-electric-keywords' was leaking a message;
509
510 ;;;; After 1.41:
511 ;;;  RMS changes for 20.3 merged
512
513 ;;;; 2.0.1.0: RMS mode (has 3 misprints)
514
515 ;;;; After 2.0:
516 ;;;  RMS whitespace changes for 20.3 merged
517
518 ;;;; After 2.1:
519 ;;;  History updated
520
521 ;;;; After 2.2:
522 ;;;  Merge `c-style-alist' since `c-mode' is no more.  (Somebody who
523 ;;;    uses the styles should check that they work OK!)
524 ;;;  All the variable warnings go away, some undef functions too.
525
526 ;;;; After 2.3:
527 ;;;  Added `cperl-perldoc' (thanks to Anthony Foiani <afoiani@uswest.com>)
528 ;;;  Added `cperl-pod-to-manpage' (thanks to Nick Roberts <Nick.Roberts@src.bae.co.uk>)
529 ;;;  All the function warnings go away.
530
531 ;;;; After 2.4:
532 ;;;  `Perl doc', `Regexp' submenus created (latter to allow short displays).
533 ;;;  `cperl-clobber-lisp-bindings' added.
534 ;;;  $a->y() is not y///.
535 ;;;  `cperl-after-block-p' was missing a `save-excursion' => wrong results.
536 ;;;  `cperl-val' was defined too late.
537 ;;;  `cperl-init-faces' was failing.
538 ;;;  Init faces when loading `ps-print'.
539
540 ;;;; After 2.4:
541 ;;;  `cperl-toggle-autohelp' implemented.
542 ;;;  `while SPACE LESS' was buggy.
543 ;;;  `-text' in `[-text => 1]' was not highlighted.
544 ;;;  `cperl-after-block-p' was FALSE after `sub f {}'.
545
546 ;;;; After 2.5:
547 ;;;  `foreachmy', `formy' expanded too.
548 ;;;  Expand `=pod-directive'.
549 ;;;  `cperl-linefeed' behaves reasonable in POD-directive lines.
550 ;;;  `cperl-electric-keyword' prints a message, governed by
551 ;;;    `cperl-message-electric-keyword'.
552
553 ;;;; After 2.6:
554 ;;;  Typing `}' was not checking for being block or not.
555 ;;;  Beautifying levels in RE: Did not know about lookbehind;
556 ;;;                            finding *which* level was not intuitive;
557 ;;;                            `cperl-beautify-levels' added.
558 ;;;  Allow here-docs contain `=head1' and friends (at least for keywords).
559
560 ;;;; After 2.7:
561 ;;;  Fix for broken `font-lock-unfontify-region-function'.  Should
562 ;;;    preserve `syntax-table' properties even with `lazy-lock'.
563
564 ;;;; After 2.8:
565 ;;;  Some more compile time warnings crept in.
566 ;;;  `cperl-indent-region-fix-else' implemented.
567 ;;;  `cperl-fix-line-spacing' implemented.
568 ;;;  `cperl-invert-if-unless' implemented (C-c C-t and in Menu).
569 ;;;  Upgraded hints to mention 20.2's goods/bads.
570 ;;;  Started to use `cperl-extra-newline-before-brace-multiline',
571 ;;;    `cperl-break-one-line-blocks-when-indent',
572 ;;;    `cperl-fix-hanging-brace-when-indent', `cperl-merge-trailing-else'.
573
574 ;;;; After 2.9:
575 ;;;  Workaround for another `font-lock's `syntax-table' text-property bug.
576 ;;;  `zerop' could be applied to nil.
577 ;;;  At last, may work with `font-lock' without setting `cperl-font-lock'.
578 ;;;    (We expect that starting from 19.33, `font-lock' supports keywords
579 ;;;     being a function - what is a correct version?)
580 ;;;  Rename `cperl-indent-region-fix-else' to
581 ;;;    `cperl-indent-region-fix-constructs'.
582 ;;;  `cperl-fix-line-spacing' could be triggered inside strings, would not
583 ;;;     know what to do with BLOCKs of map/printf/etc.
584 ;;;  `cperl-merge-trailing-else' and `cperl-fix-line-spacing' handle
585 ;;;     `continue' too.
586 ;;;  Indentation after {BLOCK} knows about map/printf/etc.
587 ;;;  Finally: treat after-comma lines as continuation lines.
588
589 ;;;; After 2.10:
590 ;;;  `continue' made electric.
591 ;;;  Electric `do' inserts `do/while'.
592 ;;;  Some extra compile-time warnings crept in.
593 ;;;  `font-lock' of 19.33 could not handle font-lock-keywords being a function
594 ;;;      returning a symbol.
595
596 ;;;; After 2.11:
597 ;;;  Changes to make syntaxification to be autoredone via `font-lock'.
598 ;;;    Switched on by `cperl-syntaxify-by-font-lock', off by default so far.
599
600 ;;;; After 2.12:
601 ;;;  Remove some commented out chunks.
602 ;;;  Styles are slightly updated (a lot of work is needed, especially
603 ;;;    with new `cperl-fix-line-spacing').
604
605 ;;;; After 2.13:
606 ;;;  Old value of style is memorized when choosing a new style, may be
607 ;;;    restored from the same menu.
608 ;;;  Mode-documentation added to micro-docs.
609 ;;;  `cperl-praise' updated.
610 ;;;  `cperl-toggle-construct-fix' added on C-c C-w and menu.
611 ;;;  `auto-fill-mode' added on C-c C-f and menu.
612 ;;;  `PerlStyle' style added.
613 ;;;  Message for termination of scan corrected.
614
615 ;;;; After 2.14:
616
617 ;;;  Did not work with -q
618
619 ;;;; After 2.15:
620
621 ;;;  `cperl-speed' hints added.
622 ;;;  Minor style fixes.
623
624 ;;;; After 2.15:
625 ;;;  Make backspace electric after expansion of `else/continue' too.
626
627 ;;;; After 2.16:
628 ;;;  Starting to merge changes to RMS emacs version.
629
630 ;;;; After 2.17:
631 ;;;  Merged custom stuff and darn `font-lock-constant-face'.
632
633 ;;;; After 2.18:
634 ;;;  Bumped the version to 3.1
635
636 ;;;; After 3.1:
637 ;;;  Fixed customization to honor cperl-hairy.
638 ;;;  Created customization groups.  Sent to RMS to include into 2.3.
639
640 ;;;; After 3.2:
641 ;;;  Interaction of `font-lock-hot-pass' and `cperl-syntaxify-by-font-lock'.
642 ;;;  (`cperl-after-block-and-statement-beg'):
643 ;;;  (`cperl-after-block-p'):
644 ;;;  (`cperl-after-expr-p'):    It is BLOCK if we reach lim when backup sexp.
645 ;;;  (`cperl-indent-region'):   Make a marker for END - text added/removed.
646 ;;;  (`cperl-style-alist', `cperl-styles-entries')
647 ;;;             Include `cperl-merge-trailing-else' where the value is clear.
648
649 ;;;; After 3.3:
650 ;;;  (`cperl-tips'):
651 ;;;  (`cperl-problems'):        Improvements to docs.
652
653 ;;;; After 3.4:
654 ;;;  (`cperl-mode'):            Make lazy syntaxification possible.
655 ;;;  (`cperl-find-pods-heres'): Safe a position in buffer where it is safe to
656 ;;;                             restart syntaxification.
657 ;;;  (`cperl-syntaxify-by-font-lock'): Set to t, should be safe now.
658
659 ;;;; After 3.5:
660 ;;;  (`cperl-syntaxify-by-font-lock'): Better default, customizes to
661 ;;;                             `message' too.
662
663 ;;;; After 3.6:
664 ;;;  (`cperl-find-pods-heres'): changed so that -d ?foo? is a RE.
665 ;;;  (`cperl-array-face'): changed name from `font-lock-emphasized-face'.
666 ;;;  (`cperl-hash-face'): changed name from  `font-lock-other-emphasized-face'.
667 ;;;  Use `defface' to define these two extra faces.
668
669 ;;;; After 3.7:
670 ;;;  Can use linear algorithm for indentation if Emacs supports it:
671 ;;;  indenting DB::DB (800+ lines) improved from 69 sec to 11 sec
672 ;;;  (73 vs 15 with imenu).
673 ;;;  (`cperl-emacs-can-parse'): New state.
674 ;;;  (`cperl-indent-line'):     Corrected to use global state.
675 ;;;  (`cperl-calculate-indent'):        Likewise.
676 ;;;  (`cperl-fix-line-spacing'):        Likewise (not used yet).
677
678 ;;;; After 3.8:
679 ;;;  (`cperl-choose-color'):    Converted to a function (to be compilable in text-mode).
680
681 ;;;; After 3.9:
682 ;;;  (`cperl-dark-background '):        Disable without window-system.
683
684 ;;;; After 3.10:
685 ;;;  Do `defface' only if window-system.
686
687 ;;;; After 3.11:
688 ;;;  (`cperl-fix-line-spacing'):        sped up to bail out early.
689 ;;;  (`cperl-indent-region'):   Disable hooks during the call (how to call them later?).
690
691 ;;;  Now indents 820-line-long function in 6.5 sec (including syntaxification) the first time
692 ;;;  (when buffer has few properties), 7.1 sec the second time.
693
694 ;;;Function Name                              Call Count  Elapsed Time  Average Time
695 ;;;=========================================  ==========  ============  ============
696 ;;;cperl-indent-exp                           1           10.039999999  10.039999999
697 ;;;cperl-indent-region                        1           10.0          10.0
698 ;;;cperl-indent-line                          821         6.2100000000  0.0075639464
699 ;;;cperl-calculate-indent                     821         5.0199999999  0.0061144945
700 ;;;cperl-backward-to-noncomment               2856        2.0500000000  0.0007177871
701 ;;;cperl-fontify-syntaxically                 2           1.78          0.8900000000
702 ;;;cperl-find-pods-heres                      2           1.78          0.8900000000
703 ;;;cperl-update-syntaxification               1           1.78          1.78
704 ;;;cperl-fix-line-spacing                     769         1.4800000000  0.0019245773
705 ;;;cperl-after-block-and-statement-beg        163         1.4100000000  0.0086503067
706 ;;;cperl-block-p                              775         1.1800000000  0.0015225806
707 ;;;cperl-to-comment-or-eol                    3652        1.1200000000  0.0003066812
708 ;;;cperl-after-block-p                        165         1.0500000000  0.0063636363
709 ;;;cperl-commentify                           141         0.22          0.0015602836
710 ;;;cperl-get-state                            813         0.16          0.0001968019
711 ;;;cperl-backward-to-start-of-continued-exp   26          0.12          0.0046153846
712 ;;;cperl-delay-update-hook                    2107        0.0899999999  4.271...e-05
713 ;;;cperl-protect-defun-start                  141         0.0700000000  0.0004964539
714 ;;;cperl-after-label                          407         0.0599999999  0.0001474201
715 ;;;cperl-forward-re                           139         0.0299999999  0.0002158273
716 ;;;cperl-comment-indent                       26          0.0299999999  0.0011538461
717 ;;;cperl-use-region-p                         8           0.0           0.0
718 ;;;cperl-lazy-hook                            15          0.0           0.0
719 ;;;cperl-after-expr-p                         8           0.0           0.0
720 ;;;cperl-font-lock-unfontify-region-function  1           0.0           0.0
721
722 ;;;Function Name                              Call Count  Elapsed Time  Average Time
723 ;;;=========================================  ==========  ============  ============
724 ;;;cperl-fix-line-spacing                     769         1.4500000000  0.0018855656
725 ;;;cperl-indent-line                          13          0.3100000000  0.0238461538
726 ;;;cperl-after-block-and-statement-beg        69          0.2700000000  0.0039130434
727 ;;;cperl-after-block-p                        69          0.2099999999  0.0030434782
728 ;;;cperl-calculate-indent                     13          0.1000000000  0.0076923076
729 ;;;cperl-backward-to-noncomment               177         0.0700000000  0.0003954802
730 ;;;cperl-get-state                            13          0.0           0.0
731 ;;;cperl-to-comment-or-eol                    179         0.0           0.0
732 ;;;cperl-get-help-defer                       1           0.0           0.0
733 ;;;cperl-lazy-hook                            11          0.0           0.0
734 ;;;cperl-after-expr-p                         2           0.0           0.0
735 ;;;cperl-block-p                              13          0.0           0.0
736 ;;;cperl-after-label                          5           0.0           0.0
737
738 ;;;; After 3.12:
739 ;;;  (`cperl-find-pods-heres'): do not warn on `=cut' if doing a chunk only.
740
741 ;;;; After 3.13:
742 ;;;  (`cperl-mode'): load pseudo-faces on `cperl-find-pods-heres' (for 19.30).
743 ;;;  (`x-color-defined-p'): was not compiling on XEmacs
744 ;;;  (`cperl-find-pods-heres'): 1 << 6 was OK, but 1<<6 was considered as HERE
745 ;;;                             <file/glob> made into a string.
746
747 ;;;; After 3.14:
748 ;;;  (`cperl-find-pods-heres'): Postpone addition of faces after syntactic step
749 ;;;                             Recognition of <FH> was wrong.
750 ;;;  (`cperl-clobber-lisp-bindings'): if set, C-c variants are the old ones
751 ;;;  (`cperl-unwind-to-safe'):  New function.
752 ;;;  (`cperl-fontify-syntaxically'): Use `cperl-unwind-to-safe' to start at reasonable position.
753
754 ;;;; After 3.15:
755 ;;;  (`cperl-forward-re'):      Highlight the trailing / in s/foo// as string.
756 ;;;                     Highlight the starting // in s//foo/ as function-name.
757
758 ;;;; After 3.16:
759 ;;;  (`cperl-find-pods-heres'): Highlight `gem' in s///gem as a keyword.
760
761 ;;;; After 4.0:
762 ;;;  (`cperl-find-pods-heres'): `qr' added
763 ;;;  (`cperl-electric-keyword'):        Likewise
764 ;;;  (`cperl-electric-else'):           Likewise
765 ;;;  (`cperl-to-comment-or-eol'):       Likewise
766 ;;;  (`cperl-make-regexp-x'):   Likewise
767 ;;;  (`cperl-init-faces'):      Likewise, and `lock' (as overridable?).
768 ;;;  (`cperl-find-pods-heres'): Knows that split// is null-RE.
769 ;;;                             Highlights separators in 3-parts expressions
770 ;;;                             as labels.
771
772 ;;;; After 4.1:
773 ;;;  (`cperl-find-pods-heres'): <> was considered as a glob
774 ;;;  (`cperl-syntaxify-unwind'): New configuration variable
775 ;;;  (`cperl-fontify-m-as-s'):  New configuration variable
776
777 ;;;; After 4.2:
778 ;;;  (`cperl-find-pods-heres'): of the last line being `=head1' fixed.
779
780 ;;;  Handling of a long construct is still buggy if only the part of
781 ;;;  construct touches the updated region (we unwind to the start of
782 ;;;  long construct, but the end may have residual properties).
783
784 ;;;  (`cperl-unwind-to-safe'):  would not go to beginning of buffer.
785 ;;;  (`cperl-electric-pod'):    check for after-expr was performed
786 ;;;                             inside of POD too.
787
788 ;;;; After 4.3:
789 ;;;  (`cperl-backward-to-noncomment'):  better treatment of PODs and HEREs.
790
791 ;;;  Indent-line works good, but indent-region does not - at toplevel...
792 ;;;  (`cperl-unwind-to-safe'):  Signature changed.
793 ;;;  (`x-color-defined-p'):     was defmacro'ed with a tick.  Remove another def.
794 ;;;  (`cperl-clobber-mode-lists'): New configuration variable.
795 ;;;  (`cperl-array-face'): One of definitions was garbled.
796
797 ;;;; After 4.4:
798 ;;;  (`cperl-not-bad-style-regexp'):    Updated.
799 ;;;  (`cperl-make-regexp-x'):   Misprint in a message.
800 ;;;  (`cperl-find-pods-heres'): $a-1 ? foo : bar; was a regexp.
801 ;;;                             `<< (' was considered a start of POD.
802 ;;;  Init:                      `cperl-is-face' was busted.
803 ;;;  (`cperl-make-face'):       New macros.
804 ;;;  (`cperl-force-face'):      New macros.
805 ;;;  (`cperl-init-faces'):      Corrected to use new macros;
806 ;;;                             `if' for copying `reference-face' to
807 ;;;                             `constant-face' was backward.
808 ;;;  (`font-lock-other-type-face'): Done via `defface' too.
809
810 ;;;; After 4.5:
811 ;;;  (`cperl-init-faces-weak'): use `cperl-force-face'.
812 ;;;  (`cperl-after-block-p'):   After END/BEGIN we are a block.
813 ;;;  (`cperl-mode'):            `font-lock-unfontify-region-function'
814 ;;;                             was set to a wrong function.
815 ;;;  (`cperl-comment-indent'):  Commenting __END__ was not working.
816 ;;;  (`cperl-indent-for-comment'):      Likewise.
817 ;;;                             (Indenting is still misbehaving at toplevel.)
818
819 ;;;; After 4.5:
820 ;;;  (`cperl-unwind-to-safe'):  Signature changed, unwinds end too.
821 ;;;  (`cperl-find-pods-heres'): mark qq[]-etc sections as syntax-type=string
822 ;;;  (`cperl-fontify-syntaxically'): Unwinds start and end to go out of
823 ;;;                                  long strings (not very successful).
824
825 ;;;   >>>>  CPerl should be usable in write mode too now <<<<
826
827 ;;;  (`cperl-syntaxify-by-font-lock'): Better default - off in text-mode.
828 ;;;  (`cperl-tips'):            Updated docs.
829 ;;;  (`cperl-problems'):        Updated docs.
830
831 ;;;; After 4.6:
832 ;;;  (`cperl-calculate-indent'):        Did not consider `,' as continuation mark for statements.
833 ;;;  (`cperl-write-tags'):      Correct for XEmacs's `visit-tags-table-buffer'.
834
835 ;;;; After 4.7:
836 ;;;  (`cperl-calculate-indent'): Avoid parse-data optimization at toplevel.
837 ;;;                              Should indent correctly at toplevel too.
838 ;;;  (`cperl-tags-hier-init'):  Gross hack to pretend we work (are we?).
839 ;;;  (`cperl-find-pods-heres'): Was not processing sub protos after a comment ine.
840 ;;;                             Was treating $a++ <= 5 as a glob.
841
842 ;;;; After 4.8:
843 ;;;  (toplevel):                require custom unprotected => failure on 19.28.
844 ;;;  (`cperl-xemacs-p')         defined when compile too
845 ;;;  (`cperl-tags-hier-init'):  Another try to work around XEmacs problems
846 ;;;                             Better progress messages.
847 ;;;  (`cperl-find-tags'):       Was writing line/pos in a wrong order,
848 ;;;                             pos off by 1 and not at beg-of-line.
849 ;;;  (`cperl-etags-snarf-tag'): New macro
850 ;;;  (`cperl-etags-goto-tag-location'): New macro
851 ;;;  (`cperl-write-tags'):      When removing old TAGS info was not
852 ;;;                             relativizing filename
853
854 ;;;; After 4.9:
855 ;;;  (`cperl-version'):         New variable.  New menu entry
856
857 ;;;; After 4.10:
858 ;;;  (`cperl-tips'):            Updated.
859 ;;;  (`cperl-non-problems'):    Updated.
860 ;;;  random:                    References to future 20.3 removed.
861
862 ;;;; After 4.11:
863 ;;;  (`perl-font-lock-keywords'): Would not highlight `sub foo($$);'.
864 ;;;  Docstrings:                Menu was described as `CPerl' instead of `Perl'
865
866 ;;;; After 4.12:
867 ;;;  (`cperl-toggle-construct-fix'): Was toggling to t instead of 1.
868 ;;;  (`cperl-ps-print-init'):   Associate `cperl-array-face', `cperl-hash-face'
869 ;;;                             remove `font-lock-emphasized-face'.
870 ;;;                             remove `font-lock-other-emphasized-face'.
871 ;;;                             remove `font-lock-reference-face'.
872 ;;;                             remove `font-lock-keyword-face'.
873 ;;;                             Use `eval-after-load'.
874 ;;;  (`cperl-init-faces'):      remove init `font-lock-other-emphasized-face'.
875 ;;;                             remove init `font-lock-emphasized-face'.
876 ;;;                             remove init `font-lock-keyword-face'.
877 ;;;  (`cperl-tips-faces'):      New variable and an entry into Mini-docs.
878 ;;;  (`cperl-indent-region'):   Do not indent whitespace lines
879 ;;;  (`cperl-indent-exp'):      Was not processing else-blocks.
880 ;;;  (`cperl-calculate-indent'): Remove another parse-data optimization
881 ;;;                              at toplevel: would indent correctly.
882 ;;;  (`cperl-get-state'):       NOP line removed.
883
884 ;;;; After 4.13:
885 ;;;  (`cperl-ps-print-init'):   Remove not-CPerl-related faces.
886 ;;;  (`cperl-ps-print'):        New function and menu entry.
887 ;;;  (`cperl-ps-print-face-properties'):        New configuration variable.
888 ;;;  (`cperl-invalid-face'):    New configuration variable.
889 ;;;  (`cperl-nonoverridable-face'):     New face.  Renamed from
890 ;;;                                     `font-lock-other-type-face'.
891 ;;;  (`perl-font-lock-keywords'):       Highlight trailing whitespace
892 ;;;  (`cperl-contract-levels'): Documentation corrected.
893 ;;;  (`cperl-contract-level'):  Likewise.
894
895 ;;;; After 4.14:
896 ;;;  (`cperl-ps-print'): `ps-print-face-extension-alist' was not in old Emaxen,
897 ;;;                             same with `ps-extend-face-list'
898 ;;;  (`cperl-ps-extend-face-list'):     New macro.
899
900 ;;;; After 4.15:
901 ;;;  (`cperl-init-faces'):      Interpolate `cperl-invalid-face'.
902 ;;;  (`cperl-forward-re'):      Emit a meaningful error instead of a cryptic
903 ;;;                             one for uncomplete REx near end-of-buffer.
904 ;;;  (`cperl-find-pods-heres'): Tolerate unfinished REx at end-of-buffer.
905
906 ;;;; After 4.16:
907 ;;;  (`cperl-find-pods-heres'): `unwind-protect' was left commented.
908
909 ;;;; After 4.17:
910 ;;;  (`cperl-invalid-face'):    Change to ''underline.
911
912 ;;;; After 4.18:
913 ;;;  (`cperl-find-pods-heres'): / and ? after : start a REx.
914 ;;;  (`cperl-after-expr-p'):    Skip labels when checking
915 ;;;  (`cperl-calculate-indent'): Correct for labels when calculating
916 ;;;                                     indentation of continuations.
917 ;;;                             Docstring updated.
918
919 ;;;; After 4.19:
920 ;;;  Minor (mostly spelling) corrections from 20.3.3 merged.
921
922 ;;;; After 4.20:
923 ;;;  (`cperl-tips'):            Another workaround added.  Sent to RMS for 20.4.
924
925 ;;;; After 4.21:
926 ;;;  (`cperl-praise'):          Mention linear-time indent.
927 ;;;  (`cperl-find-pods-heres'): @if ? a : b was considered a REx.
928
929 ;;;; After 4.22:
930 ;;;  (`cperl-after-expr-p'):    Make true after __END__.
931 ;;;  (`cperl-electric-pod'):    "SYNOPSIS" was misspelled.
932
933 ;;;; After 4.23:
934 ;;;  (`cperl-beautify-regexp-piece'):   Was not allowing for *? after a class.
935 ;;;                                     Allow for POSIX char-classes.
936 ;;;                                     Remove trailing whitespace when
937 ;;;                                     adding new linebreak.
938 ;;;                                     Add a level counter to stop shallow.
939 ;;;                                     Indents unprocessed groups rigidly.
940 ;;;  (`cperl-beautify-regexp'): Add an optional count argument to go that
941 ;;;                             many levels deep.
942 ;;;  (`cperl-beautify-level'):  Likewise
943 ;;;  Menu:                      Add new entries to Regexp menu to do one level
944 ;;;  (`cperl-contract-level'):  Was entering an infinite loop
945 ;;;  (`cperl-find-pods-heres'): Typo (double quoting).
946 ;;;                             Was detecting < $file > as FH instead of glob.
947 ;;;                             Support for comments in RExen (except
948 ;;;                             for m#\#comment#x), governed by
949 ;;;                             `cperl-regexp-scan'.
950 ;;;  (`cperl-regexp-scan'):     New customization variable.
951 ;;;  (`cperl-forward-re'):      Improve logic of resetting syntax table.
952
953 ;;;; After 4.23 and: After 4.24:
954 ;;;  (`cperl-contract-levels'): Restore position.
955 ;;;  (`cperl-beautify-level'):  Likewise.
956 ;;;  (`cperl-beautify-regexp'): Likewise.
957 ;;;  (`cperl-commentify'):      Rudimental support for length=1 runs
958 ;;;  (`cperl-find-pods-heres'): Process 1-char long REx comments too /a#/x
959 ;;;                             Processes REx-comments in #-delimited RExen.
960 ;;;                             MAJOR BUG CORRECTED: after a misparse
961 ;;;                               a body of a subroutine could be corrupted!!!
962 ;;;                               One might need to reeval the function body
963 ;;;                               to fix things.  (A similar bug was
964 ;;;                               present in `cperl-indent-region' eons ago.)
965 ;;; To reproduce:
966 ;;   (defun foo () (let ((a '(t))) (insert (format "%s" a)) (setcar a 'BUG) t))
967 ;;   (foo)
968 ;;   (foo)
969 ;;; C-x C-e the above three lines (at end-of-line).  First evaluation
970 ;;; of `foo' inserts (t), second one inserts (BUG) ?!
971 ;;;
972 ;;; In CPerl it was triggered by inserting then deleting `/' at start of
973 ;;;      /  a (?# asdf  {[(}asdf )ef,/;
974
975 ;;;; After 4.25:
976 ;;; (`cperl-commentify'):       Was recognizing length=2 "strings" as length=1.
977 ;;; (`imenu-example--create-perl-index'):
978 ;;;                             Was not enforcing syntaxification-to-the-end.
979 ;;; (`cperl-invert-if-unless'): Allow `for', `foreach'.
980 ;;; (`cperl-find-pods-heres'):  Quote `cperl-nonoverridable-face'.
981 ;;;                             Mark qw(), m()x as indentable.
982 ;;; (`cperl-init-faces'):       Highlight `sysopen' too.
983 ;;;                             Highlight $var in `for my $var' too.
984 ;;; (`cperl-invert-if-unless'): Was leaving whitespace at end.
985 ;;; (`cperl-linefeed'):         Was splitting $var{$foo} if point after `{'.
986 ;;; (`cperl-calculate-indent'): Remove old commented out code.
987 ;;;                             Support (primitive) indentation of qw(), m()x.
988
989
990 ;;;; After 4.26:
991 ;;; (`cperl-problems'):         Mention `fill-paragraph' on comment. \"" and
992 ;;;                             q [] with intervening newlines.
993 ;;; (`cperl-autoindent-on-semi'):       New customization variable.
994 ;;; (`cperl-electric-semi'):    Use `cperl-autoindent-on-semi'.
995 ;;; (`cperl-tips'):             Mention how to make CPerl the default mode.
996 ;;; (`cperl-mode'):             Support `outline-minor-mode'
997 ;;;                             (Thanks to Mark A. Hershberger).
998 ;;; (`cperl-outline-level'):    New function.
999 ;;; (`cperl-highlight-variables-indiscriminately'):     New customization var.
1000 ;;; (`cperl-init-faces'):       Use `cperl-highlight-variables-indiscriminately'.
1001 ;;;                             (Thanks to Sean Kamath <kamath@pogo.wv.tek.com>).
1002 ;;; (`cperl-after-block-p'):    Support CHECK and INIT.
1003 ;;; (`cperl-init-faces'):       Likewise and "our".
1004 ;;;                             (Thanks to Doug MacEachern <dougm@covalent.net>).
1005 ;;; (`cperl-short-docs'):       Likewise and "our".
1006
1007
1008 ;;;; After 4.27:
1009 ;;; (`cperl-find-pods-heres'):  Recognize \"" as a string.
1010 ;;;                             Mark whitespace and comments between q and []
1011 ;;;                               as `syntax-type' => `prestring'.
1012 ;;;                             Allow whitespace between << and "FOO".
1013 ;;; (`cperl-problems'):         Remove \"" and q [] with intervening newlines.
1014 ;;;                             Mention multiple <<EOF as unsupported.
1015 ;;; (`cperl-highlight-variables-indiscriminately'):     Doc misprint fixed.
1016 ;;; (`cperl-indent-parens-as-block'):   New configuration variable.
1017 ;;; (`cperl-calculate-indent'): Merge cases of indenting non-BLOCK groups.
1018 ;;;                             Use `cperl-indent-parens-as-block'.
1019 ;;; (`cperl-find-pods-heres'):  Test for =cut without empty line instead of
1020 ;;;                             complaining about no =cut.
1021 ;;; (`cperl-electric-pod'):     Change the REx for POD from "\n\n=" to "^\n=".
1022 ;;; (`cperl-find-pods-heres'):  Likewise.
1023 ;;; (`cperl-electric-pod'):     Change `forward-sexp' to `forward-word':
1024 ;;;                             POD could've been marked as comment already.
1025 ;;; (`cperl-unwind-to-safe'):   Unwind before start of POD too.
1026
1027 ;;;; After 4.28:
1028 ;;; (`cperl-forward-re'):       Throw an error at proper moment REx unfinished.
1029
1030 ;;;; After 4.29:
1031 ;;; (`x-color-defined-p'):      Make an extra case to peacify the warning.
1032 ;;; Toplevel:                   `defvar' to peacify the warnings.
1033 ;;; (`cperl-find-pods-heres'):  Could access `font-lock-comment-face' in -nw.
1034 ;;;;                            No -nw-compile time warnings now.
1035 ;;; (`cperl-find-tags'):        TAGS file had too short substring-to-search.
1036 ;;;                             Be less verbose in non-interactive mode
1037 ;;; (`imenu-example--create-perl-index'):       Set index-marker after name
1038 ;;; (`cperl-outline-regexp'):   New variable.
1039 ;;; (`cperl-outline-level'):    Made compatible with `cperl-outline-regexp'.
1040 ;;; (`cperl-mode'):             Made use `cperl-outline-regexp'.
1041
1042 ;;;; After 4.30:
1043 ;;; (`cperl-find-pods-heres'):  =cut the last thing, no blank line, was error.
1044 ;;; (`cperl-outline-level'):    Make start-of-file same level as `package'.
1045
1046 ;;;; After 4.31:
1047 ;;; (`cperl-electric-pod'):     `head1' and `over' electric only if empty.
1048 ;;; (`cperl-unreadable-ok'):    New variable.
1049 ;;; (`cperl-find-tags'):        Use `cperl-unreadable-ok', do not fail
1050 ;;;                             on an unreadable file
1051 ;;; (`cperl-write-tags'):       Use `cperl-unreadable-ok', do not fail
1052 ;;;                             on an unreadable directory
1053
1054 ;;;; After 4.32:
1055 ;;;  Syncronized with v1.60 from Emacs 21.3.
1056 ;;;  Mostly docstring and formatting changes, and:
1057
1058 ;;;  (`cperl-noscan-files-regexp'): Do not scan CVS subdirs
1059 ;;;  (`cperl-problems'):        Note that newer XEmacsen may syntaxify too
1060 ;;;  (`imenu-example--create-perl-index'):
1061 ;;;                             Renamed to `cperl-imenu--create-perl-index'
1062 ;;;  (`cperl-mode'):            Replace `make-variable-buffer-local' by `make-local-variable'
1063 ;;;  (`cperl-setup-tmp-buf'):   Likewise
1064 ;;;  (`cperl-fix-line-spacing'): Fix a misprint of "t" for "\t"
1065 ;;;  (`cperl-next-bad-style'):  Fix misprints in character literals
1066
1067 ;;;; After 4.33:
1068 ;;;  (`cperl-font-lock-keywords'): +etc: Aliased to perl-font-lock-keywords.
1069
1070 ;;;; After 4.34:
1071 ;;;  Further updates of whitespace and spelling w.r.t. RMS version.
1072 ;;;  (`cperl-font-lock-keywords'): +etc: Avoid warnings when aliasing.
1073 ;;;  (`cperl-mode'):            Use `normal-auto-fill-function' if present.
1074 ;;;  (`cperl-use-major-mode'):  New variable
1075 ;;;  (`cperl-can-font-lock'):   New variable; replaces `window-system'
1076 ;;;  (`cperl-tags-hier-init'):  use `display-popup-menus-p' (if present)
1077 ;;;                             to choose `x-popup-menu' vs `tmm-prompt'
1078
1079 ;;;; 4.35 has the following differences from version 1.40+ of RMS Emacs:
1080
1081 ;;; New variables `cperl-use-major-mode', `cperl-can-font-lock';
1082 ;;; `cperl-use-major-mode' is (effectively) 'cperl-mode in RMS.
1083 ;;; `cperl-under-as-char'  is nil in RMS.
1084 ;;; Minor differences in docstrings, and `cperl-non-problems'.
1085 ;;; Backward compatibility addressed: (`); (function (lambda ...)); font-lock;
1086 ;;; (:italic t bold t) vs (:slant italic :weight bold) in faces;
1087 ;;; `normal-auto-fill-function'.
1088 ;;; RMS version has wrong logic in `cperl-calculate-indent': $a = { } is
1089 ;;; wrongly indented if the closing brace is on a separate line.
1090 ;;; Different choice of ordering if's for is-x-REx and (eq (char-after b) ?\#)
1091 ;;; in `cperl-find-pods-heres'. [Cosmetic]
1092
1093 ;;;; After 4.35:
1094 ;;;  (`cperl-find-pods-heres'): If no end of HERE-doc found, mark to the end
1095 ;;;                             of buffer.  This enables recognition of end
1096 ;;;                             of HERE-doc "as one types".
1097 ;;;                             Require "\n" after trailing tag of HERE-doc.
1098 ;;;                             \( made non-quoting outside of string/comment
1099 ;;;                             (gdj-contributed).
1100 ;;;                             Likewise for \$.
1101 ;;;                             Remove `here-doc-group' text property at start
1102 ;;;                             (makes this property reliable).
1103 ;;;                             Text property `first-format-line' ==> t.
1104 ;;;                             Do not recognize $opt_s and $opt::s as s///.
1105 ;;;  (`cperl-perldoc'):         Use case-sensitive search (contributed).
1106 ;;;  (`cperl-fix-line-spacing'): Allow "_" in $vars of foreach etc. when
1107 ;;;                             underscore isn't a word char (gdj-contributed).
1108 ;;;  (`defun-prompt-regexp'):   Allow prototypes.
1109 ;;;  (`cperl-vc-header-alist'): Extract numeric version from the Id.
1110 ;;;  Toplevel:                  Put toggle-autohelp into the mode menu.
1111 ;;;                             Better docs for toggle/set/unset autohelp.
1112 ;;;  (`cperl-electric-backspace-untabify'): New customization variable
1113 ;;;  (`cperl-after-expr-p'):    Works after here-docs, formats, and PODs too
1114 ;;;                             (affects many electric constructs).
1115 ;;;  (`cperl-calculate-indent'): Takes into account `first-format-line' ==>
1116 ;;;                             works after format.
1117 ;;;  (`cperl-short-docs'):      Make it work with ... too.
1118 ;;;                             "array context" ==> "list context"
1119 ;;;  (`cperl-electric-keyword'): make $if (etc: "$@%&*") non-electric
1120 ;;;                             '(' after keyword would insert a doubled paren
1121 ;;;  (`cperl-electric-paren'):  documented affected by `cperl-electric-parens'
1122 ;;;  (`cperl-electric-rparen'): Likewise
1123 ;;;  (`cperl-build-manpage'):   New function by Nick Roberts
1124 ;;;  (`cperl-perldoc'):         Make it work in XEmacs too
1125
1126 ;;;; After 4.36:
1127 ;;;  (`cperl-find-pods-heres'): Recognize s => 1 and {s} (as a key or varname),
1128 ;;;                             { s:: } and { s::bar::baz } as varnames.
1129 ;;;  (`cperl-after-expr-p'):    Updates syntaxification before checks
1130 ;;;  (`cperl-calculate-indent'): Likewise
1131 ;;;                             Fix wrong indent of blocks starting with POD
1132 ;;;  (`cperl-after-block-p'):   Optional argument for checking for a pre-block
1133 ;;;                             Recognize `continue' blocks too.
1134 ;;;  (`cperl-electric-brace'):  use `cperl-after-block-p' for detection;
1135 ;;;                             Now works for else/continue/sub blocks
1136 ;;;  (`cperl-short-docs'):      Minor edits; make messages fit 80-column screen
1137
1138 ;;;; After 5.0:
1139 ;;;  `cperl-add-tags-recurse-noxs-fullpath': new function (for -batch mode)
1140
1141 ;;;; After 5.1:
1142 ;;;;;; Major edit.  Summary of most visible changes:
1143
1144 ;;;;;; a) Multiple <<HERE per line allowed.
1145 ;;;;;; b) Handles multiline subroutine declaration headers (with comments).
1146 ;;;;;;    (The exception is `cperl-etags' - but it is not used in the rest
1147 ;;;;;;    of the mode.)
1148 ;;;;;; c) Fontifies multiline my/our declarations (even with comments,
1149 ;;;;;;    and with legacy `font-lock').
1150 ;;;;;; d) Major speedup of syntaxification, both immediate and postponed
1151 ;;;;;;    (3.5x to 15x [for different CPUs and versions of Emacs] on the
1152 ;;;;;;    huge real-life document I tested).
1153 ;;;;;; e) New bindings, edits to imenu.
1154 ;;;;;; f) "_" is made into word-char during fontification/syntaxification;
1155 ;;;;;;    some attempts to recognize non-word "_" during other operations too.
1156 ;;;;;; g) Detect bug in Emacs with `looking-at' inside `narrow' and bulk out.
1157 ;;;;;; h) autoload some more perldoc-related stuff
1158 ;;;;;; i) Some new convenience features: ISpell POD/HEREDOCs, narrow-to-HEREDOC
1159 ;;;;;; j) Attempt to incorporate XEmacs edits which reached me
1160
1161 ;;;; Fine-grained changelog:
1162 ;;; `cperl-hook-after-change':  New configuration variable
1163 ;;; `cperl-vc-sccs-header':     Likewise
1164 ;;; `cperl-vc-sccs-header':     Likewise
1165 ;;; `cperl-vc-header-alist':    Default via two preceding variables
1166 ;;; `cperl-invalid-face':       Remove double quoting under XEmacs
1167 ;;;                                     (still needed under 21.2)
1168 ;;; `cperl-tips':               Update URLs for resources
1169 ;;; `cperl-problems':           Likewise
1170 ;;; `cperl-praise':             Mention new features
1171 ;;; New C-c key bindings:       for `cperl-find-bad-style',
1172 ;;;     `cperl-pod-spell', `cperl-here-doc-spell', `cperl-narrow-to-here-doc',
1173 ;;;     `cperl-perdoc', `cperl-perldoc-at-point'
1174 ;;; CPerl Mode menu changes:    "Fix style by spaces", "Imenu on Perl Info"
1175 ;;;     moved, new submenu of Tools with Ispell entries and narrowing.
1176 ;;; `cperl-after-sub-regexp':   New defsubst
1177 ;;; `cperl-imenu--function-name-regexp-perl': Use `cperl-after-sub-regexp',
1178 ;;;                             Allows heads up to head4
1179 ;;;                             Allow "package;"
1180 ;;; `defun-prompt-regexp':      Use `cperl-after-sub-regexp',
1181 ;;; `paren-backwards-message':  ??? Something for XEmacs???
1182 ;;; `cperl-mode':               Never auto-switch abbrev-mode off
1183 ;;;                             Try to allow '_' be non-word char
1184 ;;;                             Do not use `font-lock-unfontify-region-function' on XEmacs
1185 ;;;                             Reset syntax cache on mode start
1186 ;;;                             Support multiline facification (even
1187 ;;;                                     on legacy `font-lock')
1188 ;;; `cperl-facemenu-add-face-function': ??? Some contributed code ???
1189 ;;; `cperl-after-change-function':      Since `font-lock' and `lazy-lock'
1190 ;;;         refuse to inform us whether the fontification is due to lazy
1191 ;;;         calling or due to edit to a buffer, install our own hook
1192 ;;;         (controlled by `cperl-hook-after-change')
1193 ;;; `cperl-electric-pod':       =cut may have been recognized as start
1194 ;;; `cperl-block-p':            Moved, updated for attributes
1195 ;;; `cperl-calculate-indent':   Try to allow '_' be non-word char
1196 ;;;                             Support subs with attributes
1197 ;;; `cperl-where-am-i':         Queit (?) a warning
1198 ;;; `cperl-cached-syntax-table' New function
1199 ;;; `cperl-forward-re':         Use `cperl-cached-syntax-table'
1200 ;;; `cperl-unwind-to-safe':     Recognize `syntax-type' property
1201 ;;;                                     changing in a middle of line
1202 ;;; `cperl-find-sub-attrs':     New function
1203 ;;; `cperl-find-pods-heres':    Allow many <<EOP per line
1204 ;;;                             Allow subs with attributes
1205 ;;;                             Major speedups (3.5x..15x on a real-life
1206 ;;;                                     test file nph-proxy.pl)
1207 ;;;                             Recognize "extproc " (OS/2)
1208 ;;;                                     case-folded and only at start
1209 ;;;                             /x on s///x with empty replacement was
1210 ;;;                                     not recognized
1211 ;;;                             Better comments
1212 ;;; `cperl-after-block-p':      Remarks on diff with `cperl-block-p'
1213 ;;;                             Allow subs with attributes, labels
1214 ;;;                             Do not confuse "else::foo" with "else"
1215 ;;;                             Minor optimizations...
1216 ;;; `cperl-after-expr-p':       Try to allow '_' be non-word char
1217 ;;; `cperl-fill-paragraph':     Try to detect a major bug in Emacs
1218 ;;;         with `looking-at' inside `narrow' and bulk out if found
1219 ;;; `cperl-imenu--create-perl-index':   Updates for new
1220 ;;;         `cperl-imenu--function-name-regexp-perl'
1221 ;;; `cperl-outline-level':      Likewise
1222 ;;; `cperl-init-faces':         Allow multiline subroutine headers
1223 ;;;         and my/our declarations, and ones with comments
1224 ;;;                             Allow subroutine attributes
1225 ;;; `cperl-imenu-on-info':      Better docstring.
1226 ;;; `cperl-etags'               Rudimentary support for attributes
1227 ;;;                             Support for packages and "package;"
1228 ;;; `cperl-add-tags-recurse-noxs':      Better (?) docstring
1229 ;;; `cperl-add-tags-recurse-noxs-fullpath': Likewise
1230 ;;; `cperl-tags-hier-init':     Misprint for `fboundp' fixed
1231 ;;; `cperl-not-bad-style-regexp':       Try to allow '_' be non-word char
1232 ;;; `cperl-perldoc':            Add autoload
1233 ;;; `cperl-perldoc-at-point':   Likewise
1234 ;;; `cperl-here-doc-spell':     New function
1235 ;;; `cperl-pod-spell':          Likewise
1236 ;;; `cperl-map-pods-heres':     Likewise
1237 ;;; `cperl-get-here-doc-region':        Likewise
1238 ;;; `cperl-font-lock-fontify-region-function': Likewise (backward compatibility
1239 ;;;                                             for legacy `font-lock')
1240 ;;; `cperl-font-lock-unfontify-region-function': Fix style
1241 ;;; `cperl-fontify-syntaxically':       Recognize and optimize away
1242 ;;;         deferred calls with no-change.  Governed by `cperl-hook-after-change'
1243 ;;; `cperl-fontify-update':     Recognize that syntaxification region
1244 ;;;         can be larger than fontification one.
1245 ;;;         XXXX we leave `cperl-postpone' property, so this is quadratic...
1246 ;;; `cperl-fontify-update-bad': Temporary placeholder until
1247 ;;;         it is clear how to implement `cperl-fontify-update'.
1248 ;;; `cperl-time-fontification': New function
1249 ;;; `attrib-group':             New text attribute
1250 ;;; `multiline':                New value: `syntax-type' text attribute
1251
1252 ;;;; After 5.2:
1253 ;;; `cperl-emulate-lazy-lock':  New function
1254 ;;; `cperl-fontify-syntaxically': Would skip large regions
1255 ;;; Add `cperl-time-fontification', `cperl-emulate-lazy-lock' to menu
1256 ;;; Some globals were declared, but uninitialized
1257
1258 ;;;; After 5.3, 5.4:
1259 ;;; `cperl-facemenu-add-face-function': Add docs, fix U<>
1260 ;;; Copyright message updated.
1261 ;;; `cperl-init-faces':         Work around a bug in `font-lock'. May slow
1262 ;;;                                     facification down a bit.
1263 ;;;                             Misprint for my|our|local for old `font-lock'
1264 ;;;                             "our" was not fontified same as "my|local"
1265 ;;;                             Highlight variables after "my" etc even in
1266 ;;;                                     a middle of an expression
1267 ;;;                             Do not facify multiple variables after my etc
1268 ;;;                                     unless parentheses are present
1269
1270 ;;; After 5.5, 5.6
1271 ;;; `cperl-fontify-syntaxically': after-change hook could reset
1272 ;;;     `cperl-syntax-done-to' to a middle of line; unwind to BOL.
1273
1274 ;;; After 5.7:
1275 ;;; `cperl-init-faces':         Allow highlighting of local ($/)
1276 ;;; `cperl-problems-old-emaxen': New variable (for the purpose of DOCSTRING).
1277 ;;; `cperl-problems':           Remove fixed problems.
1278 ;;; `cperl-find-pods-heres':    Recognize #-comments in m##x too
1279 ;;;                             Recognize charclasses (unless delimiter is \).
1280 ;;; `cperl-fontify-syntaxically': Unwinding to safe was done in wrong order
1281 ;;; `cperl-regexp-scan':        Update docs
1282 ;;; `cperl-beautify-regexp-piece': use information got from regexp scan
1283
1284 ;;; After 5.8:
1285 ;;; Major user visible changes:
1286 ;;; Recognition and fontification of character classes in RExen.
1287 ;;; Variable indentation of RExen according to groups
1288 ;;;
1289 ;;; `cperl-find-pods-heres':    Recognize POSIX classes in REx charclasses
1290 ;;;                             Fontify REx charclasses in variable-name face
1291 ;;;                             Fontify POSIX charclasses in "type" face
1292 ;;;                             Fontify unmatched "]" in function-name face
1293 ;;;                             Mark first-char of HERE-doc as `front-sticky'
1294 ;;;                             Reset `front-sticky' property when needed
1295 ;;; `cperl-calculate-indent':   Indents //x -RExen accordning to parens level
1296 ;;; `cperl-to-comment-or-eol':  Recognize ends of `syntax-type' constructs
1297 ;;; `cperl-backward-to-noncomment': Recognize stringy `syntax-type' constructs
1298 ;;;                             Support `narrow'ed buffers.
1299 ;;; `cperl-praise':             Remove a reservation
1300 ;;; `cperl-make-indent':        New function
1301 ;;; `cperl-indent-for-comment': Use `cperl-make-indent'
1302 ;;; `cperl-indent-line':        Likewise
1303 ;;; `cperl-lineup':             Likewise
1304 ;;; `cperl-beautify-regexp-piece': Likewise
1305 ;;; `cperl-contract-level':     Likewise
1306 ;;; `cperl-toggle-set-debug-unwind': New function
1307 ;;;                             New menu entry for this
1308 ;;; `fill-paragraph-function':  Use when `boundp'
1309 ;;; `cperl-calculate-indent':   Take into account groups when indenting RExen
1310 ;;; `cperl-to-comment-or-eol':  Recognize # which end a string
1311 ;;; `cperl-modify-syntax-type': Make only syntax-table property non-sticky
1312 ;;; `cperl-fill-paragraph':     Return t: needed for `fill-paragraph-function'
1313 ;;; `cperl-fontify-syntaxically': More clear debugging message
1314 ;;; `cperl-pod2man-build-command': XEmacs portability: check `Man-filter-list'
1315 ;;; `cperl-init-faces':         More complicated highlight even on XEmacs (new)
1316 ;;; Merge cosmetic changes from XEmacs
1317
1318 ;;; After 5.9:
1319 ;;; `cperl-1+':                 Moved to before the first use
1320 ;;; `cperl-1-':                 Likewise
1321
1322 ;;; After 5.10:
1323
1324 ;;; This code may lock Emacs hard!!!  Use on your own risk!
1325
1326 ;;; `cperl-font-locking':       New internal variable
1327 ;;; `cperl-beginning-of-property': New function
1328 ;;; `cperl-calculate-indent':   Use `cperl-beginning-of-property'
1329 ;;;     instead of `previous-single-property-change'
1330 ;;; `cperl-unwind-to-safe':     Likewise
1331 ;;; `cperl-after-expr-p':       Likewise
1332 ;;; `cperl-get-here-doc-region': Likewise
1333 ;;; `cperl-font-lock-fontify-region-function': Likewise
1334 ;;; `cperl-to-comment-or-eol':  Do not call `cperl-update-syntaxification'
1335 ;;;                                     recursively
1336 ;;;                             Bound `next-single-property-change'
1337 ;;;                                     via `point-max'
1338 ;;; `cperl-unwind-to-safe':     Bound likewise
1339 ;;; `cperl-font-lock-fontify-region-function': Likewise
1340 ;;; `cperl-find-pods-heres':    Mark as recursive for `cperl-to-comment-or-eol'
1341 ;;;                             Initialization of
1342 ;;;     `cperl-font-lock-multiline-start' could be missed if the "main"
1343 ;;;     fontification did not run due to the keyword being already fontified.
1344 ;;; `cperl-pod-spell':          Return t from do-one-chunk function
1345 ;;; `cperl-map-pods-heres':     Stop when the worker returns nil
1346 ;;;                             Call `cperl-update-syntaxification'
1347 ;;; `cperl-get-here-doc-region': Call `cperl-update-syntaxification'
1348 ;;; `cperl-get-here-doc-delim': Remove unused function
1349
1350 ;;; After 5.11:
1351
1352 ;;;  The possible lockup of Emacs (introduced in 5.10) fixed
1353
1354 ;;; `cperl-unwind-to-safe':     `cperl-beginning-of-property' won't return nil
1355 ;;; `cperl-syntaxify-for-menu': New customization variable
1356 ;;; `cperl-select-this-pod-or-here-doc': New function
1357 ;;; `cperl-get-here-doc-region': Extra argument.
1358 ;;;                             Do not adjust pos by 1.
1359
1360 ;;; New menu entries (Perl/Tools): selection of current POD or HERE-DOC section
1361 ;;;                             (Debugging CPerl:) backtrace on fontification
1362
1363 ;;; After 5.12:
1364 ;;; `cperl-cached-syntax-table': use `car-safe'
1365 ;;; `cperl-forward-re':         Remove spurious argument SET-ST
1366 ;;;                             Add documentation
1367 ;;; `cperl-forward-group-in-re': New function
1368 ;;; `cperl-find-pods-heres':    Find and highlight (?{}) blocks in RExen.
1369 ;;;     (XXXX Temporary (?) hack is to syntax-mark them as comment)
1370
1371 ;;; After 5.13:
1372 ;;; `cperl-string-syntax-table': Make { and } not-grouping
1373 ;;;   (Sometimes they ARE grouping in RExen, but matching them would only
1374 ;;;    confuse in many situations when they are not).
1375 ;;; `beginning-of-buffer':      Replaced two occurences with goto-char...
1376 ;;; `cperl-calculate-indent':   `char-after' could be nil...
1377 ;;; `cperl-find-pods-heres':    REx can start after "[" too
1378 ;;;                             Hightlight (??{}) in RExen too 
1379 ;;; `cperl-maybe-white-and-comment-rex': New constant
1380 ;;; `cperl-white-and-comment-rex': Likewise
1381 ;;;                             XXXX Not very efficient, but hard to make
1382 ;;;                             better while keeping 1 group.
1383
1384 ;;; After 5.13:
1385 ;;; `cperl-find-pods-heres':    $foo << identifier() is not a HERE-DOC
1386 ;;;                             Likewise for 1 << identifier
1387
1388 ;;; After 5.14:
1389 ;;; `cperl-find-pods-heres':    Different logic for $foo .= <<EOF etc
1390 ;;;                             Error-less condition-case could fail
1391 ;;; `cperl-font-lock-fontify-region-function': Likewise
1392 ;;; `cperl-init-faces':         Likewise
1393
1394 ;;; After 5.15:
1395 ;;; `cperl-find-pods-heres':    Support property REx-part2
1396 ;;; `cperl-calculate-indent':   Likewise
1397 ;;;                             Don't special-case REx with non-empty 1st line
1398 ;;; `cperl-find-pods-heres':    In RExen, highlight non-literal backslashes
1399 ;;;                             Invert highlighting of charclasses: 
1400 ;;;                                     now the envelop is highlighted
1401 ;;;                             Highlight many others 0-length builtins
1402 ;;; `cperl-praise':             Mention indenting and highlight in RExen.
1403
1404 ;;; Code:
1405 \f
1406 (if (fboundp 'eval-when-compile)
1407     (eval-when-compile
1408       (condition-case nil
1409           (require 'custom)
1410         (error nil))
1411       (condition-case nil
1412           (require 'man)
1413         (error nil))
1414       (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1415       (defvar cperl-can-font-lock
1416         (or cperl-xemacs-p
1417             (and (boundp 'emacs-major-version)
1418                  (or window-system
1419                      (> emacs-major-version 20)))))
1420       (if cperl-can-font-lock
1421           (require 'font-lock))
1422       (defvar msb-menu-cond)
1423       (defvar gud-perldb-history)
1424       (defvar font-lock-background-mode) ; not in Emacs
1425       (defvar font-lock-display-type)   ; ditto
1426       (or (fboundp 'defgroup)
1427           (defmacro defgroup (name val doc &rest arr)
1428             nil))
1429       (or (fboundp 'custom-declare-variable)
1430           (defmacro defcustom (name val doc &rest arr)
1431             (` (defvar (, name) (, val) (, doc)))))
1432       (or (and (fboundp 'custom-declare-variable)
1433                (string< "19.31" emacs-version)) ;  Checked with 19.30: defface does not work
1434           (defmacro defface (&rest arr)
1435             nil))
1436       ;; Avoid warning (tmp definitions)
1437       (or (fboundp 'x-color-defined-p)
1438           (defmacro x-color-defined-p (col)
1439             (cond ((fboundp 'color-defined-p) (` (color-defined-p (, col))))
1440                   ;; XEmacs >= 19.12
1441                   ((fboundp 'valid-color-name-p) (` (valid-color-name-p (, col))))
1442                   ;; XEmacs 19.11
1443                   ((fboundp 'x-valid-color-name-p) (` (x-valid-color-name-p (, col))))
1444                   (t '(error "Cannot implement color-defined-p")))))
1445       (defmacro cperl-is-face (arg)     ; Takes quoted arg
1446         (cond ((fboundp 'find-face)
1447                (` (find-face (, arg))))
1448               (;;(and (fboundp 'face-list)
1449                ;;       (face-list))
1450                (fboundp 'face-list)
1451                (` (member (, arg) (and (fboundp 'face-list)
1452                                        (face-list)))))
1453               (t
1454                (` (boundp (, arg))))))
1455       (defmacro cperl-make-face (arg descr) ; Takes unquoted arg
1456         (cond ((fboundp 'make-face)
1457                (` (make-face (quote (, arg)))))
1458               (t
1459                (` (defvar (, arg) (quote (, arg)) (, descr))))))
1460       (defmacro cperl-force-face (arg descr) ; Takes unquoted arg
1461         (` (progn
1462              (or (cperl-is-face (quote (, arg)))
1463                  (cperl-make-face (, arg) (, descr)))
1464              (or (boundp (quote (, arg))) ; We use unquoted variants too
1465                  (defvar (, arg) (quote (, arg)) (, descr))))))
1466       (if cperl-xemacs-p
1467           (defmacro cperl-etags-snarf-tag (file line)
1468             (` (progn
1469                  (beginning-of-line 2)
1470                  (list (, file) (, line)))))
1471         (defmacro cperl-etags-snarf-tag (file line)
1472           (` (etags-snarf-tag))))
1473       (if cperl-xemacs-p
1474           (defmacro cperl-etags-goto-tag-location (elt)
1475             (`;;(progn
1476              ;; (switch-to-buffer (get-file-buffer (elt (, elt) 0)))
1477              ;; (set-buffer (get-file-buffer (elt (, elt) 0)))
1478              ;; Probably will not work due to some save-excursion???
1479              ;; Or save-file-position?
1480              ;; (message "Did I get to line %s?" (elt (, elt) 1))
1481              (goto-line (string-to-int (elt (, elt) 1)))))
1482         ;;)
1483         (defmacro cperl-etags-goto-tag-location (elt)
1484           (` (etags-goto-tag-location (, elt)))))))
1485
1486 (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1487
1488 (defvar cperl-can-font-lock
1489   (or cperl-xemacs-p
1490       (and (boundp 'emacs-major-version)
1491            (or window-system
1492                (> emacs-major-version 20)))))
1493
1494 (condition-case nil
1495     (require 'custom)
1496   (error nil))                          ; Already fixed by eval-when-compile
1497
1498 (defun cperl-choose-color (&rest list)
1499   (let (answer)
1500     (while list
1501       (or answer
1502           (if (or (x-color-defined-p (car list))
1503                   (null (cdr list)))
1504               (setq answer (car list))))
1505       (setq list (cdr list)))
1506     answer))
1507
1508 \f
1509 (defgroup cperl nil
1510   "Major mode for editing Perl code."
1511   :prefix "cperl-"
1512   :group 'languages)
1513
1514 (defgroup cperl-indentation-details nil
1515   "Indentation."
1516   :prefix "cperl-"
1517   :group 'cperl)
1518
1519 (defgroup cperl-affected-by-hairy nil
1520   "Variables affected by `cperl-hairy'."
1521   :prefix "cperl-"
1522   :group 'cperl)
1523
1524 (defgroup cperl-autoinsert-details nil
1525   "Auto-insert tuneup."
1526   :prefix "cperl-"
1527   :group 'cperl)
1528
1529 (defgroup cperl-faces nil
1530   "Fontification colors."
1531   :prefix "cperl-"
1532   :group 'cperl)
1533
1534 (defgroup cperl-speed nil
1535   "Speed vs. validity tuneup."
1536   :prefix "cperl-"
1537   :group 'cperl)
1538
1539 (defgroup cperl-help-system nil
1540   "Help system tuneup."
1541   :prefix "cperl-"
1542   :group 'cperl)
1543
1544 \f
1545 (defcustom cperl-extra-newline-before-brace nil
1546   "*Non-nil means that if, elsif, while, until, else, for, foreach
1547 and do constructs look like:
1548
1549         if ()
1550         {
1551         }
1552
1553 instead of:
1554
1555         if () {
1556         }"
1557   :type 'boolean
1558   :group 'cperl-autoinsert-details)
1559
1560 (defcustom cperl-extra-newline-before-brace-multiline
1561   cperl-extra-newline-before-brace
1562   "*Non-nil means the same as `cperl-extra-newline-before-brace', but
1563 for constructs with multiline if/unless/while/until/for/foreach condition."
1564   :type 'boolean
1565   :group 'cperl-autoinsert-details)
1566
1567 (defcustom cperl-indent-level 2
1568   "*Indentation of CPerl statements with respect to containing block."
1569   :type 'integer
1570   :group 'cperl-indentation-details)
1571
1572 (defcustom cperl-lineup-step nil
1573   "*`cperl-lineup' will always lineup at multiple of this number.
1574 If nil, the value of `cperl-indent-level' will be used."
1575   :type '(choice (const nil) integer)
1576   :group 'cperl-indentation-details)
1577
1578 (defcustom cperl-brace-imaginary-offset 0
1579   "*Imagined indentation of a Perl open brace that actually follows a statement.
1580 An open brace following other text is treated as if it were this far
1581 to the right of the start of its line."
1582   :type 'integer
1583   :group 'cperl-indentation-details)
1584
1585 (defcustom cperl-brace-offset 0
1586   "*Extra indentation for braces, compared with other text in same context."
1587   :type 'integer
1588   :group 'cperl-indentation-details)
1589 (defcustom cperl-label-offset -2
1590   "*Offset of CPerl label lines relative to usual indentation."
1591   :type 'integer
1592   :group 'cperl-indentation-details)
1593 (defcustom cperl-min-label-indent 1
1594   "*Minimal offset of CPerl label lines."
1595   :type 'integer
1596   :group 'cperl-indentation-details)
1597 (defcustom cperl-continued-statement-offset 2
1598   "*Extra indent for lines not starting new statements."
1599   :type 'integer
1600   :group 'cperl-indentation-details)
1601 (defcustom cperl-continued-brace-offset 0
1602   "*Extra indent for substatements that start with open-braces.
1603 This is in addition to cperl-continued-statement-offset."
1604   :type 'integer
1605   :group 'cperl-indentation-details)
1606 (defcustom cperl-close-paren-offset -1
1607   "*Extra indent for substatements that start with close-parenthesis."
1608   :type 'integer
1609   :group 'cperl-indentation-details)
1610
1611 (defcustom cperl-auto-newline nil
1612   "*Non-nil means automatically newline before and after braces,
1613 and after colons and semicolons, inserted in CPerl code.  The following
1614 \\[cperl-electric-backspace] will remove the inserted whitespace.
1615 Insertion after colons requires both this variable and
1616 `cperl-auto-newline-after-colon' set."
1617   :type 'boolean
1618   :group 'cperl-autoinsert-details)
1619
1620 (defcustom cperl-autoindent-on-semi nil
1621   "*Non-nil means automatically indent after insertion of (semi)colon.
1622 Active if `cperl-auto-newline' is false."
1623   :type 'boolean
1624   :group 'cperl-autoinsert-details)
1625
1626 (defcustom cperl-auto-newline-after-colon nil
1627   "*Non-nil means automatically newline even after colons.
1628 Subject to `cperl-auto-newline' setting."
1629   :type 'boolean
1630   :group 'cperl-autoinsert-details)
1631
1632 (defcustom cperl-tab-always-indent t
1633   "*Non-nil means TAB in CPerl mode should always reindent the current line,
1634 regardless of where in the line point is when the TAB command is used."
1635   :type 'boolean
1636   :group 'cperl-indentation-details)
1637
1638 (defcustom cperl-font-lock nil
1639   "*Non-nil (and non-null) means CPerl buffers will use `font-lock-mode'.
1640 Can be overwritten by `cperl-hairy' if nil."
1641   :type '(choice (const null) boolean)
1642   :group 'cperl-affected-by-hairy)
1643
1644 (defcustom cperl-electric-lbrace-space nil
1645   "*Non-nil (and non-null) means { after $ should be preceded by ` '.
1646 Can be overwritten by `cperl-hairy' if nil."
1647   :type '(choice (const null) boolean)
1648   :group 'cperl-affected-by-hairy)
1649
1650 (defcustom cperl-electric-parens-string "({[]})<"
1651   "*String of parentheses that should be electric in CPerl.
1652 Closing ones are electric only if the region is highlighted."
1653   :type 'string
1654   :group 'cperl-affected-by-hairy)
1655
1656 (defcustom cperl-electric-parens nil
1657   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
1658 Can be overwritten by `cperl-hairy' if nil."
1659   :type '(choice (const null) boolean)
1660   :group 'cperl-affected-by-hairy)
1661
1662 (defvar zmacs-regions)                  ; Avoid warning
1663
1664 (defcustom cperl-electric-parens-mark
1665   (and window-system
1666        (or (and (boundp 'transient-mark-mode) ; For Emacs
1667                 transient-mark-mode)
1668            (and (boundp 'zmacs-regions) ; For XEmacs
1669                 zmacs-regions)))
1670   "*Not-nil means that electric parens look for active mark.
1671 Default is yes if there is visual feedback on mark."
1672   :type 'boolean
1673   :group 'cperl-autoinsert-details)
1674
1675 (defcustom cperl-electric-linefeed nil
1676   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
1677 In any case these two mean plain and hairy linefeeds together.
1678 Can be overwritten by `cperl-hairy' if nil."
1679   :type '(choice (const null) boolean)
1680   :group 'cperl-affected-by-hairy)
1681
1682 (defcustom cperl-electric-keywords nil
1683   "*Not-nil (and non-null) means keywords are electric in CPerl.
1684 Can be overwritten by `cperl-hairy' if nil."
1685   :type '(choice (const null) boolean)
1686   :group 'cperl-affected-by-hairy)
1687
1688 (defcustom cperl-electric-backspace-untabify t
1689   "*Not-nil means electric-backspace will untabify in CPerl."
1690   :type 'boolean
1691   :group 'cperl-autoinsert-details)
1692
1693 (defcustom cperl-hairy nil
1694   "*Not-nil means most of the bells and whistles are enabled in CPerl.
1695 Affects: `cperl-font-lock', `cperl-electric-lbrace-space',
1696 `cperl-electric-parens', `cperl-electric-linefeed', `cperl-electric-keywords',
1697 `cperl-info-on-command-no-prompt', `cperl-clobber-lisp-bindings',
1698 `cperl-lazy-help-time'."
1699   :type 'boolean
1700   :group 'cperl-affected-by-hairy)
1701
1702 (defcustom cperl-comment-column 32
1703   "*Column to put comments in CPerl (use \\[cperl-indent] to lineup with code)."
1704   :type 'integer
1705   :group 'cperl-indentation-details)
1706
1707 (defcustom cperl-vc-sccs-header '("($sccs) = ('%W\%' =~ /(\\d+(\\.\\d+)+)/) ;")
1708   "*Special version of `vc-sccs-header' that is used in CPerl mode buffers."
1709   :type '(repeat string)
1710   :group 'cperl)
1711
1712 (defcustom cperl-vc-rcs-header '("($rcs) = (' $Id\$ ' =~ /(\\d+(\\.\\d+)+)/);")
1713   "*Special version of `vc-rcs-header' that is used in CPerl mode buffers."
1714   :type '(repeat string)
1715      :group 'cperl)
1716
1717 ;; This became obsolete...
1718 (defcustom cperl-vc-header-alist '()
1719   "*What to use as `vc-header-alist' in CPerl.
1720 Obsolete, with newer Emacsen use `cperl-vc-rcs-header' or
1721 `cperl-vc-sccs-header' instead.  If this list is empty, `vc-header-alist'
1722 will be reconstructed basing on these two variables."
1723   :type '(repeat (list symbol string))
1724   :group 'cperl)
1725
1726 (defcustom cperl-clobber-mode-lists
1727   (not
1728    (and
1729     (boundp 'interpreter-mode-alist)
1730     (assoc "miniperl" interpreter-mode-alist)
1731     (assoc "\\.\\([pP][Llm]\\|al\\)$" auto-mode-alist)))
1732   "*Whether to install us into `interpreter-' and `extension' mode lists."
1733   :type 'boolean
1734   :group 'cperl)
1735
1736 (defcustom cperl-info-on-command-no-prompt nil
1737   "*Not-nil (and non-null) means not to prompt on C-h f.
1738 The opposite behaviour is always available if prefixed with C-c.
1739 Can be overwritten by `cperl-hairy' if nil."
1740   :type '(choice (const null) boolean)
1741   :group 'cperl-affected-by-hairy)
1742
1743 (defcustom cperl-clobber-lisp-bindings nil
1744   "*Not-nil (and non-null) means not overwrite C-h f.
1745 The function is available on \\[cperl-info-on-command], \\[cperl-get-help].
1746 Can be overwritten by `cperl-hairy' if nil."
1747   :type '(choice (const null) boolean)
1748   :group 'cperl-affected-by-hairy)
1749
1750 (defcustom cperl-lazy-help-time nil
1751   "*Not-nil (and non-null) means to show lazy help after given idle time.
1752 Can be overwritten by `cperl-hairy' to be 5 sec if nil."
1753   :type '(choice (const null) (const nil) integer)
1754   :group 'cperl-affected-by-hairy)
1755
1756 (defcustom cperl-pod-face 'font-lock-comment-face
1757   "*The result of evaluation of this expression is used for POD highlighting."
1758   :type 'face
1759   :group 'cperl-faces)
1760
1761 (defcustom cperl-pod-head-face 'font-lock-variable-name-face
1762   "*The result of evaluation of this expression is used for POD highlighting.
1763 Font for POD headers."
1764   :type 'face
1765   :group 'cperl-faces)
1766
1767 (defcustom cperl-here-face 'font-lock-string-face
1768   "*The result of evaluation of this expression is used for here-docs highlighting."
1769   :type 'face
1770   :group 'cperl-faces)
1771
1772 ;;; Some double-evaluation happened with font-locks...  Needed with 21.2...
1773 (defvar cperl-singly-quote-face cperl-xemacs-p)
1774
1775 (defcustom cperl-invalid-face           ; Does not customize with '' on XEmacs
1776   (if cperl-singly-quote-face
1777       'underline ''underline) ; On older Emacsen was evaluated by `font-lock'
1778   (if cperl-singly-quote-face
1779       "*This face is used for highlighting trailing whitespace."
1780     "*The result of evaluation of this expression highlights trailing whitespace.")
1781   :type 'face
1782   :group 'cperl-faces)
1783
1784 (defcustom cperl-pod-here-fontify '(featurep 'font-lock)
1785   "*Not-nil after evaluation means to highlight POD and here-docs sections."
1786   :type 'boolean
1787   :group 'cperl-faces)
1788
1789 (defcustom cperl-fontify-m-as-s t
1790   "*Not-nil means highlight 1arg regular expressions operators same as 2arg."
1791   :type 'boolean
1792   :group 'cperl-faces)
1793
1794 (defcustom cperl-highlight-variables-indiscriminately nil
1795   "*Non-nil means perform additional highlighting on variables.
1796 Currently only changes how scalar variables are highlighted.
1797 Note that that variable is only read at initialization time for
1798 the variable `perl-font-lock-keywords-2', so changing it after you've
1799 entered CPerl mode the first time will have no effect."
1800   :type 'boolean
1801   :group 'cperl)
1802
1803 (defcustom cperl-pod-here-scan t
1804   "*Not-nil means look for POD and here-docs sections during startup.
1805 You can always make lookup from menu or using \\[cperl-find-pods-heres]."
1806   :type 'boolean
1807   :group 'cperl-speed)
1808
1809 (defcustom cperl-regexp-scan t
1810   "*Not-nil means make marking of regular expression more thorough.
1811 Effective only with `cperl-pod-here-scan'."
1812   :type 'boolean
1813   :group 'cperl-speed)
1814
1815 (defcustom cperl-hook-after-change t
1816   "*Not-nil means install hook to know which regions of buffer are changed.
1817 May significantly speed up delayed fontification.  Changes take effect
1818 after reload."
1819   :type 'boolean
1820   :group 'cperl-speed)
1821
1822 (defcustom cperl-imenu-addback nil
1823   "*Not-nil means add backreferences to generated `imenu's.
1824 May require patched `imenu' and `imenu-go'.  Obsolete."
1825   :type 'boolean
1826   :group 'cperl-help-system)
1827
1828 (defcustom cperl-max-help-size 66
1829   "*Non-nil means shrink-wrapping of info-buffer allowed up to these percents."
1830   :type '(choice integer (const nil))
1831   :group 'cperl-help-system)
1832
1833 (defcustom cperl-shrink-wrap-info-frame t
1834   "*Non-nil means shrink-wrapping of info-buffer-frame allowed."
1835   :type 'boolean
1836   :group 'cperl-help-system)
1837
1838 (defcustom cperl-info-page "perl"
1839   "*Name of the info page containing perl docs.
1840 Older version of this page was called `perl5', newer `perl'."
1841   :type 'string
1842   :group 'cperl-help-system)
1843
1844 (defcustom cperl-use-syntax-table-text-property
1845   (boundp 'parse-sexp-lookup-properties)
1846   "*Non-nil means CPerl sets up and uses `syntax-table' text property."
1847   :type 'boolean
1848   :group 'cperl-speed)
1849
1850 (defcustom cperl-use-syntax-table-text-property-for-tags
1851   cperl-use-syntax-table-text-property
1852   "*Non-nil means: set up and use `syntax-table' text property generating TAGS."
1853   :type 'boolean
1854   :group 'cperl-speed)
1855
1856 (defcustom cperl-scan-files-regexp "\\.\\([pP][Llm]\\|xs\\)$"
1857   "*Regexp to match files to scan when generating TAGS."
1858   :type 'regexp
1859   :group 'cperl)
1860
1861 (defcustom cperl-noscan-files-regexp
1862   "/\\(\\.\\.?\\|SCCS\\|RCS\\|CVS\\|blib\\)$"
1863   "*Regexp to match files/dirs to skip when generating TAGS."
1864   :type 'regexp
1865   :group 'cperl)
1866
1867 (defcustom cperl-regexp-indent-step nil
1868   "*Indentation used when beautifying regexps.
1869 If nil, the value of `cperl-indent-level' will be used."
1870   :type '(choice integer (const nil))
1871   :group 'cperl-indentation-details)
1872
1873 (defcustom cperl-indent-left-aligned-comments t
1874   "*Non-nil means that the comment starting in leftmost column should indent."
1875   :type 'boolean
1876   :group 'cperl-indentation-details)
1877
1878 (defcustom cperl-under-as-char t
1879   "*Non-nil means that the _ (underline) should be treated as word char."
1880   :type 'boolean
1881   :group 'cperl)
1882
1883 (defcustom cperl-extra-perl-args ""
1884   "*Extra arguments to use when starting Perl.
1885 Currently used with `cperl-check-syntax' only."
1886   :type 'string
1887   :group 'cperl)
1888
1889 (defcustom cperl-message-electric-keyword t
1890   "*Non-nil means that the `cperl-electric-keyword' prints a help message."
1891   :type 'boolean
1892   :group 'cperl-help-system)
1893
1894 (defcustom cperl-indent-region-fix-constructs 1
1895   "*Amount of space to insert between `}' and `else' or `elsif'
1896 in `cperl-indent-region'.  Set to nil to leave as is.  Values other
1897 than 1 and nil will probably not work."
1898   :type '(choice (const nil) (const 1))
1899   :group 'cperl-indentation-details)
1900
1901 (defcustom cperl-break-one-line-blocks-when-indent t
1902   "*Non-nil means that one-line if/unless/while/until/for/foreach BLOCKs
1903 need to be reformatted into multiline ones when indenting a region."
1904   :type 'boolean
1905   :group 'cperl-indentation-details)
1906
1907 (defcustom cperl-fix-hanging-brace-when-indent t
1908   "*Non-nil means that BLOCK-end `}' may be put on a separate line
1909 when indenting a region.
1910 Braces followed by else/elsif/while/until are excepted."
1911   :type 'boolean
1912   :group 'cperl-indentation-details)
1913
1914 (defcustom cperl-merge-trailing-else t
1915   "*Non-nil means that BLOCK-end `}' followed by else/elsif/continue
1916 may be merged to be on the same line when indenting a region."
1917   :type 'boolean
1918   :group 'cperl-indentation-details)
1919
1920 (defcustom cperl-indent-parens-as-block nil
1921   "*Non-nil means that non-block ()-, {}- and []-groups are indented as blocks,
1922 but for trailing \",\" inside the group, which won't increase indentation.
1923 One should tune up `cperl-close-paren-offset' as well."
1924   :type 'boolean
1925   :group 'cperl-indentation-details)
1926
1927 (defcustom cperl-syntaxify-by-font-lock
1928   (and cperl-can-font-lock
1929        (boundp 'parse-sexp-lookup-properties))
1930   "*Non-nil means that CPerl uses `font-lock's routines for syntaxification."
1931   :type '(choice (const message) boolean)
1932   :group 'cperl-speed)
1933
1934 (defcustom cperl-syntaxify-unwind
1935   t
1936   "*Non-nil means that CPerl unwinds to a start of a long construction
1937 when syntaxifying a chunk of buffer."
1938   :type 'boolean
1939   :group 'cperl-speed)
1940
1941 (defcustom cperl-syntaxify-for-menu
1942   t
1943   "*Non-nil means that CPerl syntaxifies up to the point before showing menu.
1944 This way enabling/disabling of menu items is more correct."
1945   :type 'boolean
1946   :group 'cperl-speed)
1947
1948 (defcustom cperl-ps-print-face-properties
1949   '((font-lock-keyword-face             nil nil         bold shadow)
1950     (font-lock-variable-name-face       nil nil         bold)
1951     (font-lock-function-name-face       nil nil         bold italic box)
1952     (font-lock-constant-face            nil "LightGray" bold)
1953     (cperl-array-face                   nil "LightGray" bold underline)
1954     (cperl-hash-face                    nil "LightGray" bold italic underline)
1955     (font-lock-comment-face             nil "LightGray" italic)
1956     (font-lock-string-face              nil nil         italic underline)
1957     (cperl-nonoverridable-face          nil nil         italic underline)
1958     (font-lock-type-face                nil nil         underline)
1959     (underline                          nil "LightGray" strikeout))
1960   "List given as an argument to `ps-extend-face-list' in `cperl-ps-print'."
1961   :type '(repeat (cons symbol
1962                        (cons (choice (const nil) string)
1963                              (cons (choice (const nil) string)
1964                                    (repeat symbol)))))
1965   :group 'cperl-faces)
1966
1967 (if cperl-can-font-lock
1968     (progn
1969       (defvar cperl-dark-background
1970         (cperl-choose-color "navy" "os2blue" "darkgreen"))
1971       (defvar cperl-dark-foreground
1972         (cperl-choose-color "orchid1" "orange"))
1973
1974       (defface cperl-nonoverridable-face
1975         (` ((((class grayscale) (background light))
1976              (:background "Gray90" :italic t :underline t))
1977             (((class grayscale) (background dark))
1978              (:foreground "Gray80" :italic t :underline t :bold t))
1979             (((class color) (background light))
1980              (:foreground "chartreuse3"))
1981             (((class color) (background dark))
1982              (:foreground (, cperl-dark-foreground)))
1983             (t (:bold t :underline t))))
1984         "Font Lock mode face used to highlight array names."
1985         :group 'cperl-faces)
1986
1987       (defface cperl-array-face
1988         (` ((((class grayscale) (background light))
1989              (:background "Gray90" :bold t))
1990             (((class grayscale) (background dark))
1991              (:foreground "Gray80" :bold t))
1992             (((class color) (background light))
1993              (:foreground "Blue" :background "lightyellow2" :bold t))
1994             (((class color) (background dark))
1995              (:foreground "yellow" :background (, cperl-dark-background) :bold t))
1996             (t (:bold t))))
1997         "Font Lock mode face used to highlight array names."
1998         :group 'cperl-faces)
1999
2000       (defface cperl-hash-face
2001         (` ((((class grayscale) (background light))
2002              (:background "Gray90" :bold t :italic t))
2003             (((class grayscale) (background dark))
2004              (:foreground "Gray80" :bold t :italic t))
2005             (((class color) (background light))
2006              (:foreground "Red" :background "lightyellow2" :bold t :italic t))
2007             (((class color) (background dark))
2008              (:foreground "Red" :background (, cperl-dark-background) :bold t :italic t))
2009             (t (:bold t :italic t))))
2010         "Font Lock mode face used to highlight hash names."
2011         :group 'cperl-faces)))
2012
2013 \f
2014
2015 ;;; Short extra-docs.
2016
2017 (defvar cperl-tips 'please-ignore-this-line
2018   "Get maybe newer version of this package from
2019   http://ilyaz.org/software/emacs
2020 Subdirectory `cperl-mode' may contain yet newer development releases and/or
2021 patches to related files.
2022
2023 For best results apply to an older Emacs the patches from
2024   ftp://ftp.math.ohio-state.edu/pub/users/ilya/cperl-mode/patches
2025 \(this upgrades syntax-parsing abilities of RMS Emaxen v19.34 and
2026 v20.2 up to the level of RMS Emacs v20.3 - a must for a good Perl
2027 mode.)  As of beginning of 2003, XEmacs may provide a similar ability.
2028
2029 Get support packages choose-color.el (or font-lock-extra.el before
2030 19.30), imenu-go.el from the same place.  \(Look for other files there
2031 too... ;-).  Get a patch for imenu.el in 19.29.  Note that for 19.30 and
2032 later you should use choose-color.el *instead* of font-lock-extra.el
2033 \(and you will not get smart highlighting in C :-().
2034
2035 Note that to enable Compile choices in the menu you need to install
2036 mode-compile.el.
2037
2038 If your Emacs does not default to `cperl-mode' on Perl files, and you
2039 want it to: put the following into your .emacs file:
2040
2041   (autoload 'perl-mode \"cperl-mode\" \"alternate mode for editing Perl programs\" t)
2042
2043 or
2044
2045   (defalias 'perl-mode 'cperl-mode)
2046
2047 Get perl5-info from
2048   $CPAN/doc/manual/info/perl5-old/perl5-info.tar.gz
2049 Also, one can generate a newer documentation running `pod2texi' converter
2050   $CPAN/doc/manual/info/perl5/pod2texi-0.1.tar.gz
2051
2052 If you use imenu-go, run imenu on perl5-info buffer (you can do it
2053 from Perl menu).  If many files are related, generate TAGS files from
2054 Tools/Tags submenu in Perl menu.
2055
2056 If some class structure is too complicated, use Tools/Hierarchy-view
2057 from Perl menu, or hierarchic view of imenu.  The second one uses the
2058 current buffer only, the first one requires generation of TAGS from
2059 Perl/Tools/Tags menu beforehand.
2060
2061 Run Perl/Tools/Insert-spaces-if-needed to fix your lazy typing.
2062
2063 Switch auto-help on/off with Perl/Tools/Auto-help.
2064
2065 Though with contemporary Emaxen CPerl mode should maintain the correct
2066 parsing of Perl even when editing, sometimes it may be lost.  Fix this by
2067
2068   M-x norm RET
2069
2070 or
2071
2072   \\[normal-mode]
2073
2074 In cases of more severe confusion sometimes it is helpful to do
2075
2076   M-x load-l RET cperl-mode RET
2077   M-x norm RET
2078
2079 or
2080
2081   \\[load-library] cperl-mode RET
2082   \\[normal-mode]
2083
2084 Before reporting (non-)problems look in the problem section of online
2085 micro-docs on what I know about CPerl problems.")
2086
2087 (defvar cperl-problems 'please-ignore-this-line
2088   "Description of problems in CPerl mode.
2089 Some faces will not be shown on some versions of Emacs unless you
2090 install choose-color.el, available from
2091   http://ilyaz.org/software/emacs
2092
2093 `fill-paragraph' on a comment may leave the point behind the
2094 paragraph.  It also triggers a bug in some versions of Emacs (CPerl tries
2095 to detect it and bulk out).
2096
2097 See documentation of a variable `cperl-problems-old-emaxen' for the
2098 problems which disappear if you upgrade Emacs to a reasonably new
2099 version (20.3 for RMS Emacs, and those of 2004 for XEmacs).")
2100
2101 (defvar cperl-problems-old-emaxen 'please-ignore-this-line
2102   "Description of problems in CPerl mode specific for older Emacs versions.
2103
2104 Emacs had a _very_ restricted syntax parsing engine until RMS's Emacs
2105 20.1.  Most problems below are corrected starting from this version of
2106 Emacs, and all of them should be fixed in RMS's version 20.3.  (Or apply
2107 patches to Emacs 19.33/34 - see tips.)  XEmacs was very backward in
2108 this respect (until 2003).
2109
2110 Note that even with newer Emacsen in some very rare cases the details
2111 of interaction of `font-lock' and syntaxification may be not cleaned
2112 up yet.  You may get slightly different colors basing on the order of
2113 fontification and syntaxification.  Say, the initial faces is correct,
2114 but editing the buffer breaks this.
2115
2116 Even with older Emacsen CPerl mode tries to corrects some Emacs
2117 misunderstandings, however, for efficiency reasons the degree of
2118 correction is different for different operations.  The partially
2119 corrected problems are: POD sections, here-documents, regexps.  The
2120 operations are: highlighting, indentation, electric keywords, electric
2121 braces.
2122
2123 This may be confusing, since the regexp s#//#/#\; may be highlighted
2124 as a comment, but it will be recognized as a regexp by the indentation
2125 code.  Or the opposite case, when a POD section is highlighted, but
2126 may break the indentation of the following code (though indentation
2127 should work if the balance of delimiters is not broken by POD).
2128
2129 The main trick (to make $ a \"backslash\") makes constructions like
2130 ${aaa} look like unbalanced braces.  The only trick I can think of is
2131 to insert it as $ {aaa} (legal in perl5, not in perl4).
2132
2133 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
2134 as /($|\\s)/.  Note that such a transposition is not always possible.
2135
2136 The solution is to upgrade your Emacs or patch an older one.  Note
2137 that RMS's 20.2 has some bugs related to `syntax-table' text
2138 properties.  Patches are available on the main CPerl download site,
2139 and on CPAN.
2140
2141 If these bugs cannot be fixed on your machine (say, you have an inferior
2142 environment and cannot recompile), you may still disable all the fancy stuff
2143 via `cperl-use-syntax-table-text-property'.")
2144
2145 (defvar cperl-non-problems 'please-ignore-this-line
2146 "As you know from `problems' section, Perl syntax is too hard for CPerl on
2147 older Emacsen.  Here is what you can do if you cannot upgrade, or if
2148 you want to switch off these capabilities on RMS Emacs 20.2 (+patches) or 20.3
2149 or better.  Please skip this docs if you run a capable Emacs already.
2150
2151 Most of the time, if you write your own code, you may find an equivalent
2152 \(and almost as readable) expression (what is discussed below is usually
2153 not relevant on newer Emacsen, since they can do it automatically).
2154
2155 Try to help CPerl: add comments with embedded quotes to fix CPerl
2156 misunderstandings about the end of quotation:
2157
2158 $a='500$';      # ';
2159
2160 You won't need it too often.  The reason: $ \"quotes\" the following
2161 character (this saves a life a lot of times in CPerl), thus due to
2162 Emacs parsing rules it does not consider tick (i.e., ' ) after a
2163 dollar as a closing one, but as a usual character.  This is usually
2164 correct, but not in the above context.
2165
2166 Even with older Emacsen the indentation code is pretty wise.  The only
2167 drawback is that it relied on Emacs parsing to find matching
2168 parentheses.  And Emacs *could not* match parentheses in Perl 100%
2169 correctly.  So
2170         1 if s#//#/#;
2171 would not break indentation, but
2172         1 if ( s#//#/# );
2173 would.  Upgrade.
2174
2175 By similar reasons
2176         s\"abc\"def\";
2177 could confuse CPerl a lot.
2178
2179 If you still get wrong indentation in situation that you think the
2180 code should be able to parse, try:
2181
2182 a) Check what Emacs thinks about balance of your parentheses.
2183 b) Supply the code to me (IZ).
2184
2185 Pods were treated _very_ rudimentally.  Here-documents were not
2186 treated at all (except highlighting and inhibiting indentation).  Upgrade.
2187
2188 To speed up coloring the following compromises exist:
2189    a) sub in $mypackage::sub may be highlighted.
2190    b) -z in [a-z] may be highlighted.
2191    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
2192
2193
2194 Imenu in 19.31 is broken.  Set `imenu-use-keymap-menu' to t, and remove
2195 `car' before `imenu-choose-buffer-index' in `imenu'.
2196 `imenu-add-to-menubar' in 20.2 is broken.
2197 A lot of things on XEmacs may be broken too, judging by bug reports I
2198 receive.  Note that some releases of XEmacs are better than the others
2199 as far as bugs reports I see are concerned.")
2200
2201 (defvar cperl-praise 'please-ignore-this-line
2202   "Advantages of CPerl mode.
2203
2204 0) It uses the newest `syntax-table' property ;-);
2205
2206 1) It does 99% of Perl syntax correct (as opposed to 80-90% in Perl
2207 mode - but the latter number may have improved too in last years) even
2208 with old Emaxen which do not support `syntax-table' property.
2209
2210 When using `syntax-table' property for syntax assist hints, it should
2211 handle 99.995% of lines correct - or somesuch.  It automatically
2212 updates syntax assist hints when you edit your script.
2213
2214 2) It is generally believed to be \"the most user-friendly Emacs
2215 package\" whatever it may mean (I doubt that the people who say similar
2216 things tried _all_ the rest of Emacs ;-), but this was not a lonely
2217 voice);
2218
2219 3) Everything is customizable, one-by-one or in a big sweep;
2220
2221 4) It has many easily-accessable \"tools\":
2222         a) Can run program, check syntax, start debugger;
2223         b) Can lineup vertically \"middles\" of rows, like `=' in
2224                 a  = b;
2225                 cc = d;
2226         c) Can insert spaces where this impoves readability (in one
2227                 interactive sweep over the buffer);
2228         d) Has support for imenu, including:
2229                 1) Separate unordered list of \"interesting places\";
2230                 2) Separate TOC of POD sections;
2231                 3) Separate list of packages;
2232                 4) Hierarchical view of methods in (sub)packages;
2233                 5) and functions (by the full name - with package);
2234         e) Has an interface to INFO docs for Perl; The interface is
2235                 very flexible, including shrink-wrapping of
2236                 documentation buffer/frame;
2237         f) Has a builtin list of one-line explanations for perl constructs.
2238         g) Can show these explanations if you stay long enough at the
2239                 corresponding place (or on demand);
2240         h) Has an enhanced fontification (using 3 or 4 additional faces
2241                 comparing to font-lock - basically, different
2242                 namespaces in Perl have different colors);
2243         i) Can construct TAGS basing on its knowledge of Perl syntax,
2244                 the standard menu has 6 different way to generate
2245                 TAGS (if \"by directory\", .xs files - with C-language
2246                 bindings - are included in the scan);
2247         j) Can build a hierarchical view of classes (via imenu) basing
2248                 on generated TAGS file;
2249         k) Has electric parentheses, electric newlines, uses Abbrev
2250                 for electric logical constructs
2251                         while () {}
2252                 with different styles of expansion (context sensitive
2253                 to be not so bothering).  Electric parentheses behave
2254                 \"as they should\" in a presence of a visible region.
2255         l) Changes msb.el \"on the fly\" to insert a group \"Perl files\";
2256         m) Can convert from
2257                 if (A) { B }
2258            to
2259                 B if A;
2260
2261         n) Highlights (by user-choice) either 3-delimiters constructs
2262            (such as tr/a/b/), or regular expressions and `y/tr';
2263         o) Highlights trailing whitespace;
2264         p) Is able to manipulate Perl Regular Expressions to ease
2265            conversion to a more readable form.
2266         q) Can ispell POD sections and HERE-DOCs.
2267         r) Understands comments and character classes inside regular
2268            expressions; can find matching () and [] in a regular expression.
2269         s) Allows indentation of //x-style regular expressions;
2270         t) Highlights different symbols in regular expressions according
2271            to their function; much less problems with backslashitis.
2272
2273 5) The indentation engine was very smart, but most of tricks may be
2274 not needed anymore with the support for `syntax-table' property.  Has
2275 progress indicator for indentation (with `imenu' loaded).
2276
2277 6) Indent-region improves inline-comments as well; also corrects
2278 whitespace *inside* the conditional/loop constructs.
2279
2280 7) Fill-paragraph correctly handles multi-line comments;
2281
2282 8) Can switch to different indentation styles by one command, and restore
2283 the settings present before the switch.
2284
2285 9) When doing indentation of control constructs, may correct
2286 line-breaks/spacing between elements of the construct.
2287
2288 10) Uses a linear-time algorith for indentation of regions (on Emaxen with
2289 capable syntax engines).")
2290
2291 (defvar cperl-speed 'please-ignore-this-line
2292   "This is an incomplete compendium of what is available in other parts
2293 of CPerl documentation.  (Please inform me if I skept anything.)
2294
2295 There is a perception that CPerl is slower than alternatives.  This part
2296 of documentation is designed to overcome this misconception.
2297
2298 *By default* CPerl tries to enable the most comfortable settings.
2299 From most points of view, correctly working package is infinitely more
2300 comfortable than a non-correctly working one, thus by default CPerl
2301 prefers correctness over speed.  Below is the guide how to change
2302 settings if your preferences are different.
2303
2304 A)  Speed of loading the file.  When loading file, CPerl may perform a
2305 scan which indicates places which cannot be parsed by primitive Emacs
2306 syntax-parsing routines, and marks them up so that either
2307
2308     A1) CPerl may work around these deficiencies (for big chunks, mostly
2309         PODs and HERE-documents), or
2310     A2) On capable Emaxen CPerl will use improved syntax-handlings
2311         which reads mark-up hints directly.
2312
2313     The scan in case A2 is much more comprehensive, thus may be slower.
2314
2315     User can disable syntax-engine-helping scan of A2 by setting
2316        `cperl-use-syntax-table-text-property'
2317     variable to nil (if it is set to t).
2318
2319     One can disable the scan altogether (both A1 and A2) by setting
2320        `cperl-pod-here-scan'
2321     to nil.
2322
2323 B) Speed of editing operations.
2324
2325     One can add a (minor) speedup to editing operations by setting
2326        `cperl-use-syntax-table-text-property'
2327     variable to nil (if it is set to t).  This will disable
2328     syntax-engine-helping scan, thus will make many more Perl
2329     constructs be wrongly recognized by CPerl, thus may lead to
2330     wrongly matched parentheses, wrong indentation, etc.
2331
2332     One can unset `cperl-syntaxify-unwind'.  This might speed up editing
2333     of, say, long POD sections.")
2334
2335 (defvar cperl-tips-faces 'please-ignore-this-line
2336   "CPerl mode uses following faces for highlighting:
2337
2338   `cperl-array-face'            Array names
2339   `cperl-hash-face'             Hash names
2340   `font-lock-comment-face'      Comments, PODs and whatever is considered
2341                                 syntaxically to be not code
2342   `font-lock-constant-face'     HERE-doc delimiters, labels, delimiters of
2343                                 2-arg operators s/y/tr/ or of RExen,
2344   `font-lock-function-name-face' Special-cased m// and s//foo/, _ as
2345                                 a target of a file tests, file tests,
2346                                 subroutine names at the moment of definition
2347                                 (except those conflicting with Perl operators),
2348                                 package names (when recognized), format names
2349   `font-lock-keyword-face'      Control flow switch constructs, declarators
2350   `cperl-nonoverridable-face'   Non-overridable keywords, modifiers of RExen
2351   `font-lock-string-face'       Strings, qw() constructs, RExen, POD sections,
2352                                 literal parts and the terminator of formats
2353                                 and whatever is syntaxically considered
2354                                 as string literals
2355   `font-lock-type-face'         Overridable keywords
2356   `font-lock-variable-name-face' Variable declarations, indirect array and
2357                                 hash names, POD headers/item names
2358   `cperl-invalid-face'          Trailing whitespace
2359
2360 Note that in several situations the highlighting tries to inform about
2361 possible confusion, such as different colors for function names in
2362 declarations depending on what they (do not) override, or special cases
2363 m// and s/// which do not do what one would expect them to do.
2364
2365 Help with best setup of these faces for printout requested (for each of
2366 the faces: please specify bold, italic, underline, shadow and box.)
2367
2368 \(Not finished.)")
2369
2370 \f
2371
2372 ;;; Portability stuff:
2373
2374 (defmacro cperl-define-key (emacs-key definition &optional xemacs-key)
2375   (` (define-key cperl-mode-map
2376        (, (if xemacs-key
2377               (` (if cperl-xemacs-p (, xemacs-key) (, emacs-key)))
2378             emacs-key))
2379        (, definition))))
2380
2381 (defvar cperl-del-back-ch
2382   (car (append (where-is-internal 'delete-backward-char)
2383                (where-is-internal 'backward-delete-char-untabify)))
2384   "Character generated by key bound to `delete-backward-char'.")
2385
2386 (and (vectorp cperl-del-back-ch) (= (length cperl-del-back-ch) 1)
2387      (setq cperl-del-back-ch (aref cperl-del-back-ch 0)))
2388
2389 (defun cperl-mark-active () (mark))     ; Avoid undefined warning
2390 (if cperl-xemacs-p
2391     (progn
2392       ;; "Active regions" are on: use region only if active
2393       ;; "Active regions" are off: use region unconditionally
2394       (defun cperl-use-region-p ()
2395         (if zmacs-regions (mark) t)))
2396   (defun cperl-use-region-p ()
2397     (if transient-mark-mode mark-active t))
2398   (defun cperl-mark-active () mark-active))
2399
2400 (defsubst cperl-enable-font-lock ()
2401   cperl-can-font-lock)
2402
2403 (defun cperl-putback-char (c)           ; Emacs 19
2404   (set 'unread-command-events (list c))) ; Avoid undefined warning
2405
2406 (if (boundp 'unread-command-events)
2407     (if cperl-xemacs-p
2408         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
2409           (setq unread-command-events (list (eval '(character-to-event c))))))
2410   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
2411     (set 'unread-command-event (eval '(character-to-event c))))) ; Avoid warnings
2412
2413 (or (fboundp 'uncomment-region)
2414     (defun uncomment-region (beg end)
2415       (interactive "r")
2416       (comment-region beg end -1)))
2417
2418 (defvar cperl-do-not-fontify
2419   (if (string< emacs-version "19.30")
2420       'fontified
2421     'lazy-lock)
2422   "Text property which inhibits refontification.")
2423
2424 (defsubst cperl-put-do-not-fontify (from to &optional post)
2425   ;; If POST, do not do it with postponed fontification
2426   (if (and post cperl-syntaxify-by-font-lock)
2427       nil
2428     (put-text-property (max (point-min) (1- from))
2429                        to cperl-do-not-fontify t)))
2430
2431 (defcustom cperl-mode-hook nil
2432   "Hook run by CPerl mode."
2433   :type 'hook
2434   :group 'cperl)
2435
2436 (defvar cperl-syntax-state nil)
2437 (defvar cperl-syntax-done-to nil)
2438 (defvar cperl-emacs-can-parse (> (length (save-excursion
2439                                            (parse-partial-sexp (point) (point)))) 9))
2440 \f
2441 ;; Make customization possible "in reverse"
2442 (defsubst cperl-val (symbol &optional default hairy)
2443   (cond
2444    ((eq (symbol-value symbol) 'null) default)
2445    (cperl-hairy (or hairy t))
2446    (t (symbol-value symbol))))
2447 \f
2448
2449 (defun cperl-make-indent (column &optional minimum keep)
2450   "Makes indent of the current line the requested amount.
2451 If ANEW, removes the old indentation.  Works around a bug in ancient
2452 versions of Emacs."
2453   (let ((prop (get-text-property (point) 'syntax-type)))
2454     (or keep
2455         (delete-horizontal-space))
2456     (indent-to column minimum)
2457     ;; In old versions (e.g., 19.33) `indent-to' would not inherit properties
2458     (and prop
2459          (> (current-column) 0)
2460          (save-excursion
2461            (beginning-of-line)
2462            (or (get-text-property (point) 'syntax-type)
2463                (and (looking-at "\\=[ \t]")
2464                       (put-text-property (point) (match-end 0)
2465                                          'syntax-type prop)))))))
2466
2467 ;;; Probably it is too late to set these guys already, but it can help later:
2468
2469 (and cperl-clobber-mode-lists
2470      (setq auto-mode-alist
2471       (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
2472      (and (boundp 'interpreter-mode-alist)
2473           (setq interpreter-mode-alist (append interpreter-mode-alist
2474                                                '(("miniperl" . perl-mode))))))
2475 (if (fboundp 'eval-when-compile)
2476     (eval-when-compile
2477       (mapcar (lambda (p)
2478                 (condition-case nil
2479                     (require p)
2480                   (error nil)))
2481               '(imenu easymenu etags timer man info))
2482       (if (fboundp 'ps-extend-face-list)
2483           (defmacro cperl-ps-extend-face-list (arg)
2484             (` (ps-extend-face-list (, arg))))
2485         (defmacro cperl-ps-extend-face-list (arg)
2486           (` (error "This version of Emacs has no `ps-extend-face-list'"))))
2487       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
2488       ;; macros instead of defsubsts don't work on Emacs, so we do the
2489       ;; expansion manually.  Any other suggestions?
2490       (if cperl-can-font-lock
2491           (require 'font-lock))
2492       (require 'cl)))
2493
2494 (defvar cperl-mode-abbrev-table nil
2495   "Abbrev table in use in CPerl mode buffers.")
2496
2497 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
2498
2499 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
2500
2501 (if cperl-mode-map nil
2502   (setq cperl-mode-map (make-sparse-keymap))
2503   (cperl-define-key "{" 'cperl-electric-lbrace)
2504   (cperl-define-key "[" 'cperl-electric-paren)
2505   (cperl-define-key "(" 'cperl-electric-paren)
2506   (cperl-define-key "<" 'cperl-electric-paren)
2507   (cperl-define-key "}" 'cperl-electric-brace)
2508   (cperl-define-key "]" 'cperl-electric-rparen)
2509   (cperl-define-key ")" 'cperl-electric-rparen)
2510   (cperl-define-key ";" 'cperl-electric-semi)
2511   (cperl-define-key ":" 'cperl-electric-terminator)
2512   (cperl-define-key "\C-j" 'newline-and-indent)
2513   (cperl-define-key "\C-c\C-j" 'cperl-linefeed)
2514   (cperl-define-key "\C-c\C-t" 'cperl-invert-if-unless)
2515   (cperl-define-key "\C-c\C-a" 'cperl-toggle-auto-newline)
2516   (cperl-define-key "\C-c\C-k" 'cperl-toggle-abbrev)
2517   (cperl-define-key "\C-c\C-w" 'cperl-toggle-construct-fix)
2518   (cperl-define-key "\C-c\C-f" 'auto-fill-mode)
2519   (cperl-define-key "\C-c\C-e" 'cperl-toggle-electric)
2520   (cperl-define-key "\C-c\C-b" 'cperl-find-bad-style)
2521   (cperl-define-key "\C-c\C-p" 'cperl-pod-spell)
2522   (cperl-define-key "\C-c\C-d" 'cperl-here-doc-spell)
2523   (cperl-define-key "\C-c\C-n" 'cperl-narrow-to-here-doc)
2524   (cperl-define-key "\C-c\C-ha" 'cperl-toggle-autohelp)
2525   (cperl-define-key "\C-c\C-hp" 'cperl-perldoc)
2526   (cperl-define-key "\C-c\C-hP" 'cperl-perldoc-at-point)
2527   (cperl-define-key "\e\C-q" 'cperl-indent-exp) ; Usually not bound
2528   (cperl-define-key [?\C-\M-\|] 'cperl-lineup
2529                     [(control meta |)])
2530   ;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
2531   ;;(cperl-define-key "\e;" 'cperl-indent-for-comment)
2532   (cperl-define-key "\177" 'cperl-electric-backspace)
2533   (cperl-define-key "\t" 'cperl-indent-command)
2534   ;; don't clobber the backspace binding:
2535   (cperl-define-key "\C-c\C-hF" 'cperl-info-on-command
2536                     [(control c) (control h) F])
2537   (if (cperl-val 'cperl-clobber-lisp-bindings)
2538       (progn
2539         (cperl-define-key "\C-hf"
2540                           ;;(concat (char-to-string help-char) "f") ; does not work
2541                           'cperl-info-on-command
2542                           [(control h) f])
2543         (cperl-define-key "\C-hv"
2544                           ;;(concat (char-to-string help-char) "v") ; does not work
2545                           'cperl-get-help
2546                           [(control h) v])
2547         (cperl-define-key "\C-c\C-hf"
2548                           ;;(concat (char-to-string help-char) "f") ; does not work
2549                           (key-binding "\C-hf")
2550                           [(control c) (control h) f])
2551         (cperl-define-key "\C-c\C-hv"
2552                           ;;(concat (char-to-string help-char) "v") ; does not work
2553                           (key-binding "\C-hv")
2554                           [(control c) (control h) v]))
2555     (cperl-define-key "\C-c\C-hf" 'cperl-info-on-current-command
2556                       [(control c) (control h) f])
2557     (cperl-define-key "\C-c\C-hv"
2558                       ;;(concat (char-to-string help-char) "v") ; does not work
2559                       'cperl-get-help
2560                       [(control c) (control h) v]))
2561   (if (and cperl-xemacs-p
2562            (<= emacs-minor-version 11) (<= emacs-major-version 19))
2563       (progn
2564         ;; substitute-key-definition is usefulness-deenhanced...
2565         ;;;;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
2566         (cperl-define-key "\e;" 'cperl-indent-for-comment)
2567         (cperl-define-key "\e\C-\\" 'cperl-indent-region))
2568     (or (boundp 'fill-paragraph-function)
2569         (substitute-key-definition
2570          'fill-paragraph 'cperl-fill-paragraph
2571          cperl-mode-map global-map))
2572     (substitute-key-definition
2573      'indent-sexp 'cperl-indent-exp
2574      cperl-mode-map global-map)
2575     (substitute-key-definition
2576      'indent-region 'cperl-indent-region
2577      cperl-mode-map global-map)
2578     (substitute-key-definition
2579      'indent-for-comment 'cperl-indent-for-comment
2580      cperl-mode-map global-map)))
2581
2582 (defvar cperl-menu)
2583 (defvar cperl-lazy-installed)
2584 (defvar cperl-old-style nil)
2585 (condition-case nil
2586     (progn
2587       (require 'easymenu)
2588       (easy-menu-define
2589        cperl-menu cperl-mode-map "Menu for CPerl mode"
2590        '("Perl"
2591          ["Beginning of function" beginning-of-defun t]
2592          ["End of function" end-of-defun t]
2593          ["Mark function" mark-defun t]
2594          ["Indent expression" cperl-indent-exp t]
2595          ["Fill paragraph/comment" cperl-fill-paragraph t]
2596          "----"
2597          ["Line up a construction" cperl-lineup (cperl-use-region-p)]
2598          ["Invert if/unless/while etc" cperl-invert-if-unless t]
2599          ("Regexp"
2600           ["Beautify" cperl-beautify-regexp
2601            cperl-use-syntax-table-text-property]
2602           ["Beautify one level deep" (cperl-beautify-regexp 1)
2603            cperl-use-syntax-table-text-property]
2604           ["Beautify a group" cperl-beautify-level
2605            cperl-use-syntax-table-text-property]
2606           ["Beautify a group one level deep" (cperl-beautify-level 1)
2607            cperl-use-syntax-table-text-property]
2608           ["Contract a group" cperl-contract-level
2609            cperl-use-syntax-table-text-property]
2610           ["Contract groups" cperl-contract-levels
2611            cperl-use-syntax-table-text-property])
2612          ["Insert spaces if needed to fix style" cperl-find-bad-style t]
2613          ["Refresh \"hard\" constructions" cperl-find-pods-heres t]
2614          "----"
2615          ["Indent region" cperl-indent-region (cperl-use-region-p)]
2616          ["Comment region" cperl-comment-region (cperl-use-region-p)]
2617          ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
2618          "----"
2619          ["Run" mode-compile (fboundp 'mode-compile)]
2620          ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
2621                                         (get-buffer "*compilation*"))]
2622          ["Next error" next-error (get-buffer "*compilation*")]
2623          ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
2624          "----"
2625          ["Debugger" cperl-db t]
2626          "----"
2627          ("Tools"
2628           ["Imenu" imenu (fboundp 'imenu)]
2629           ["Imenu on Perl Info" cperl-imenu-on-info (featurep 'imenu)]
2630           "----"
2631           ["Ispell PODs" cperl-pod-spell
2632            ;; Better not to update syntaxification here:
2633            ;; debugging syntaxificatio can be broken by this???
2634            (or
2635             (get-text-property (point-min) 'in-pod)
2636             (< (progn
2637                  (and cperl-syntaxify-for-menu
2638                       (cperl-update-syntaxification (point-max) (point-max)))
2639                  (next-single-property-change (point-min) 'in-pod nil (point-max)))
2640                (point-max)))]
2641           ["Ispell HERE-DOCs" cperl-here-doc-spell
2642            (< (progn
2643                 (and cperl-syntaxify-for-menu
2644                      (cperl-update-syntaxification (point-max) (point-max)))
2645                 (next-single-property-change (point-min) 'here-doc-group nil (point-max)))
2646               (point-max))]
2647           ["Narrow to this HERE-DOC" cperl-narrow-to-here-doc
2648            (eq 'here-doc  (progn
2649                 (and cperl-syntaxify-for-menu
2650                      (cperl-update-syntaxification (point) (point)))
2651                 (get-text-property (point) 'syntax-type)))]
2652           ["Select this HERE-DOC or POD section"
2653            cperl-select-this-pod-or-here-doc
2654            (memq (progn
2655                    (and cperl-syntaxify-for-menu
2656                         (cperl-update-syntaxification (point) (point)))
2657                    (get-text-property (point) 'syntax-type))
2658                  '(here-doc pod))]
2659           "----"
2660           ["CPerl pretty print (exprmntl)" cperl-ps-print
2661            (fboundp 'ps-extend-face-list)]
2662           "----"
2663           ["Syntaxify region" cperl-find-pods-heres-region
2664            (cperl-use-region-p)]
2665           ["Profile syntaxification" cperl-time-fontification t]
2666           ["Debug errors in delayed fontification" cperl-emulate-lazy-lock t]
2667           ["Debug unwind for syntactic scan" cperl-toggle-set-debug-unwind t]
2668           ["Debug backtrace on syntactic scan (BEWARE!!!)"
2669            (cperl-toggle-set-debug-unwind nil t) t]
2670           "----"
2671           ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
2672           ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
2673           ("Tags"
2674 ;;;          ["Create tags for current file" cperl-etags t]
2675 ;;;          ["Add tags for current file" (cperl-etags t) t]
2676 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
2677 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
2678 ;;;          ["Create tags for Perl files in (sub)directories"
2679 ;;;           (cperl-etags nil 'recursive) t]
2680 ;;;          ["Add tags for Perl files in (sub)directories"
2681 ;;;           (cperl-etags t 'recursive) t])
2682 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
2683            ["Create tags for current file" (cperl-write-tags nil t) t]
2684            ["Add tags for current file" (cperl-write-tags) t]
2685            ["Create tags for Perl files in directory"
2686             (cperl-write-tags nil t nil t) t]
2687            ["Add tags for Perl files in directory"
2688             (cperl-write-tags nil nil nil t) t]
2689            ["Create tags for Perl files in (sub)directories"
2690             (cperl-write-tags nil t t t) t]
2691            ["Add tags for Perl files in (sub)directories"
2692             (cperl-write-tags nil nil t t) t]))
2693          ("Perl docs"
2694           ["Define word at point" imenu-go-find-at-position
2695            (fboundp 'imenu-go-find-at-position)]
2696           ["Help on function" cperl-info-on-command t]
2697           ["Help on function at point" cperl-info-on-current-command t]
2698           ["Help on symbol at point" cperl-get-help t]
2699           ["Perldoc" cperl-perldoc t]
2700           ["Perldoc on word at point" cperl-perldoc-at-point t]
2701           ["View manpage of POD in this file" cperl-build-manpage t]
2702           ["Auto-help on" cperl-lazy-install
2703            (and (fboundp 'run-with-idle-timer)
2704                 (not cperl-lazy-installed))]
2705           ["Auto-help off" cperl-lazy-unstall
2706            (and (fboundp 'run-with-idle-timer)
2707                 cperl-lazy-installed)])
2708          ("Toggle..."
2709           ["Auto newline" cperl-toggle-auto-newline t]
2710           ["Electric parens" cperl-toggle-electric t]
2711           ["Electric keywords" cperl-toggle-abbrev t]
2712           ["Fix whitespace on indent" cperl-toggle-construct-fix t]
2713           ["Auto-help on Perl constructs" cperl-toggle-autohelp t]
2714           ["Auto fill" auto-fill-mode t])
2715          ("Indent styles..."
2716           ["CPerl" (cperl-set-style "CPerl") t]
2717           ["PerlStyle" (cperl-set-style "PerlStyle") t]
2718           ["GNU" (cperl-set-style "GNU") t]
2719           ["C++" (cperl-set-style "C++") t]
2720           ["FSF" (cperl-set-style "FSF") t]
2721           ["BSD" (cperl-set-style "BSD") t]
2722           ["Whitesmith" (cperl-set-style "Whitesmith") t]
2723           ["Current" (cperl-set-style "Current") t]
2724           ["Memorized" (cperl-set-style-back) cperl-old-style])
2725          ("Micro-docs"
2726           ["Tips" (describe-variable 'cperl-tips) t]
2727           ["Problems" (describe-variable 'cperl-problems) t]
2728           ["Non-problems" (describe-variable 'cperl-non-problems) t]
2729           ["Speed" (describe-variable 'cperl-speed) t]
2730           ["Praise" (describe-variable 'cperl-praise) t]
2731           ["Faces" (describe-variable 'cperl-tips-faces) t]
2732           ["CPerl mode" (describe-function 'cperl-mode) t]
2733           ["CPerl version"
2734            (message "The version of master-file for this CPerl is %s"
2735                     cperl-version) t]))))
2736   (error nil))
2737
2738 (autoload 'c-macro-expand "cmacexp"
2739   "Display the result of expanding all C macros occurring in the region.
2740 The expansion is entirely correct because it uses the C preprocessor."
2741   t)
2742
2743 ;;; These two must be unwound, otherwise take exponential time
2744 (defconst cperl-maybe-white-and-comment-rex "[ \t\n]*\\(#[^\n]*\n[ \t\n]*\\)*"
2745 "Regular expression to match optional whitespace with interpspersed comments.
2746 Should contain exactly one group.")
2747
2748 ;;; This one is tricky to unwind; still very inefficient...
2749 (defconst cperl-white-and-comment-rex "\\([ \t\n]\\|#[^\n]*\n\\)+"
2750 "Regular expression to match whitespace with interpspersed comments.
2751 Should contain exactly one group.")
2752
2753
2754 ;;; Is incorporated in `cperl-imenu--function-name-regexp-perl'
2755 ;;; `cperl-outline-regexp', `defun-prompt-regexp'.
2756 ;;; Details of groups in this may be used in several functions; see comments
2757 ;;; near mentioned above variable(s)...
2758 ;;; sub($$):lvalue{}  sub:lvalue{} Both allowed...
2759 (defsubst cperl-after-sub-regexp (named attr) ; 9 groups without attr...
2760   "Match the text after `sub' in a subroutine declaration.
2761 If NAMED is nil, allows anonymous subroutines.  Matches up to the first \":\"
2762 of attributes (if present), or end of the name or prototype (whatever is
2763 the last)."
2764   (concat                               ; Assume n groups before this...
2765    "\\("                                ; n+1=name-group
2766      cperl-white-and-comment-rex        ; n+2=pre-name
2767      "\\(::[a-zA-Z_0-9:']+\\|[a-zA-Z_'][a-zA-Z_0-9:']*\\)" ; n+3=name
2768    "\\)"                                ; END n+1=name-group
2769    (if named "" "?")
2770    "\\("                                ; n+4=proto-group
2771      cperl-maybe-white-and-comment-rex  ; n+5=pre-proto
2772      "\\(([^()]*)\\)"                   ; n+6=prototype
2773    "\\)?"                               ; END n+4=proto-group
2774    "\\("                                ; n+7=attr-group
2775      cperl-maybe-white-and-comment-rex  ; n+8=pre-attr
2776      "\\("                              ; n+9=start-attr
2777         ":"
2778         (if attr (concat
2779                   "\\("
2780                      cperl-maybe-white-and-comment-rex ; whitespace-comments
2781                      "\\(\\sw\\|_\\)+"  ; attr-name
2782                      ;; attr-arg (1 level of internal parens allowed!)
2783                      "\\((\\(\\\\.\\|[^\\\\()]\\|([^\\\\()]*)\\)*)\\)?"
2784                      "\\("              ; optional : (XXX allows trailing???)
2785                         cperl-maybe-white-and-comment-rex ; whitespace-comments
2786                      ":\\)?"
2787                   "\\)+")
2788           "[^:]")
2789      "\\)"
2790    "\\)?"                               ; END n+6=proto-group
2791    ))
2792
2793 ;;; Details of groups in this are used in `cperl-imenu--create-perl-index'
2794 ;;;  and `cperl-outline-level'.
2795 ;;;; Was: 2=sub|package; now 2=package-group, 5=package-name 8=sub-name (+3)
2796 (defvar cperl-imenu--function-name-regexp-perl
2797   (concat
2798    "^\\("                               ; 1 = all
2799        "\\([ \t]*package"               ; 2 = package-group
2800           "\\("                         ; 3 = package-name-group
2801             cperl-white-and-comment-rex ; 4 = pre-package-name
2802                "\\([a-zA-Z_0-9:']+\\)\\)?\\)" ; 5 = package-name
2803        "\\|"
2804           "[ \t]*sub"
2805           (cperl-after-sub-regexp 'named nil) ; 8=name 11=proto 14=attr-start
2806           cperl-maybe-white-and-comment-rex     ; 15=pre-block
2807    "\\|"
2808      "=head\\([1-4]\\)[ \t]+"           ; 16=level
2809      "\\([^\n]+\\)$"                    ; 17=text
2810    "\\)"))
2811
2812 (defvar cperl-outline-regexp
2813   (concat cperl-imenu--function-name-regexp-perl "\\|" "\\`"))
2814
2815 (defvar cperl-mode-syntax-table nil
2816   "Syntax table in use in CPerl mode buffers.")
2817
2818 (defvar cperl-string-syntax-table nil
2819   "Syntax table in use in CPerl mode string-like chunks.")
2820
2821 (defsubst cperl-1- (p)
2822   (max (point-min) (1- p)))
2823
2824 (defsubst cperl-1+ (p)
2825   (min (point-max) (1+ p)))
2826
2827 (if cperl-mode-syntax-table
2828     ()
2829   (setq cperl-mode-syntax-table (make-syntax-table))
2830   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
2831   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
2832   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
2833   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
2834   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
2835   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
2836   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
2837   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
2838   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
2839   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
2840   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
2841   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
2842   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
2843   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
2844   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
2845   (if cperl-under-as-char
2846       (modify-syntax-entry ?_ "w" cperl-mode-syntax-table))
2847   (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
2848   (modify-syntax-entry ?| "." cperl-mode-syntax-table)
2849   (setq cperl-string-syntax-table (copy-syntax-table cperl-mode-syntax-table))
2850   (modify-syntax-entry ?$ "." cperl-string-syntax-table)
2851   (modify-syntax-entry ?\{ "." cperl-string-syntax-table)
2852   (modify-syntax-entry ?\} "." cperl-string-syntax-table)
2853   (modify-syntax-entry ?# "." cperl-string-syntax-table)) ; (?# comment )
2854
2855
2856 \f
2857 ;; provide an alias for working with emacs 19.  the perl-mode that comes
2858 ;; with it is really bad, and this lets us seamlessly replace it.
2859 ;;;###autoload
2860 (fset 'perl-mode 'cperl-mode)
2861 (defvar cperl-faces-init nil)
2862 ;; Fix for msb.el
2863 (defvar cperl-msb-fixed nil)
2864 (defvar font-lock-syntactic-keywords)
2865 (defvar perl-font-lock-keywords)
2866 (defvar perl-font-lock-keywords-1)
2867 (defvar perl-font-lock-keywords-2)
2868 (defvar outline-level)
2869 (if (fboundp 'defvaralias)
2870     (let ((f 'defvaralias)) ; Some functions deduce stuff from the mode name...
2871       (funcall f 'cperl-font-lock-keywords   'perl-font-lock-keywords)
2872       (funcall f 'cperl-font-lock-keywords-1 'perl-font-lock-keywords-1)
2873       (funcall f 'cperl-font-lock-keywords-2 'perl-font-lock-keywords-2)))
2874
2875 (defvar cperl-use-major-mode 'perl-mode)
2876 (defvar cperl-font-lock-multiline-start nil)
2877 (defvar cperl-font-lock-multiline nil)
2878 (defvar cperl-compilation-error-regexp-alist nil)
2879 (defvar cperl-font-locking nil)
2880
2881 ;;;###autoload
2882 (defun cperl-mode ()
2883   "Major mode for editing Perl code.
2884 Expression and list commands understand all C brackets.
2885 Tab indents for Perl code.
2886 Paragraphs are separated by blank lines only.
2887 Delete converts tabs to spaces as it moves back.
2888
2889 Various characters in Perl almost always come in pairs: {}, (), [],
2890 sometimes <>.  When the user types the first, she gets the second as
2891 well, with optional special formatting done on {}.  (Disabled by
2892 default.)  You can always quote (with \\[quoted-insert]) the left
2893 \"paren\" to avoid the expansion.  The processing of < is special,
2894 since most the time you mean \"less\".  CPerl mode tries to guess
2895 whether you want to type pair <>, and inserts is if it
2896 appropriate.  You can set `cperl-electric-parens-string' to the string that
2897 contains the parenths from the above list you want to be electrical.
2898 Electricity of parenths is controlled by `cperl-electric-parens'.
2899 You may also set `cperl-electric-parens-mark' to have electric parens
2900 look for active mark and \"embrace\" a region if possible.'
2901
2902 CPerl mode provides expansion of the Perl control constructs:
2903
2904    if, else, elsif, unless, while, until, continue, do,
2905    for, foreach, formy and foreachmy.
2906
2907 and POD directives (Disabled by default, see `cperl-electric-keywords'.)
2908
2909 The user types the keyword immediately followed by a space, which
2910 causes the construct to be expanded, and the point is positioned where
2911 she is most likely to want to be.  eg. when the user types a space
2912 following \"if\" the following appears in the buffer: if () { or if ()
2913 } { } and the cursor is between the parentheses.  The user can then
2914 type some boolean expression within the parens.  Having done that,
2915 typing \\[cperl-linefeed] places you - appropriately indented - on a
2916 new line between the braces (if you typed \\[cperl-linefeed] in a POD
2917 directive line, then appropriate number of new lines is inserted).
2918
2919 If CPerl decides that you want to insert \"English\" style construct like
2920
2921             bite if angry;
2922
2923 it will not do any expansion.  See also help on variable
2924 `cperl-extra-newline-before-brace'.  (Note that one can switch the
2925 help message on expansion by setting `cperl-message-electric-keyword'
2926 to nil.)
2927
2928 \\[cperl-linefeed] is a convenience replacement for typing carriage
2929 return.  It places you in the next line with proper indentation, or if
2930 you type it inside the inline block of control construct, like
2931
2932             foreach (@lines) {print; print}
2933
2934 and you are on a boundary of a statement inside braces, it will
2935 transform the construct into a multiline and will place you into an
2936 appropriately indented blank line.  If you need a usual
2937 `newline-and-indent' behaviour, it is on \\[newline-and-indent],
2938 see documentation on `cperl-electric-linefeed'.
2939
2940 Use \\[cperl-invert-if-unless] to change a construction of the form
2941
2942             if (A) { B }
2943
2944 into
2945
2946             B if A;
2947
2948 \\{cperl-mode-map}
2949
2950 Setting the variable `cperl-font-lock' to t switches on font-lock-mode
2951 \(even with older Emacsen), `cperl-electric-lbrace-space' to t switches
2952 on electric space between $ and {, `cperl-electric-parens-string' is
2953 the string that contains parentheses that should be electric in CPerl
2954 \(see also `cperl-electric-parens-mark' and `cperl-electric-parens'),
2955 setting `cperl-electric-keywords' enables electric expansion of
2956 control structures in CPerl.  `cperl-electric-linefeed' governs which
2957 one of two linefeed behavior is preferable.  You can enable all these
2958 options simultaneously (recommended mode of use) by setting
2959 `cperl-hairy' to t.  In this case you can switch separate options off
2960 by setting them to `null'.  Note that one may undo the extra
2961 whitespace inserted by semis and braces in `auto-newline'-mode by
2962 consequent \\[cperl-electric-backspace].
2963
2964 If your site has perl5 documentation in info format, you can use commands
2965 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
2966 These keys run commands `cperl-info-on-current-command' and
2967 `cperl-info-on-command', which one is which is controlled by variable
2968 `cperl-info-on-command-no-prompt' and `cperl-clobber-lisp-bindings'
2969 \(in turn affected by `cperl-hairy').
2970
2971 Even if you have no info-format documentation, short one-liner-style
2972 help is available on \\[cperl-get-help], and one can run perldoc or
2973 man via menu.
2974
2975 It is possible to show this help automatically after some idle time.
2976 This is regulated by variable `cperl-lazy-help-time'.  Default with
2977 `cperl-hairy' (if the value of `cperl-lazy-help-time' is nil) is 5
2978 secs idle time .  It is also possible to switch this on/off from the
2979 menu, or via \\[cperl-toggle-autohelp].  Requires `run-with-idle-timer'.
2980
2981 Use \\[cperl-lineup] to vertically lineup some construction - put the
2982 beginning of the region at the start of construction, and make region
2983 span the needed amount of lines.
2984
2985 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
2986 `cperl-pod-face', `cperl-pod-head-face' control processing of POD and
2987 here-docs sections.  With capable Emaxen results of scan are used
2988 for indentation too, otherwise they are used for highlighting only.
2989
2990 Variables controlling indentation style:
2991  `cperl-tab-always-indent'
2992     Non-nil means TAB in CPerl mode should always reindent the current line,
2993     regardless of where in the line point is when the TAB command is used.
2994  `cperl-indent-left-aligned-comments'
2995     Non-nil means that the comment starting in leftmost column should indent.
2996  `cperl-auto-newline'
2997     Non-nil means automatically newline before and after braces,
2998     and after colons and semicolons, inserted in Perl code.  The following
2999     \\[cperl-electric-backspace] will remove the inserted whitespace.
3000     Insertion after colons requires both this variable and
3001     `cperl-auto-newline-after-colon' set.
3002  `cperl-auto-newline-after-colon'
3003     Non-nil means automatically newline even after colons.
3004     Subject to `cperl-auto-newline' setting.
3005  `cperl-indent-level'
3006     Indentation of Perl statements within surrounding block.
3007     The surrounding block's indentation is the indentation
3008     of the line on which the open-brace appears.
3009  `cperl-continued-statement-offset'
3010     Extra indentation given to a substatement, such as the
3011     then-clause of an if, or body of a while, or just a statement continuation.
3012  `cperl-continued-brace-offset'
3013     Extra indentation given to a brace that starts a substatement.
3014     This is in addition to `cperl-continued-statement-offset'.
3015  `cperl-brace-offset'
3016     Extra indentation for line if it starts with an open brace.
3017  `cperl-brace-imaginary-offset'
3018     An open brace following other text is treated as if it the line started
3019     this far to the right of the actual line indentation.
3020  `cperl-label-offset'
3021     Extra indentation for line that is a label.
3022  `cperl-min-label-indent'
3023     Minimal indentation for line that is a label.
3024
3025 Settings for K&R and BSD indentation styles are
3026   `cperl-indent-level'                5    8
3027   `cperl-continued-statement-offset'  5    8
3028   `cperl-brace-offset'               -5   -8
3029   `cperl-label-offset'               -5   -8
3030
3031 CPerl knows several indentation styles, and may bulk set the
3032 corresponding variables.  Use \\[cperl-set-style] to do this.  Use
3033 \\[cperl-set-style-back] to restore the memorized preexisting values
3034 \(both available from menu).
3035
3036 If `cperl-indent-level' is 0, the statement after opening brace in
3037 column 0 is indented on
3038 `cperl-brace-offset'+`cperl-continued-statement-offset'.
3039
3040 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
3041 with no args.
3042
3043 DO NOT FORGET to read micro-docs (available from `Perl' menu)
3044 or as help on variables `cperl-tips', `cperl-problems',
3045 `cperl-non-problems', `cperl-praise', `cperl-speed'."
3046   (interactive)
3047   (kill-all-local-variables)
3048   (use-local-map cperl-mode-map)
3049   (if (cperl-val 'cperl-electric-linefeed)
3050       (progn
3051         (local-set-key "\C-J" 'cperl-linefeed)
3052         (local-set-key "\C-C\C-J" 'newline-and-indent)))
3053   (if (and
3054        (cperl-val 'cperl-clobber-lisp-bindings)
3055        (cperl-val 'cperl-info-on-command-no-prompt))
3056       (progn
3057         ;; don't clobber the backspace binding:
3058         (cperl-define-key "\C-hf" 'cperl-info-on-current-command [(control h) f])
3059         (cperl-define-key "\C-c\C-hf" 'cperl-info-on-command
3060                           [(control c) (control h) f])))
3061   (setq major-mode cperl-use-major-mode)
3062   (setq mode-name "CPerl")
3063   (if (not cperl-mode-abbrev-table)
3064       (let ((prev-a-c abbrevs-changed))
3065         (define-abbrev-table 'cperl-mode-abbrev-table '(
3066                 ("if" "if" cperl-electric-keyword 0)
3067                 ("elsif" "elsif" cperl-electric-keyword 0)
3068                 ("while" "while" cperl-electric-keyword 0)
3069                 ("until" "until" cperl-electric-keyword 0)
3070                 ("unless" "unless" cperl-electric-keyword 0)
3071                 ("else" "else" cperl-electric-else 0)
3072                 ("continue" "continue" cperl-electric-else 0)
3073                 ("for" "for" cperl-electric-keyword 0)
3074                 ("foreach" "foreach" cperl-electric-keyword 0)
3075                 ("formy" "formy" cperl-electric-keyword 0)
3076                 ("foreachmy" "foreachmy" cperl-electric-keyword 0)
3077                 ("do" "do" cperl-electric-keyword 0)
3078                 ("=pod" "=pod" cperl-electric-pod 0)
3079                 ("=over" "=over" cperl-electric-pod 0)
3080                 ("=head1" "=head1" cperl-electric-pod 0)
3081                 ("=head2" "=head2" cperl-electric-pod 0)
3082                 ("pod" "pod" cperl-electric-pod 0)
3083                 ("over" "over" cperl-electric-pod 0)
3084                 ("head1" "head1" cperl-electric-pod 0)
3085                 ("head2" "head2" cperl-electric-pod 0)))
3086         (setq abbrevs-changed prev-a-c)))
3087   (setq local-abbrev-table cperl-mode-abbrev-table)
3088   (if (cperl-val 'cperl-electric-keywords)
3089       (abbrev-mode 1))
3090   (set-syntax-table cperl-mode-syntax-table)
3091   ;; Until Emacs is multi-threaded, we do not actually need it local:
3092   (make-local-variable 'cperl-font-lock-multiline-start)
3093   (make-local-variable 'cperl-font-locking)
3094   (make-local-variable 'outline-regexp)
3095   ;; (setq outline-regexp imenu-example--function-name-regexp-perl)
3096   (setq outline-regexp cperl-outline-regexp)
3097   (make-local-variable 'outline-level)
3098   (setq outline-level 'cperl-outline-level)
3099   (make-local-variable 'paragraph-start)
3100   (setq paragraph-start (concat "^$\\|" page-delimiter))
3101   (make-local-variable 'paragraph-separate)
3102   (setq paragraph-separate paragraph-start)
3103   (make-local-variable 'paragraph-ignore-fill-prefix)
3104   (setq paragraph-ignore-fill-prefix t)
3105   (if cperl-xemacs-p
3106     (progn
3107       (make-local-variable 'paren-backwards-message)
3108       (set 'paren-backwards-message t)))
3109   (make-local-variable 'indent-line-function)
3110   (setq indent-line-function 'cperl-indent-line)
3111   (make-local-variable 'require-final-newline)
3112   (setq require-final-newline t)
3113   (make-local-variable 'comment-start)
3114   (setq comment-start "# ")
3115   (make-local-variable 'comment-end)
3116   (setq comment-end "")
3117   (make-local-variable 'comment-column)
3118   (setq comment-column cperl-comment-column)
3119   (make-local-variable 'comment-start-skip)
3120   (setq comment-start-skip "#+ *")
3121   (make-local-variable 'defun-prompt-regexp)
3122 ;;;       "[ \t]*sub"
3123 ;;;       (cperl-after-sub-regexp 'named nil) ; 8=name 11=proto 14=attr-start
3124 ;;;       cperl-maybe-white-and-comment-rex     ; 15=pre-block
3125   (setq defun-prompt-regexp
3126         (concat "[ \t]*sub"
3127                 (cperl-after-sub-regexp 'named 'attr-groups)
3128                 cperl-maybe-white-and-comment-rex))
3129   (make-local-variable 'comment-indent-function)
3130   (setq comment-indent-function 'cperl-comment-indent)
3131   (and (boundp 'fill-paragraph-function)
3132       (progn
3133         (make-local-variable 'fill-paragraph-function)
3134         (set 'fill-paragraph-function 'cperl-fill-paragraph)))
3135   (make-local-variable 'parse-sexp-ignore-comments)
3136   (setq parse-sexp-ignore-comments t)
3137   (make-local-variable 'indent-region-function)
3138   (setq indent-region-function 'cperl-indent-region)
3139   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
3140   (make-local-variable 'imenu-create-index-function)
3141   (setq imenu-create-index-function
3142         (function cperl-imenu--create-perl-index))
3143   (make-local-variable 'imenu-sort-function)
3144   (setq imenu-sort-function nil)
3145   (make-local-variable 'vc-rcs-header)
3146   (set 'vc-rcs-header cperl-vc-rcs-header)
3147   (make-local-variable 'vc-sccs-header)
3148   (set 'vc-sccs-header cperl-vc-sccs-header)
3149   ;; This one is obsolete...
3150   (make-local-variable 'vc-header-alist)
3151   (set 'vc-header-alist (or cperl-vc-header-alist ; Avoid warning
3152                             (` ((SCCS (, (car cperl-vc-sccs-header)))
3153                                      (RCS (, (car cperl-vc-rcs-header)))))))
3154   (cond ((boundp 'compilation-error-regexp-alist-alist);; xemacs 20.x
3155          (make-local-variable 'compilation-error-regexp-alist-alist)
3156          (set 'compilation-error-regexp-alist-alist
3157               (cons (cons 'cperl cperl-compilation-error-regexp-alist)
3158                     (symbol-value 'compilation-error-regexp-alist-alist)))
3159          (let ((f 'compilation-build-compilation-error-regexp-alist))
3160            (funcall f)))
3161         ((boundp 'compilation-error-regexp-alist);; xmeacs 19.x
3162          (make-local-variable 'compilation-error-regexp-alist)
3163          (set 'compilation-error-regexp-alist
3164                (cons cperl-compilation-error-regexp-alist
3165                      (symbol-value 'compilation-error-regexp-alist)))))
3166   (make-local-variable 'font-lock-defaults)
3167   (setq font-lock-defaults
3168         (cond
3169          ((string< emacs-version "19.30")
3170           '(perl-font-lock-keywords-2 nil nil ((?_ . "w"))))
3171          ((string< emacs-version "19.33") ; Which one to use?
3172           '((perl-font-lock-keywords
3173              perl-font-lock-keywords-1
3174              perl-font-lock-keywords-2) nil nil ((?_ . "w"))))
3175          (t
3176           '((cperl-load-font-lock-keywords
3177              cperl-load-font-lock-keywords-1
3178              cperl-load-font-lock-keywords-2) nil nil ((?_ . "w"))))))
3179   (make-local-variable 'cperl-syntax-state)
3180   (setq cperl-syntax-state nil)         ; reset syntaxification cache
3181   (if cperl-use-syntax-table-text-property
3182       (progn
3183         (make-local-variable 'parse-sexp-lookup-properties)
3184         ;; Do not introduce variable if not needed, we check it!
3185         (set 'parse-sexp-lookup-properties t)
3186         ;; Fix broken font-lock:
3187         (or (boundp 'font-lock-unfontify-region-function)
3188             (set 'font-lock-unfontify-region-function
3189                  'font-lock-default-unfontify-region))
3190         (unless cperl-xemacs-p          ; Our: just a plug for wrong font-lock
3191           (make-local-variable 'font-lock-unfontify-region-function)
3192           (set 'font-lock-unfontify-region-function ; not present with old Emacs
3193                'cperl-font-lock-unfontify-region-function))
3194         (make-local-variable 'cperl-syntax-done-to)
3195         (setq cperl-syntax-done-to nil) ; reset syntaxification cache
3196         ;; Another bug: unless font-lock-syntactic-keywords, font-lock
3197         ;;  ignores syntax-table text-property.  (t) is a hack
3198         ;;  to make font-lock think that font-lock-syntactic-keywords
3199         ;;  are defined
3200         (make-local-variable 'font-lock-syntactic-keywords)
3201         (setq font-lock-syntactic-keywords
3202               (if cperl-syntaxify-by-font-lock
3203                   '(t (cperl-fontify-syntaxically))
3204                 '(t)))))
3205   (if (boundp 'font-lock-multiline)     ; Newer font-lock; use its facilities
3206       (progn
3207         (setq cperl-font-lock-multiline t) ; Not localized...
3208         (set 'font-lock-multiline t)) ; not present with old Emacs; auto-local
3209     (make-local-variable 'font-lock-fontify-region-function)
3210     (set 'font-lock-fontify-region-function ; not present with old Emacs
3211          'cperl-font-lock-fontify-region-function))
3212   (make-local-variable 'font-lock-fontify-region-function)
3213   (set 'font-lock-fontify-region-function ; not present with old Emacs
3214        'cperl-font-lock-fontify-region-function)
3215   (make-local-variable 'cperl-old-style)
3216   (if (boundp 'normal-auto-fill-function) ; 19.33 and later
3217       (set (make-local-variable 'normal-auto-fill-function)
3218            'cperl-do-auto-fill)       ; RMS has it as #'cperl-do-auto-fill ???
3219     (or (fboundp 'cperl-old-auto-fill-mode)
3220         (progn
3221           (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
3222           (defun auto-fill-mode (&optional arg)
3223             (interactive "P")
3224             (eval '(cperl-old-auto-fill-mode arg)) ; Avoid a warning
3225             (and auto-fill-function (memq major-mode '(perl-mode cperl-mode))
3226                  (setq auto-fill-function 'cperl-do-auto-fill))))))
3227   (if (cperl-enable-font-lock)
3228       (if (cperl-val 'cperl-font-lock)
3229           (progn (or cperl-faces-init (cperl-init-faces))
3230                  (font-lock-mode 1))))
3231   (set (make-local-variable 'facemenu-add-face-function)
3232        'cperl-facemenu-add-face-function) ; XXXX What this guy is for???
3233   (and (boundp 'msb-menu-cond)
3234        (not cperl-msb-fixed)
3235        (cperl-msb-fix))
3236   (if (featurep 'easymenu)
3237       (easy-menu-add cperl-menu))       ; A NOP in RMS Emacs.
3238   (run-hooks 'cperl-mode-hook)
3239   (if cperl-hook-after-change
3240       (progn
3241         (make-local-hook 'after-change-functions)
3242         (add-hook 'after-change-functions 'cperl-after-change-function nil t)))
3243   ;; After hooks since fontification will break this
3244   (if cperl-pod-here-scan
3245       (or cperl-syntaxify-by-font-lock
3246        (progn (or cperl-faces-init (cperl-init-faces-weak))
3247               (cperl-find-pods-heres)))))
3248 \f
3249 ;; Fix for perldb - make default reasonable
3250 (defun cperl-db ()
3251   (interactive)
3252   (require 'gud)
3253   (perldb (read-from-minibuffer "Run perldb (like this): "
3254                                 (if (consp gud-perldb-history)
3255                                     (car gud-perldb-history)
3256                                   (concat "perl " ;;(file-name-nondirectory
3257                                           ;; I have problems
3258                                           ;; in OS/2
3259                                           ;; otherwise
3260                                           (buffer-file-name)))
3261                                 nil nil
3262                                 '(gud-perldb-history . 1))))
3263 \f
3264 (defun cperl-msb-fix ()
3265   ;; Adds perl files to msb menu, supposes that msb is already loaded
3266   (setq cperl-msb-fixed t)
3267   (let* ((l (length msb-menu-cond))
3268          (last (nth (1- l) msb-menu-cond))
3269          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
3270          (handle (1- (nth 1 last))))
3271     (setcdr precdr (list
3272                     (list
3273                      '(memq major-mode '(cperl-mode perl-mode))
3274                      handle
3275                      "Perl Files (%d)")
3276                     last))))
3277 \f
3278 ;; This is used by indent-for-comment
3279 ;; to decide how much to indent a comment in CPerl code
3280 ;; based on its context.  Do fallback if comment is found wrong.
3281
3282 (defvar cperl-wrong-comment)
3283 (defvar cperl-st-cfence '(14))          ; Comment-fence
3284 (defvar cperl-st-sfence '(15))          ; String-fence
3285 (defvar cperl-st-punct '(1))
3286 (defvar cperl-st-word '(2))
3287 (defvar cperl-st-bra '(4 . ?\>))
3288 (defvar cperl-st-ket '(5 . ?\<))
3289
3290
3291 (defun cperl-comment-indent ()
3292   (let ((p (point)) (c (current-column)) was phony)
3293     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
3294       ;; Wrong comment found
3295       (save-excursion
3296         (setq was (cperl-to-comment-or-eol)
3297               phony (eq (get-text-property (point) 'syntax-table)
3298                         cperl-st-cfence))
3299         (if phony
3300             (progn
3301               (re-search-forward "#\\|$") ; Hmm, what about embedded #?
3302               (if (eq (preceding-char) ?\#)
3303                   (forward-char -1))
3304               (setq was nil)))
3305         (if (= (point) p)
3306             (progn
3307               (skip-chars-backward " \t")
3308               (max (1+ (current-column)) ; Else indent at comment column
3309                    comment-column))
3310           (if was nil
3311             (insert comment-start)
3312             (backward-char (length comment-start)))
3313           (setq cperl-wrong-comment t)
3314           (cperl-make-indent comment-column 1 'keep)    ; Indent minimum 1
3315           c)))))                        ; except leave at least one space.
3316
3317 ;;;(defun cperl-comment-indent-fallback ()
3318 ;;;  "Is called if the standard comment-search procedure fails.
3319 ;;;Point is at start of real comment."
3320 ;;;  (let ((c (current-column)) target cnt prevc)
3321 ;;;    (if (= c comment-column) nil
3322 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
3323 ;;;      (setq target (max (1+ (setq prevc
3324 ;;;                          (current-column))) ; Else indent at comment column
3325 ;;;                comment-column))
3326 ;;;      (if (= c comment-column) nil
3327 ;;;     (delete-backward-char cnt)
3328 ;;;     (while (< prevc target)
3329 ;;;       (insert "\t")
3330 ;;;       (setq prevc (current-column)))
3331 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
3332 ;;;     (while (< prevc target)
3333 ;;;       (insert " ")
3334 ;;;       (setq prevc (current-column)))))))
3335
3336 (defun cperl-indent-for-comment ()
3337   "Substitute for `indent-for-comment' in CPerl."
3338   (interactive)
3339   (let (cperl-wrong-comment)
3340     (indent-for-comment)
3341     (if cperl-wrong-comment             ; set by `cperl-comment-indent'
3342         (progn (cperl-to-comment-or-eol)
3343                (forward-char (length comment-start))))))
3344
3345 (defun cperl-comment-region (b e arg)
3346   "Comment or uncomment each line in the region in CPerl mode.
3347 See `comment-region'."
3348   (interactive "r\np")
3349   (let ((comment-start "#"))
3350     (comment-region b e arg)))
3351
3352 (defun cperl-uncomment-region (b e arg)
3353   "Uncomment or comment each line in the region in CPerl mode.
3354 See `comment-region'."
3355   (interactive "r\np")
3356   (let ((comment-start "#"))
3357     (comment-region b e (- arg))))
3358
3359 (defvar cperl-brace-recursing nil)
3360
3361 (defun cperl-electric-brace (arg &optional only-before)
3362   "Insert character and correct line's indentation.
3363 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
3364 place (even in empty line), but not after.  If after \")\" and the inserted
3365 char is \"{\", insert extra newline before only if
3366 `cperl-extra-newline-before-brace'."
3367   (interactive "P")
3368   (let (insertpos
3369         (other-end (if (and cperl-electric-parens-mark
3370                             (cperl-mark-active)
3371                             (< (mark) (point)))
3372                        (mark)
3373                      nil)))
3374     (if (and other-end
3375              (not cperl-brace-recursing)
3376              (cperl-val 'cperl-electric-parens)
3377              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point)))
3378         ;; Need to insert a matching pair
3379         (progn
3380           (save-excursion
3381             (setq insertpos (point-marker))
3382             (goto-char other-end)
3383             (setq last-command-char ?\{)
3384             (cperl-electric-lbrace arg insertpos))
3385           (forward-char 1))
3386       ;; Check whether we close something "usual" with `}'
3387       (if (and (eq last-command-char ?\})
3388                (not
3389                 (condition-case nil
3390                     (save-excursion
3391                       (up-list (- (prefix-numeric-value arg)))
3392                       ;;(cperl-after-block-p (point-min))
3393                       (or (cperl-after-expr-p nil "{;)")
3394                           ;; after sub, else, continue
3395                           (cperl-after-block-p nil 'pre)))
3396                   (error nil))))
3397           ;; Just insert the guy
3398           (self-insert-command (prefix-numeric-value arg))
3399         (if (and (not arg)              ; No args, end (of empty line or auto)
3400                  (eolp)
3401                  (or (and (null only-before)
3402                           (save-excursion
3403                             (skip-chars-backward " \t")
3404                             (bolp)))
3405                      (and (eq last-command-char ?\{) ; Do not insert newline
3406                           ;; if after ")" and `cperl-extra-newline-before-brace'
3407                           ;; is nil, do not insert extra newline.
3408                           (not cperl-extra-newline-before-brace)
3409                           (save-excursion
3410                             (skip-chars-backward " \t")
3411                             (eq (preceding-char) ?\))))
3412                      (if cperl-auto-newline
3413                          (progn (cperl-indent-line) (newline) t) nil)))
3414             (progn
3415               (self-insert-command (prefix-numeric-value arg))
3416               (cperl-indent-line)
3417               (if cperl-auto-newline
3418                   (setq insertpos (1- (point))))
3419               (if (and cperl-auto-newline (null only-before))
3420                   (progn
3421                     (newline)
3422                     (cperl-indent-line)))
3423               (save-excursion
3424                 (if insertpos (progn (goto-char insertpos)
3425                                      (search-forward (make-string
3426                                                       1 last-command-char))
3427                                      (setq insertpos (1- (point)))))
3428                 (delete-char -1))))
3429         (if insertpos
3430             (save-excursion
3431               (goto-char insertpos)
3432               (self-insert-command (prefix-numeric-value arg)))
3433           (self-insert-command (prefix-numeric-value arg)))))))
3434
3435 (defun cperl-electric-lbrace (arg &optional end)
3436   "Insert character, correct line's indentation, correct quoting by space."
3437   (interactive "P")
3438   (let ((cperl-brace-recursing t)
3439         (cperl-auto-newline cperl-auto-newline)
3440         (other-end (or end
3441                        (if (and cperl-electric-parens-mark
3442                                 (cperl-mark-active)
3443                                 (> (mark) (point)))
3444                            (save-excursion
3445                              (goto-char (mark))
3446                              (point-marker))
3447                          nil)))
3448         pos after)
3449     (and (cperl-val 'cperl-electric-lbrace-space)
3450          (eq (preceding-char) ?$)
3451          (save-excursion
3452            (skip-chars-backward "$")
3453            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
3454          (insert ?\ ))
3455     ;; Check whether we are in comment
3456     (if (and
3457          (save-excursion
3458            (beginning-of-line)
3459            (not (looking-at "[ \t]*#")))
3460          (cperl-after-expr-p nil "{;)"))
3461         nil
3462       (setq cperl-auto-newline nil))
3463     (cperl-electric-brace arg)
3464     (and (cperl-val 'cperl-electric-parens)
3465          (eq last-command-char ?{)
3466          (memq last-command-char
3467                (append cperl-electric-parens-string nil))
3468          (or (if other-end (goto-char (marker-position other-end)))
3469              t)
3470          (setq last-command-char ?} pos (point))
3471          (progn (cperl-electric-brace arg t)
3472                 (goto-char pos)))))
3473
3474 (defun cperl-electric-paren (arg)
3475   "Insert an opening parenthesis or a matching pair of parentheses.
3476 See `cperl-electric-parens'."
3477   (interactive "P")
3478   (let ((beg (save-excursion (beginning-of-line) (point)))
3479         (other-end (if (and cperl-electric-parens-mark
3480                             (cperl-mark-active)
3481                             (> (mark) (point)))
3482                        (save-excursion
3483                          (goto-char (mark))
3484                          (point-marker))
3485                      nil)))
3486     (if (and (cperl-val 'cperl-electric-parens)
3487              (memq last-command-char
3488                    (append cperl-electric-parens-string nil))
3489              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
3490              ;;(not (save-excursion (search-backward "#" beg t)))
3491              (if (eq last-command-char ?<)
3492                  (progn
3493                    (and abbrev-mode ; later it is too late, may be after `for'
3494                         (expand-abbrev))
3495                    (cperl-after-expr-p nil "{;(,:="))
3496                1))
3497         (progn
3498           (self-insert-command (prefix-numeric-value arg))
3499           (if other-end (goto-char (marker-position other-end)))
3500           (insert (make-string
3501                    (prefix-numeric-value arg)
3502                    (cdr (assoc last-command-char '((?{ .?})
3503                                                    (?[ . ?])
3504                                                    (?( . ?))
3505                                                    (?< . ?>))))))
3506           (forward-char (- (prefix-numeric-value arg))))
3507       (self-insert-command (prefix-numeric-value arg)))))
3508
3509 (defun cperl-electric-rparen (arg)
3510   "Insert a matching pair of parentheses if marking is active.
3511 If not, or if we are not at the end of marking range, would self-insert.
3512 Affected by `cperl-electric-parens'."
3513   (interactive "P")
3514   (let ((beg (save-excursion (beginning-of-line) (point)))
3515         (other-end (if (and cperl-electric-parens-mark
3516                             (cperl-val 'cperl-electric-parens)
3517                             (memq last-command-char
3518                                   (append cperl-electric-parens-string nil))
3519                             (cperl-mark-active)
3520                             (< (mark) (point)))
3521                        (mark)
3522                      nil))
3523         p)
3524     (if (and other-end
3525              (cperl-val 'cperl-electric-parens)
3526              (memq last-command-char '( ?\) ?\] ?\} ?\> ))
3527              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
3528              ;;(not (save-excursion (search-backward "#" beg t)))
3529              )
3530         (progn
3531           (self-insert-command (prefix-numeric-value arg))
3532           (setq p (point))
3533           (if other-end (goto-char other-end))
3534           (insert (make-string
3535                    (prefix-numeric-value arg)
3536                    (cdr (assoc last-command-char '((?\} . ?\{)
3537                                                    (?\] . ?\[)
3538                                                    (?\) . ?\()
3539                                                    (?\> . ?\<))))))
3540           (goto-char (1+ p)))
3541       (self-insert-command (prefix-numeric-value arg)))))
3542
3543 (defun cperl-electric-keyword ()
3544   "Insert a construction appropriate after a keyword.
3545 Help message may be switched off by setting `cperl-message-electric-keyword'
3546 to nil."
3547   (let ((beg (save-excursion (beginning-of-line) (point)))
3548         (dollar (and (eq last-command-char ?$)
3549                      (eq this-command 'self-insert-command)))
3550         (delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3551                      (memq this-command '(self-insert-command newline))))
3552         my do)
3553     (and (save-excursion
3554            (condition-case nil
3555                (progn
3556                  (backward-sexp 1)
3557                  (setq do (looking-at "do\\>")))
3558              (error nil))
3559            (cperl-after-expr-p nil "{;:"))
3560          (save-excursion
3561            (not
3562             (re-search-backward
3563              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3564              beg t)))
3565          (save-excursion (or (not (re-search-backward "^=" nil t))
3566                              (or
3567                               (looking-at "=cut")
3568                               (and cperl-use-syntax-table-text-property
3569                                    (not (eq (get-text-property (point)
3570                                                                'syntax-type)
3571                                             'pod))))))
3572          (save-excursion (forward-sexp -1)
3573                          (not (memq (following-char) (append "$@%&*" nil))))
3574          (progn
3575            (and (eq (preceding-char) ?y)
3576                 (progn                  ; "foreachmy"
3577                   (forward-char -2)
3578                   (insert " ")
3579                   (forward-char 2)
3580                   (setq my t dollar t
3581                         delete
3582                         (memq this-command '(self-insert-command newline)))))
3583            (and dollar (insert " $"))
3584            (cperl-indent-line)
3585            ;;(insert " () {\n}")
3586            (cond
3587             (cperl-extra-newline-before-brace
3588              (insert (if do "\n" " ()\n"))
3589              (insert "{")
3590              (cperl-indent-line)
3591              (insert "\n")
3592              (cperl-indent-line)
3593              (insert "\n}")
3594              (and do (insert " while ();")))
3595             (t
3596              (insert (if do " {\n} while ();" " () {\n}"))))
3597            (or (looking-at "[ \t]\\|$") (insert " "))
3598            (cperl-indent-line)
3599            (if dollar (progn (search-backward "$")
3600                              (if my
3601                                  (forward-char 1)
3602                                (delete-char 1)))
3603              (search-backward ")")
3604              (if (eq last-command-char ?\()
3605                  (progn                 ; Avoid "if (())"
3606                    (delete-backward-char 1)
3607                    (delete-backward-char -1))))
3608            (if delete
3609                (cperl-putback-char cperl-del-back-ch))
3610            (if cperl-message-electric-keyword
3611                (message "Precede char by C-q to avoid expansion"))))))
3612
3613 (defun cperl-ensure-newlines (n &optional pos)
3614   "Make sure there are N newlines after the point."
3615   (or pos (setq pos (point)))
3616   (if (looking-at "\n")
3617       (forward-char 1)
3618     (insert "\n"))
3619   (if (> n 1)
3620       (cperl-ensure-newlines (1- n) pos)
3621     (goto-char pos)))
3622
3623 (defun cperl-electric-pod ()
3624   "Insert a POD chunk appropriate after a =POD directive."
3625   (let ((delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3626                      (memq this-command '(self-insert-command newline))))
3627         head1 notlast name p really-delete over)
3628     (and (save-excursion
3629            (forward-word -1)
3630            (and
3631             (eq (preceding-char) ?=)
3632             (progn
3633               (setq head1 (looking-at "head1\\>[ \t]*$"))
3634               (setq over (and (looking-at "over\\>[ \t]*$")
3635                               (not (looking-at "over[ \t]*\n\n\n*=item\\>"))))
3636               (forward-char -1)
3637               (bolp))
3638             (or
3639              (get-text-property (point) 'in-pod)
3640              (cperl-after-expr-p nil "{;:")
3641              (and (re-search-backward "\\(\\`\n?\\|^\n\\)=\\sw+" (point-min) t)
3642                   (not (looking-at "\n*=cut"))
3643                   (or (not cperl-use-syntax-table-text-property)
3644                       (eq (get-text-property (point) 'syntax-type) 'pod))))))
3645          (progn
3646            (save-excursion
3647              (setq notlast (re-search-forward "^\n=" nil t)))
3648            (or notlast
3649                (progn
3650                  (insert "\n\n=cut")
3651                  (cperl-ensure-newlines 2)
3652                  (forward-word -2)
3653                  (if (and head1
3654                           (not
3655                            (save-excursion
3656                              (forward-char -1)
3657                              (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\>"
3658                                                  nil t)))) ; Only one
3659                      (progn
3660                        (forward-word 1)
3661                        (setq name (file-name-sans-extension
3662                                    (file-name-nondirectory (buffer-file-name)))
3663                              p (point))
3664                        (insert " NAME\n\n" name
3665                                " - \n\n=head1 SYNOPSIS\n\n\n\n"
3666                                "=head1 DESCRIPTION")
3667                        (cperl-ensure-newlines 4)
3668                        (goto-char p)
3669                        (forward-word 2)
3670                        (end-of-line)
3671                        (setq really-delete t))
3672                    (forward-word 1))))
3673            (if over
3674                (progn
3675                  (setq p (point))
3676                  (insert "\n\n=item \n\n\n\n"
3677                          "=back")
3678                  (cperl-ensure-newlines 2)
3679                  (goto-char p)
3680                  (forward-word 1)
3681                  (end-of-line)
3682                  (setq really-delete t)))
3683            (if (and delete really-delete)
3684                (cperl-putback-char cperl-del-back-ch))))))
3685
3686 (defun cperl-electric-else ()
3687   "Insert a construction appropriate after a keyword.
3688 Help message may be switched off by setting `cperl-message-electric-keyword'
3689 to nil."
3690   (let ((beg (save-excursion (beginning-of-line) (point))))
3691     (and (save-excursion
3692            (backward-sexp 1)
3693            (cperl-after-expr-p nil "{;:"))
3694          (save-excursion
3695            (not
3696             (re-search-backward
3697              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3698              beg t)))
3699          (save-excursion (or (not (re-search-backward "^=" nil t))
3700                              (looking-at "=cut")
3701                              (and cperl-use-syntax-table-text-property
3702                                   (not (eq (get-text-property (point)
3703                                                               'syntax-type)
3704                                            'pod)))))
3705          (progn
3706            (cperl-indent-line)
3707            ;;(insert " {\n\n}")
3708            (cond
3709             (cperl-extra-newline-before-brace
3710              (insert "\n")
3711              (insert "{")
3712              (cperl-indent-line)
3713              (insert "\n\n}"))
3714             (t
3715              (insert " {\n\n}")))
3716            (or (looking-at "[ \t]\\|$") (insert " "))
3717            (cperl-indent-line)
3718            (forward-line -1)
3719            (cperl-indent-line)
3720            (cperl-putback-char cperl-del-back-ch)
3721            (setq this-command 'cperl-electric-else)
3722            (if cperl-message-electric-keyword
3723                (message "Precede char by C-q to avoid expansion"))))))
3724
3725 (defun cperl-linefeed ()
3726   "Go to end of line, open a new line and indent appropriately.
3727 If in POD, insert appropriate lines."
3728   (interactive)
3729   (let ((beg (save-excursion (beginning-of-line) (point)))
3730         (end (save-excursion (end-of-line) (point)))
3731         (pos (point)) start over cut res)
3732     (if (and                            ; Check if we need to split:
3733                                         ; i.e., on a boundary and inside "{...}"
3734          (save-excursion (cperl-to-comment-or-eol)
3735                          (>= (point) pos)) ; Not in a comment
3736          (or (save-excursion
3737                (skip-chars-backward " \t" beg)
3738                (forward-char -1)
3739                (looking-at "[;{]"))     ; After { or ; + spaces
3740              (looking-at "[ \t]*}")     ; Before }
3741              (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
3742          (save-excursion
3743            (and
3744             (eq (car (parse-partial-sexp pos end -1)) -1)
3745                                         ; Leave the level of parens
3746             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
3747                                         ; Are at end
3748             (cperl-after-block-p (point-min))
3749             (progn
3750               (backward-sexp 1)
3751               (setq start (point-marker))
3752               (<= start pos)))))        ; Redundant?  Are after the
3753                                         ; start of parens group.
3754         (progn
3755           (skip-chars-backward " \t")
3756           (or (memq (preceding-char) (append ";{" nil))
3757               (insert ";"))
3758           (insert "\n")
3759           (forward-line -1)
3760           (cperl-indent-line)
3761           (goto-char start)
3762           (or (looking-at "{[ \t]*$")   ; If there is a statement
3763                                         ; before, move it to separate line
3764               (progn
3765                 (forward-char 1)
3766                 (insert "\n")
3767                 (cperl-indent-line)))
3768           (forward-line 1)              ; We are on the target line
3769           (cperl-indent-line)
3770           (beginning-of-line)
3771           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
3772                                         ; after, move it to separate line
3773               (progn
3774                 (end-of-line)
3775                 (search-backward "}" beg)
3776                 (skip-chars-backward " \t")
3777                 (or (memq (preceding-char) (append ";{" nil))
3778                     (insert ";"))
3779                 (insert "\n")
3780                 (cperl-indent-line)
3781                 (forward-line -1)))
3782           (forward-line -1)             ; We are on the line before target
3783           (end-of-line)
3784           (newline-and-indent))
3785       (end-of-line)                     ; else - no splitting
3786       (cond
3787        ((and (looking-at "\n[ \t]*{$")
3788              (save-excursion
3789                (skip-chars-backward " \t")
3790                (eq (preceding-char) ?\)))) ; Probably if () {} group
3791                                         ; with an extra newline.
3792         (forward-line 2)
3793         (cperl-indent-line))
3794        ((save-excursion                 ; In POD header
3795           (forward-paragraph -1)
3796           ;; (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\b")
3797           ;; We are after \n now, so look for the rest
3798           (if (looking-at "\\(\\`\n?\\|\n\\)=\\sw+")
3799               (progn
3800                 (setq cut (looking-at "\\(\\`\n?\\|\n\\)=cut\\>"))
3801                 (setq over (looking-at "\\(\\`\n?\\|\n\\)=over\\>"))
3802                 t)))
3803         (if (and over
3804                  (progn
3805                    (forward-paragraph -1)
3806                    (forward-word 1)
3807                    (setq pos (point))
3808                    (setq cut (buffer-substring (point)
3809                                                (save-excursion
3810                                                  (end-of-line)
3811                                                  (point))))
3812                    (delete-char (- (save-excursion (end-of-line) (point))
3813                                    (point)))
3814                    (setq res (expand-abbrev))
3815                    (save-excursion
3816                      (goto-char pos)
3817                      (insert cut))
3818                    res))
3819             nil
3820           (cperl-ensure-newlines (if cut 2 4))
3821           (forward-line 2)))
3822        ((get-text-property (point) 'in-pod) ; In POD section
3823         (cperl-ensure-newlines 4)
3824         (forward-line 2))
3825        ((looking-at "\n[ \t]*$")        ; Next line is empty - use it.
3826         (forward-line 1)
3827         (cperl-indent-line))
3828        (t
3829         (newline-and-indent))))))
3830
3831 (defun cperl-electric-semi (arg)
3832   "Insert character and correct line's indentation."
3833   (interactive "P")
3834   (if cperl-auto-newline
3835       (cperl-electric-terminator arg)
3836     (self-insert-command (prefix-numeric-value arg))
3837     (if cperl-autoindent-on-semi
3838         (cperl-indent-line))))
3839
3840 (defun cperl-electric-terminator (arg)
3841   "Insert character and correct line's indentation."
3842   (interactive "P")
3843   (let ((end (point))
3844         (auto (and cperl-auto-newline
3845                    (or (not (eq last-command-char ?:))
3846                        cperl-auto-newline-after-colon)))
3847         insertpos)
3848     (if (and ;;(not arg)
3849              (eolp)
3850              (not (save-excursion
3851                     (beginning-of-line)
3852                     (skip-chars-forward " \t")
3853                     (or
3854                      ;; Ignore in comment lines
3855                      (= (following-char) ?#)
3856                      ;; Colon is special only after a label
3857                      ;; So quickly rule out most other uses of colon
3858                      ;; and do no indentation for them.
3859                      (and (eq last-command-char ?:)
3860                           (save-excursion
3861                             (forward-word 1)
3862                             (skip-chars-forward " \t")
3863                             (and (< (point) end)
3864                                  (progn (goto-char (- end 1))
3865                                         (not (looking-at ":"))))))
3866                      (progn
3867                        (beginning-of-defun)
3868                        (let ((pps (parse-partial-sexp (point) end)))
3869                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
3870         (progn
3871           (self-insert-command (prefix-numeric-value arg))
3872           ;;(forward-char -1)
3873           (if auto (setq insertpos (point-marker)))
3874           ;;(forward-char 1)
3875           (cperl-indent-line)
3876           (if auto
3877               (progn
3878                 (newline)
3879                 (cperl-indent-line)))
3880           (save-excursion
3881             (if insertpos (goto-char (1- (marker-position insertpos)))
3882               (forward-char -1))
3883             (delete-char 1))))
3884     (if insertpos
3885         (save-excursion
3886           (goto-char insertpos)
3887           (self-insert-command (prefix-numeric-value arg)))
3888       (self-insert-command (prefix-numeric-value arg)))))
3889
3890 (defun cperl-electric-backspace (arg)
3891   "Backspace, or remove the whitespace around the point inserted by an electric
3892 key.  Will untabivy if `cperl-electric-backspace-untabify' is non-nil."
3893   (interactive "p")
3894   (if (and cperl-auto-newline
3895            (memq last-command '(cperl-electric-semi
3896                                 cperl-electric-terminator
3897                                 cperl-electric-lbrace))
3898            (memq (preceding-char) '(?\  ?\t ?\n)))
3899       (let (p)
3900         (if (eq last-command 'cperl-electric-lbrace)
3901             (skip-chars-forward " \t\n"))
3902         (setq p (point))
3903         (skip-chars-backward " \t\n")
3904         (delete-region (point) p))
3905     (and (eq last-command 'cperl-electric-else)
3906          ;; We are removing the whitespace *inside* cperl-electric-else
3907          (setq this-command 'cperl-electric-else-really))
3908     (if (and cperl-auto-newline
3909              (eq last-command 'cperl-electric-else-really)
3910              (memq (preceding-char) '(?\  ?\t ?\n)))
3911         (let (p)
3912           (skip-chars-forward " \t\n")
3913           (setq p (point))
3914           (skip-chars-backward " \t\n")
3915           (delete-region (point) p))
3916       (if cperl-electric-backspace-untabify
3917           (backward-delete-char-untabify arg)
3918         (delete-backward-char arg)))))
3919
3920 (defun cperl-inside-parens-p ()         ;; NOT USED????
3921   (condition-case ()
3922       (save-excursion
3923         (save-restriction
3924           (narrow-to-region (point)
3925                             (progn (beginning-of-defun) (point)))
3926           (goto-char (point-max))
3927           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
3928     (error nil)))
3929 \f
3930 (defun cperl-indent-command (&optional whole-exp)
3931   "Indent current line as Perl code, or in some cases insert a tab character.
3932 If `cperl-tab-always-indent' is non-nil (the default), always indent current
3933 line.  Otherwise, indent the current line only if point is at the left margin
3934 or in the line's indentation; otherwise insert a tab.
3935
3936 A numeric argument, regardless of its value,
3937 means indent rigidly all the lines of the expression starting after point
3938 so that this line becomes properly indented.
3939 The relative indentation among the lines of the expression are preserved."
3940   (interactive "P")
3941   (cperl-update-syntaxification (point) (point))
3942   (if whole-exp
3943       ;; If arg, always indent this line as Perl
3944       ;; and shift remaining lines of expression the same amount.
3945       (let ((shift-amt (cperl-indent-line))
3946             beg end)
3947         (save-excursion
3948           (if cperl-tab-always-indent
3949               (beginning-of-line))
3950           (setq beg (point))
3951           (forward-sexp 1)
3952           (setq end (point))
3953           (goto-char beg)
3954           (forward-line 1)
3955           (setq beg (point)))
3956         (if (and shift-amt (> end beg))
3957             (indent-code-rigidly beg end shift-amt "#")))
3958     (if (and (not cperl-tab-always-indent)
3959              (save-excursion
3960                (skip-chars-backward " \t")
3961                (not (bolp))))
3962         (insert-tab)
3963       (cperl-indent-line))))
3964
3965 (defun cperl-indent-line (&optional parse-data)
3966   "Indent current line as Perl code.
3967 Return the amount the indentation changed by."
3968   (let ((case-fold-search nil)
3969         (pos (- (point-max) (point)))
3970         indent i beg shift-amt)
3971     (setq indent (cperl-calculate-indent parse-data)
3972           i indent)
3973     (beginning-of-line)
3974     (setq beg (point))
3975     (cond ((or (eq indent nil) (eq indent t))
3976            (setq indent (current-indentation) i nil))
3977           ;;((eq indent t)    ; Never?
3978           ;; (setq indent (cperl-calculate-indent-within-comment)))
3979           ;;((looking-at "[ \t]*#")
3980           ;; (setq indent 0))
3981           (t
3982            (skip-chars-forward " \t")
3983            (if (listp indent) (setq indent (car indent)))
3984            (cond ((looking-at "[A-Za-z_][A-Za-z_0-9]*:[^:]")
3985                   (and (> indent 0)
3986                        (setq indent (max cperl-min-label-indent
3987                                          (+ indent cperl-label-offset)))))
3988                  ((= (following-char) ?})
3989                   (setq indent (- indent cperl-indent-level)))
3990                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
3991                   (setq indent (+ indent cperl-close-paren-offset)))
3992                  ((= (following-char) ?{)
3993                   (setq indent (+ indent cperl-brace-offset))))))
3994     (skip-chars-forward " \t")
3995     (setq shift-amt (and i (- indent (current-column))))
3996     (if (or (not shift-amt)
3997             (zerop shift-amt))
3998         (if (> (- (point-max) pos) (point))
3999             (goto-char (- (point-max) pos)))
4000       ;;;(delete-region beg (point))
4001       ;;;(indent-to indent)
4002       (cperl-make-indent indent)
4003       ;; If initial point was within line's indentation,
4004       ;; position after the indentation.  Else stay at same point in text.
4005       (if (> (- (point-max) pos) (point))
4006           (goto-char (- (point-max) pos))))
4007     shift-amt))
4008
4009 (defun cperl-after-label ()
4010   ;; Returns true if the point is after label.  Does not do save-excursion.
4011   (and (eq (preceding-char) ?:)
4012        (memq (char-syntax (char-after (- (point) 2)))
4013              '(?w ?_))
4014        (progn
4015          (backward-sexp)
4016          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))
4017
4018 (defun cperl-get-state (&optional parse-start start-state)
4019   ;; returns list (START STATE DEPTH PRESTART),
4020   ;; START is a good place to start parsing, or equal to
4021   ;; PARSE-START if preset,
4022   ;; STATE is what is returned by `parse-partial-sexp'.
4023   ;; DEPTH is true is we are immediately after end of block
4024   ;; which contains START.
4025   ;; PRESTART is the position basing on which START was found.
4026   (save-excursion
4027     (let ((start-point (point)) depth state start prestart)
4028       (if (and parse-start
4029                (<= parse-start start-point))
4030           (goto-char parse-start)
4031         (beginning-of-defun)
4032         (setq start-state nil))
4033       (setq prestart (point))
4034       (if start-state nil
4035         ;; Try to go out, if sub is not on the outermost level
4036         (while (< (point) start-point)
4037           (setq start (point) parse-start start depth nil
4038                 state (parse-partial-sexp start start-point -1))
4039           (if (> (car state) -1) nil
4040             ;; The current line could start like }}}, so the indentation
4041             ;; corresponds to a different level than what we reached
4042             (setq depth t)
4043             (beginning-of-line 2)))     ; Go to the next line.
4044         (if start (goto-char start)))   ; Not at the start of file
4045       (setq start (point))
4046       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
4047       (list start state depth prestart))))
4048
4049 (defvar cperl-look-for-prop '((pod in-pod) (here-doc-delim here-doc-group)))
4050
4051 (defun cperl-beginning-of-property (p prop &optional lim)
4052   "Given that P has a property PROP, find where the property starts.
4053 Will not look before LIM."
4054   ;;; XXXX What to do at point-max???
4055   (or (previous-single-property-change (cperl-1+ p) prop lim)
4056       (point-min))
4057 ;;;  (cond ((eq p (point-min))
4058 ;;;      p)
4059 ;;;     ((and lim (<= p lim))
4060 ;;;      p)
4061 ;;;     ((not (get-text-property (1- p) prop))
4062 ;;;      p)
4063 ;;;     (t (or (previous-single-property-change p look-prop lim)
4064 ;;;            (point-min))))
4065   )
4066
4067 (defun cperl-calculate-indent (&optional parse-data) ; was parse-start
4068   "Return appropriate indentation for current line as Perl code.
4069 In usual case returns an integer: the column to indent to.
4070 Returns nil if line starts inside a string, t if in a comment.
4071
4072 Will not correct the indentation for labels, but will correct it for braces
4073 and closing parentheses and brackets."
4074   (cperl-update-syntaxification (point) (point))
4075   (save-excursion
4076     (if (or
4077          (and (memq (get-text-property (point) 'syntax-type)
4078                     '(pod here-doc here-doc-delim format))
4079               (not (get-text-property (point) 'indentable)))
4080          ;; before start of POD - whitespace found since do not have 'pod!
4081          (and (looking-at "[ \t]*\n=")
4082               (error "Spaces before POD section!"))
4083          (and (not cperl-indent-left-aligned-comments)
4084               (looking-at "^#")))
4085         nil
4086       (beginning-of-line)
4087       (let* ((indent-point (point))
4088              (char-after-pos (save-excursion
4089                                (skip-chars-forward " \t")
4090                                (point)))
4091              (char-after (char-after char-after-pos))
4092              (in-pod (get-text-property (point) 'in-pod))
4093              (pre-indent-point (point))
4094              p prop look-prop is-block delim)
4095         (cond
4096          (in-pod
4097           ;; In the verbatim part, probably code example.  What to do???
4098           )
4099          (t
4100           (save-excursion
4101             ;; Not in POD
4102             (cperl-backward-to-noncomment nil)
4103             (setq p (max (point-min) (1- (point)))
4104                   prop (get-text-property p 'syntax-type)
4105                   look-prop (or (nth 1 (assoc prop cperl-look-for-prop))
4106                                 'syntax-type))
4107             (if (memq prop '(pod here-doc format here-doc-delim))
4108                 (progn
4109                   (goto-char (cperl-beginning-of-property p look-prop))
4110                   (beginning-of-line)
4111                   (setq pre-indent-point (point)))))))
4112         (goto-char pre-indent-point)
4113         (let* ((case-fold-search nil)
4114                (s-s (cperl-get-state (car parse-data) (nth 1 parse-data)))
4115                (start (or (nth 2 parse-data)
4116                           (nth 0 s-s)))
4117                (state (nth 1 s-s))
4118                (containing-sexp (car (cdr state)))
4119                old-indent)
4120           (if (and
4121                ;;containing-sexp                ;; We are buggy at toplevel :-(
4122                parse-data)
4123               (progn
4124                 (setcar parse-data pre-indent-point)
4125                 (setcar (cdr parse-data) state)
4126                 (or (nth 2 parse-data)
4127                     (setcar (cddr parse-data) start))
4128                 ;; Before this point: end of statement
4129                 (setq old-indent (nth 3 parse-data))))
4130           (cond ((get-text-property (point) 'indentable)
4131                  ;; indent to "after" the surrounding open
4132                  ;; (same offset as `cperl-beautify-regexp-piece'),
4133                  ;; skip blanks if we do not close the expression.
4134                  (setq delim            ; We do not close the expression
4135                        (get-text-property
4136                         (cperl-1+ char-after-pos) 'indentable)
4137                        p (1+ (cperl-beginning-of-property
4138                               (point) 'indentable))
4139                        is-block         ; misused for: preceeding line in REx
4140                        (save-excursion  ; Find preceeding line
4141                          (cperl-backward-to-noncomment p)
4142                          (beginning-of-line)
4143                          (if (<= (point) p)
4144                              (progn     ; get indent from the first line
4145                                (goto-char p)
4146                                (skip-chars-forward " \t")
4147                                (if (memq (char-after (point))
4148                                          (append "#\n" nil))
4149                                    nil  ; Can't use intentation of this line...
4150                                  (point)))
4151                            (skip-chars-forward " \t")
4152                            (point)))
4153                        prop (parse-partial-sexp p char-after-pos))
4154                  (cond ((not delim)
4155                         (goto-char p)   ; beginning of REx etc
4156                         (1- (current-column))) ; End the REx, ignore is-block
4157                        (is-block
4158                         ;; Indent as the level after closing parens
4159                         (goto-char char-after-pos)
4160                         (skip-chars-forward " \t)")
4161                         (setq char-after-pos (point))
4162                         (goto-char is-block)
4163                         (skip-chars-forward " \t)")
4164                         (setq p (parse-partial-sexp (point) char-after-pos))
4165                         (goto-char is-block)
4166                         (+ (* (nth 0 p)
4167                               (or cperl-regexp-indent-step cperl-indent-level))
4168                            (cond ((eq char-after ?\) )
4169                                   (- cperl-close-paren-offset)) ; compensate
4170                                  ((eq char-after ?\| )
4171                                   (- (or cperl-regexp-indent-step cperl-indent-level)))
4172                                  (t 0))
4173                            (if (eq (following-char) ?\| )
4174                                (or cperl-regexp-indent-step cperl-indent-level)
4175                              0)
4176                            (current-column)))
4177                        ;; Now we have no preceeding line...
4178                        (t
4179                         (goto-char p)
4180                         (+ (or cperl-regexp-indent-step cperl-indent-level)
4181                            -1
4182                            (current-column)))))
4183                 ((get-text-property char-after-pos 'REx-part2)
4184                  (condition-case nil    ; Use indentation of the 1st part
4185                      (forward-sexp -1))
4186                  (current-column))
4187                 ((or (nth 3 state) (nth 4 state))
4188                  ;; return nil or t if should not change this line
4189                  (nth 4 state))
4190                 ;; XXXX Do we need to special-case this?
4191                 ((null containing-sexp)
4192                  ;; Line is at top level.  May be data or function definition,
4193                  ;; or may be function argument declaration.
4194                  ;; Indent like the previous top level line
4195                  ;; unless that ends in a closeparen without semicolon,
4196                  ;; in which case this line is the first argument decl.
4197                  (skip-chars-forward " \t")
4198                  (+ (save-excursion
4199                       (goto-char start)
4200                       (- (current-indentation)
4201                          (if (nth 2 s-s) cperl-indent-level 0)))
4202                     (if (eq char-after ?{) cperl-continued-brace-offset 0)
4203                     (progn
4204                       (cperl-backward-to-noncomment (or old-indent (point-min)))
4205                       ;; Look at previous line that's at column 0
4206                       ;; to determine whether we are in top-level decls
4207                       ;; or function's arg decls.  Set basic-indent accordingly.
4208                       ;; Now add a little if this is a continuation line.
4209                       (if (or (bobp)
4210                               (eq (point) old-indent) ; old-indent was at comment
4211                               (eq (preceding-char) ?\;)
4212                               ;;  Had ?\) too
4213                               (and (eq (preceding-char) ?\})
4214                                    (cperl-after-block-and-statement-beg
4215                                     (point-min))) ; Was start - too close
4216                               (memq char-after (append ")]}" nil))
4217                               (and (eq (preceding-char) ?\:) ; label
4218                                    (progn
4219                                      (forward-sexp -1)
4220                                      (skip-chars-backward " \t")
4221                                      (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*[ \t]*:")))
4222                               (get-text-property (point) 'first-format-line))
4223                           (progn
4224                             (if (and parse-data
4225                                      (not (eq char-after ?\C-j)))
4226                                 (setcdr (cddr parse-data)
4227                                         (list pre-indent-point)))
4228                             0)
4229                         cperl-continued-statement-offset))))
4230                 ((not
4231                   (or (setq is-block
4232                             (and (setq delim (= (char-after containing-sexp) ?{))
4233                                  (save-excursion ; Is it a hash?
4234                                    (goto-char containing-sexp)
4235                                    (cperl-block-p))))
4236                       cperl-indent-parens-as-block))
4237                  ;; group is an expression, not a block:
4238                  ;; indent to just after the surrounding open parens,
4239                  ;; skip blanks if we do not close the expression.
4240                  (goto-char (1+ containing-sexp))
4241                  (or (memq char-after
4242                            (append (if delim "}" ")]}") nil))
4243                      (looking-at "[ \t]*\\(#\\|$\\)")
4244                      (skip-chars-forward " \t"))
4245                  (+ (current-column)
4246                     (if (and delim
4247                              (eq char-after ?\}))
4248                         ;; Correct indentation of trailing ?\}
4249                         (+ cperl-indent-level cperl-close-paren-offset)
4250                       0)))
4251 ;;;           ((and (/= (char-after containing-sexp) ?{)
4252 ;;;                 (not cperl-indent-parens-as-block))
4253 ;;;            ;; line is expression, not statement:
4254 ;;;            ;; indent to just after the surrounding open,
4255 ;;;            ;; skip blanks if we do not close the expression.
4256 ;;;            (goto-char (1+ containing-sexp))
4257 ;;;            (or (memq char-after (append ")]}" nil))
4258 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
4259 ;;;                (skip-chars-forward " \t"))
4260 ;;;            (current-column))
4261 ;;;           ((progn
4262 ;;;              ;; Containing-expr starts with \{.  Check whether it is a hash.
4263 ;;;              (goto-char containing-sexp)
4264 ;;;              (and (not (cperl-block-p))
4265 ;;;                   (not cperl-indent-parens-as-block)))
4266 ;;;            (goto-char (1+ containing-sexp))
4267 ;;;            (or (eq char-after ?\})
4268 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
4269 ;;;                (skip-chars-forward " \t"))
4270 ;;;            (+ (current-column)      ; Correct indentation of trailing ?\}
4271 ;;;               (if (eq char-after ?\}) (+ cperl-indent-level
4272 ;;;                                          cperl-close-paren-offset)
4273 ;;;                 0)))
4274                 (t
4275                  ;; Statement level.  Is it a continuation or a new statement?
4276                  ;; Find previous non-comment character.
4277                  (goto-char pre-indent-point)
4278                  (cperl-backward-to-noncomment containing-sexp)
4279                  ;; Back up over label lines, since they don't
4280                  ;; affect whether our line is a continuation.
4281                  ;; (Had \, too)
4282                  (while;;(or (eq (preceding-char) ?\,)
4283                      (and (eq (preceding-char) ?:)
4284                           (or;;(eq (char-after (- (point) 2)) ?\') ; ????
4285                            (memq (char-syntax (char-after (- (point) 2)))
4286                                  '(?w ?_))))
4287                    ;;)
4288                    (if (eq (preceding-char) ?\,)
4289                        ;; Will go to beginning of line, essentially.
4290                        ;; Will ignore embedded sexpr XXXX.
4291                        (cperl-backward-to-start-of-continued-exp containing-sexp))
4292                    (beginning-of-line)
4293                    (cperl-backward-to-noncomment containing-sexp))
4294                  ;; Now we get the answer.
4295                  (if (not (or (eq (1- (point)) containing-sexp)
4296                               (memq (preceding-char)
4297                                     (append (if is-block " ;{" " ,;{") '(nil)))
4298                               (and (eq (preceding-char) ?\})
4299                                    (cperl-after-block-and-statement-beg
4300                                     containing-sexp))
4301                               (get-text-property (point) 'first-format-line)))
4302                      ;; This line is continuation of preceding line's statement;
4303                      ;; indent  `cperl-continued-statement-offset'  more than the
4304                      ;; previous line of the statement.
4305                      ;;
4306                      ;; There might be a label on this line, just
4307                      ;; consider it bad style and ignore it.
4308                      (progn
4309                        (cperl-backward-to-start-of-continued-exp containing-sexp)
4310                        (+ (if (memq char-after (append "}])" nil))
4311                               0         ; Closing parenth
4312                             cperl-continued-statement-offset)
4313                           (if (or is-block
4314                                   (not delim)
4315                                   (not (eq char-after ?\})))
4316                               0
4317                             ;; Now it is a hash reference
4318                             (+ cperl-indent-level cperl-close-paren-offset))
4319                           ;; Labels do not take :: ...
4320                           (if (looking-at "\\(\\w\\|_\\)+[ \t]*:")
4321                               (if (> (current-indentation) cperl-min-label-indent)
4322                                   (- (current-indentation) cperl-label-offset)
4323                                 ;; Do not move `parse-data', this should
4324                                 ;; be quick anyway (this comment comes
4325                                 ;; from different location):
4326                                 (cperl-calculate-indent))
4327                             (current-column))
4328                           (if (eq char-after ?\{)
4329                               cperl-continued-brace-offset 0)))
4330                    ;; This line starts a new statement.
4331                    ;; Position following last unclosed open.
4332                    (goto-char containing-sexp)
4333                    ;; Is line first statement after an open-brace?
4334                    (or
4335                     ;; If no, find that first statement and indent like
4336                     ;; it.  If the first statement begins with label, do
4337                     ;; not believe when the indentation of the label is too
4338                     ;; small.
4339                     (save-excursion
4340                       (forward-char 1)
4341                       (setq old-indent (current-indentation))
4342                       (let ((colon-line-end 0))
4343                         (while
4344                             (progn (skip-chars-forward " \t\n")
4345                                    (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]\\|=[a-zA-Z]"))
4346                           ;; Skip over comments and labels following openbrace.
4347                           (cond ((= (following-char) ?\#)
4348                                  (forward-line 1))
4349                                 ((= (following-char) ?\=)
4350                                  (goto-char
4351                                   (or (next-single-property-change (point) 'in-pod)
4352                                       (point-max)))) ; do not loop if no syntaxification
4353                                 ;; label:
4354                                 (t
4355                                  (save-excursion (end-of-line)
4356                                                  (setq colon-line-end (point)))
4357                                  (search-forward ":"))))
4358                         ;; The first following code counts
4359                         ;; if it is before the line we want to indent.
4360                         (and (< (point) indent-point)
4361                              (if (> colon-line-end (point)) ; After label
4362                                  (if (> (current-indentation)
4363                                         cperl-min-label-indent)
4364                                      (- (current-indentation) cperl-label-offset)
4365                                    ;; Do not believe: `max' is involved
4366                                    (+ old-indent cperl-indent-level))
4367                                (current-column)))))
4368                     ;; If no previous statement,
4369                     ;; indent it relative to line brace is on.
4370                     ;; For open brace in column zero, don't let statement
4371                     ;; start there too.  If cperl-indent-level is zero,
4372                     ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
4373                     ;; For open-braces not the first thing in a line,
4374                     ;; add in cperl-brace-imaginary-offset.
4375
4376                     ;; If first thing on a line:  ?????
4377                     (+ (if (and (bolp) (zerop cperl-indent-level))
4378                            (+ cperl-brace-offset cperl-continued-statement-offset)
4379                          cperl-indent-level)
4380                        (if (or is-block
4381                                (not delim)
4382                                (not (eq char-after ?\})))
4383                            0
4384                          ;; Now it is a hash reference
4385                          (+ cperl-indent-level cperl-close-paren-offset))
4386                        ;; Move back over whitespace before the openbrace.
4387                        ;; If openbrace is not first nonwhite thing on the line,
4388                        ;; add the cperl-brace-imaginary-offset.
4389                        (progn (skip-chars-backward " \t")
4390                               (if (bolp) 0 cperl-brace-imaginary-offset))
4391                        ;; If the openbrace is preceded by a parenthesized exp,
4392                        ;; move to the beginning of that;
4393                        ;; possibly a different line
4394                        (progn
4395                          (cperl-backward-to-noncomment (point-min))
4396                          (if (eq (preceding-char) ?\))
4397                              (forward-sexp -1))
4398                          ;; In the case it starts a subroutine, indent with
4399                          ;; respect to `sub', not with respect to the
4400                          ;; first thing on the line, say in the case of
4401                          ;; anonymous sub in a hash.
4402                          ;;
4403                          ;;(skip-chars-backward " \t")
4404                          (cperl-backward-to-noncomment (point-min))
4405                          (if (and
4406                               (or
4407                                (and (get-text-property (point) 'attrib-group)
4408                                     (goto-char
4409                                      (cperl-beginning-of-property
4410                                       (point) 'attrib-group)))
4411                                (and (eq (preceding-char) ?b)
4412                                     (progn
4413                                       (forward-sexp -1)
4414                                       (looking-at "sub\\>"))))
4415                               (setq old-indent
4416                                     (nth 1
4417                                          (parse-partial-sexp
4418                                           (save-excursion (beginning-of-line) (point))
4419                                           (point)))))
4420                              (progn (goto-char (1+ old-indent))
4421                                     (skip-chars-forward " \t")
4422                                     (current-column))
4423                            ;; Get initial indentation of the line we are on.
4424                            ;; If line starts with label, calculate label indentation
4425                            (if (save-excursion
4426                                  (beginning-of-line)
4427                                  (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
4428                                (if (> (current-indentation) cperl-min-label-indent)
4429                                    (- (current-indentation) cperl-label-offset)
4430                                  ;; Do not move `parse-data', this should
4431                                  ;; be quick anyway:
4432                                  (cperl-calculate-indent))
4433                              (current-indentation))))))))))))))
4434
4435 (defvar cperl-indent-alist
4436   '((string nil)
4437     (comment nil)
4438     (toplevel 0)
4439     (toplevel-after-parenth 2)
4440     (toplevel-continued 2)
4441     (expression 1))
4442   "Alist of indentation rules for CPerl mode.
4443 The values mean:
4444   nil: do not indent;
4445   number: add this amount of indentation.
4446
4447 Not finished, not used.")
4448
4449 (defun cperl-where-am-i (&optional parse-start start-state)
4450   ;; Unfinished
4451   "Return a list of lists ((TYPE POS)...) of good points before the point.
4452 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'.
4453
4454 Not finished, not used."
4455   (save-excursion
4456     (let* ((start-point (point)) unused
4457            (s-s (cperl-get-state))
4458            (start (nth 0 s-s))
4459            (state (nth 1 s-s))
4460            (prestart (nth 3 s-s))
4461            (containing-sexp (car (cdr state)))
4462            (case-fold-search nil)
4463            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
4464       (cond ((nth 3 state)              ; In string
4465              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
4466             ((nth 4 state)              ; In comment
4467              (setq res (cons '(comment) res)))
4468             ((null containing-sexp)
4469              ;; Line is at top level.
4470              ;; Indent like the previous top level line
4471              ;; unless that ends in a closeparen without semicolon,
4472              ;; in which case this line is the first argument decl.
4473              (cperl-backward-to-noncomment (or parse-start (point-min)))
4474              ;;(skip-chars-backward " \t\f\n")
4475              (cond
4476               ((or (bobp)
4477                    (memq (preceding-char) (append ";}" nil)))
4478                (setq res (cons (list 'toplevel start) res)))
4479               ((eq (preceding-char) ?\) )
4480                (setq res (cons (list 'toplevel-after-parenth start) res)))
4481               (t
4482                (setq res (cons (list 'toplevel-continued start) res)))))
4483             ((/= (char-after containing-sexp) ?{)
4484              ;; line is expression, not statement:
4485              ;; indent to just after the surrounding open.
4486              ;; skip blanks if we do not close the expression.
4487              (setq res (cons (list 'expression-blanks
4488                                    (progn
4489                                      (goto-char (1+ containing-sexp))
4490                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
4491                                          (skip-chars-forward " \t"))
4492                                      (point)))
4493                              (cons (list 'expression containing-sexp) res))))
4494             ((progn
4495                ;; Containing-expr starts with \{.  Check whether it is a hash.
4496                (goto-char containing-sexp)
4497                (not (cperl-block-p)))
4498              (setq res (cons (list 'expression-blanks
4499                                    (progn
4500                                      (goto-char (1+ containing-sexp))
4501                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
4502                                          (skip-chars-forward " \t"))
4503                                      (point)))
4504                              (cons (list 'expression containing-sexp) res))))
4505             (t
4506              ;; Statement level.
4507              (setq res (cons (list 'in-block containing-sexp) res))
4508              ;; Is it a continuation or a new statement?
4509              ;; Find previous non-comment character.
4510              (cperl-backward-to-noncomment containing-sexp)
4511              ;; Back up over label lines, since they don't
4512              ;; affect whether our line is a continuation.
4513              ;; Back up comma-delimited lines too ?????
4514              (while (or (eq (preceding-char) ?\,)
4515                         (save-excursion (cperl-after-label)))
4516                (if (eq (preceding-char) ?\,)
4517                    ;; Will go to beginning of line, essentially
4518                    ;; Will ignore embedded sexpr XXXX.
4519                    (cperl-backward-to-start-of-continued-exp containing-sexp))
4520                (beginning-of-line)
4521                (cperl-backward-to-noncomment containing-sexp))
4522              ;; Now we get the answer.
4523              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
4524                  ;; This line is continuation of preceding line's statement.
4525                  (list (list 'statement-continued containing-sexp))
4526                ;; This line starts a new statement.
4527                ;; Position following last unclosed open.
4528                (goto-char containing-sexp)
4529                ;; Is line first statement after an open-brace?
4530                (or
4531                 ;; If no, find that first statement and indent like
4532                 ;; it.  If the first statement begins with label, do
4533                 ;; not believe when the indentation of the label is too
4534                 ;; small.
4535                 (save-excursion
4536                   (forward-char 1)
4537                   (let ((colon-line-end 0))
4538                     (while (progn (skip-chars-forward " \t\n" start-point)
4539                                   (and (< (point) start-point)
4540                                        (looking-at
4541                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
4542                       ;; Skip over comments and labels following openbrace.
4543                       (cond ((= (following-char) ?\#)
4544                              ;;(forward-line 1)
4545                              (end-of-line))
4546                             ;; label:
4547                             (t
4548                              (save-excursion (end-of-line)
4549                                              (setq colon-line-end (point)))
4550                              (search-forward ":"))))
4551                     ;; Now at the point, after label, or at start
4552                     ;; of first statement in the block.
4553                     (and (< (point) start-point)
4554                          (if (> colon-line-end (point))
4555                              ;; Before statement after label
4556                              (if (> (current-indentation)
4557                                     cperl-min-label-indent)
4558                                  (list (list 'label-in-block (point)))
4559                                ;; Do not believe: `max' is involved
4560                                (list
4561                                 (list 'label-in-block-min-indent (point))))
4562                            ;; Before statement
4563                            (list 'statement-in-block (point))))))
4564                 ;; If no previous statement,
4565                 ;; indent it relative to line brace is on.
4566                 ;; For open brace in column zero, don't let statement
4567                 ;; start there too.  If cperl-indent-level is zero,
4568                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
4569                 ;; For open-braces not the first thing in a line,
4570                 ;; add in cperl-brace-imaginary-offset.
4571
4572                 ;; If first thing on a line:  ?????
4573                 (setq unused            ; This is not finished...
4574                 (+ (if (and (bolp) (zerop cperl-indent-level))
4575                        (+ cperl-brace-offset cperl-continued-statement-offset)
4576                      cperl-indent-level)
4577                    ;; Move back over whitespace before the openbrace.
4578                    ;; If openbrace is not first nonwhite thing on the line,
4579                    ;; add the cperl-brace-imaginary-offset.
4580                    (progn (skip-chars-backward " \t")
4581                           (if (bolp) 0 cperl-brace-imaginary-offset))
4582                    ;; If the openbrace is preceded by a parenthesized exp,
4583                    ;; move to the beginning of that;
4584                    ;; possibly a different line
4585                    (progn
4586                      (if (eq (preceding-char) ?\))
4587                          (forward-sexp -1))
4588                      ;; Get initial indentation of the line we are on.
4589                      ;; If line starts with label, calculate label indentation
4590                      (if (save-excursion
4591                            (beginning-of-line)
4592                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
4593                          (if (> (current-indentation) cperl-min-label-indent)
4594                              (- (current-indentation) cperl-label-offset)
4595                            (cperl-calculate-indent))
4596                        (current-indentation)))))))))
4597       res)))
4598
4599 (defun cperl-calculate-indent-within-comment ()
4600   "Return the indentation amount for line, assuming that
4601 the current line is to be regarded as part of a block comment."
4602   (let (end star-start)
4603     (save-excursion
4604       (beginning-of-line)
4605       (skip-chars-forward " \t")
4606       (setq end (point))
4607       (and (= (following-char) ?#)
4608            (forward-line -1)
4609            (cperl-to-comment-or-eol)
4610            (setq end (point)))
4611       (goto-char end)
4612       (current-column))))
4613
4614
4615 (defun cperl-to-comment-or-eol ()
4616   "Go to position before comment on the current line, or to end of line.
4617 Returns true if comment is found.  In POD will not move the point."
4618   ;; If the line is inside other syntax groups (qq-style strings, HERE-docs)
4619   ;; then looks for literal # or end-of-line.
4620   (let (state stop-in cpoint (lim (progn (end-of-line) (point))) pr e)
4621     (or cperl-font-locking
4622         (cperl-update-syntaxification lim lim))
4623     (beginning-of-line)
4624     (if (setq pr (get-text-property (point) 'syntax-type))
4625         (setq e (next-single-property-change (point) 'syntax-type nil (point-max))))
4626     (if (or (eq pr 'pod)
4627             (if (or (not e) (> e lim))  ; deep inside a group
4628                 (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t)))
4629         (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
4630       ;; Else - need to do it the hard way
4631       (and (and e (<= e lim))
4632            (goto-char e))
4633       (while (not stop-in)
4634         (setq state (parse-partial-sexp (point) lim nil nil nil t))
4635                                         ; stop at comment
4636         ;; If fails (beginning-of-line inside sexp), then contains not-comment
4637         (if (nth 4 state)               ; After `#';
4638                                         ; (nth 2 state) can be
4639                                         ; beginning of m,s,qq and so
4640                                         ; on
4641             (if (nth 2 state)
4642                 (progn
4643                   (setq cpoint (point))
4644                   (goto-char (nth 2 state))
4645                   (cond
4646                    ((looking-at "\\(s\\|tr\\)\\>")
4647                     (or (re-search-forward
4648                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
4649                          lim 'move)
4650                         (setq stop-in t)))
4651                    ((looking-at "\\(m\\|q\\([qxwr]\\)?\\)\\>")
4652                     (or (re-search-forward
4653                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
4654                          lim 'move)
4655                         (setq stop-in t)))
4656                    (t                   ; It was fair comment
4657                     (setq stop-in t)    ; Finish
4658                     (goto-char (1- cpoint)))))
4659               (setq stop-in t)          ; Finish
4660               (forward-char -1))
4661           (setq stop-in t)))            ; Finish
4662       (nth 4 state))))
4663
4664 (defsubst cperl-modify-syntax-type (at how)
4665   (if (< at (point-max))
4666       (progn
4667         (put-text-property at (1+ at) 'syntax-table how)
4668         (put-text-property at (1+ at) 'rear-nonsticky '(syntax-table)))))
4669
4670 (defun cperl-protect-defun-start (s e)
4671   ;; C code looks for "^\\s(" to skip comment backward in "hard" situations
4672   (save-excursion
4673     (goto-char s)
4674     (while (re-search-forward "^\\s(" e 'to-end)
4675       (put-text-property (1- (point)) (point) 'syntax-table cperl-st-punct))))
4676
4677 (defun cperl-commentify (bb e string &optional noface)
4678   (if cperl-use-syntax-table-text-property
4679       (if (eq noface 'n)                ; Only immediate
4680           nil
4681         ;; We suppose that e is _after_ the end of construction, as after eol.
4682         (setq string (if string cperl-st-sfence cperl-st-cfence))
4683         (if (> bb (- e 2))
4684             ;; one-char string/comment?!
4685             (cperl-modify-syntax-type bb cperl-st-punct)
4686           (cperl-modify-syntax-type bb string)
4687           (cperl-modify-syntax-type (1- e) string))
4688         (if (and (eq string cperl-st-sfence) (> (- e 2) bb))
4689             (put-text-property (1+ bb) (1- e)
4690                                'syntax-table cperl-string-syntax-table))
4691         (cperl-protect-defun-start bb e))
4692     ;; Fontify
4693     (or noface
4694         (not cperl-pod-here-fontify)
4695         (put-text-property bb e 'face (if string 'font-lock-string-face
4696                                         'font-lock-comment-face)))))
4697
4698 (defvar cperl-starters '(( ?\( . ?\) )
4699                          ( ?\[ . ?\] )
4700                          ( ?\{ . ?\} )
4701                          ( ?\< . ?\> )))
4702
4703 (defun cperl-cached-syntax-table (st)
4704   "Get a syntax table cached in ST, or create and cache into ST a syntax table.
4705 All the entries of the syntax table are \".\", except for a backslash, which
4706 is quoting."
4707   (if (car-safe st)
4708       (car st)
4709     (setcar st (make-syntax-table))
4710     (setq st (car st))
4711     (let ((i 0))
4712       (while (< i 256)
4713         (modify-syntax-entry i "." st)
4714         (setq i (1+ i))))
4715     (modify-syntax-entry ?\\ "\\" st)
4716     st))
4717
4718 (defun cperl-forward-re (lim end is-2arg st-l err-l argument
4719                              &optional ostart oend)
4720 "Find the end of a regular expression or a stringish construct (q[] etc).
4721 The point should be before the starting delimiter.
4722
4723 Goes to LIM if none is found.  If IS-2ARG is non-nil, assumes that it
4724 is s/// or tr/// like expression.  If END is nil, generates an error
4725 message if needed.  If SET-ST is non-nil, will use (or generate) a
4726 cached syntax table in ST-L.  If ERR-L is non-nil, will store the
4727 error message in its CAR (unless it already contains some error
4728 message).  ARGUMENT should be the name of the construct (used in error
4729 messages).  OSTART, OEND may be set in recursive calls when processing
4730 the second argument of 2ARG construct.
4731
4732 Works *before* syntax recognition is done.  In IS-2ARG situation may
4733 modify syntax-type text property if the situation is too hard."
4734   (let (b starter ender st i i2 go-forward reset-st set-st)
4735     (skip-chars-forward " \t")
4736     ;; ender means matching-char matcher.
4737     (setq b (point)
4738           starter (if (eobp) 0 (char-after b))
4739           ender (cdr (assoc starter cperl-starters)))
4740     ;; What if starter == ?\\  ????
4741     (setq st (cperl-cached-syntax-table st-l))
4742     (setq set-st t)
4743     ;; Whether we have an intermediate point
4744     (setq i nil)
4745     ;; Prepare the syntax table:
4746     (if (not ender)             ; m/blah/, s/x//, s/x/y/
4747         (modify-syntax-entry starter "$" st)
4748       (modify-syntax-entry starter (concat "(" (list ender)) st)
4749       (modify-syntax-entry ender  (concat ")" (list starter)) st))
4750     (condition-case bb
4751         (progn
4752           ;; We use `$' syntax class to find matching stuff, but $$
4753           ;; is recognized the same as $, so we need to check this manually.
4754           (if (and (eq starter (char-after (cperl-1+ b)))
4755                    (not ender))
4756               ;; $ has TeXish matching rules, so $$ equiv $...
4757               (forward-char 2)
4758             (setq reset-st (syntax-table))
4759             (set-syntax-table st)
4760             (forward-sexp 1)
4761             (if (<= (point) (1+ b))
4762                 (error "Unfinished regular expression"))
4763             (set-syntax-table reset-st)
4764             (setq reset-st nil)
4765             ;; Now the problem is with m;blah;;
4766             (and (not ender)
4767                  (eq (preceding-char)
4768                      (char-after (- (point) 2)))
4769                  (save-excursion
4770                    (forward-char -2)
4771                    (= 0 (% (skip-chars-backward "\\\\") 2)))
4772                  (forward-char -1)))
4773           ;; Now we are after the first part.
4774           (and is-2arg                  ; Have trailing part
4775                (not ender)
4776                (eq (following-char) starter) ; Empty trailing part
4777                (progn
4778                  (or (eq (char-syntax (following-char)) ?.)
4779                      ;; Make trailing letter into punctuation
4780                      (cperl-modify-syntax-type (point) cperl-st-punct))
4781                  (setq is-2arg nil go-forward t))) ; Ignore the tail
4782           (if is-2arg                   ; Not number => have second part
4783               (progn
4784                 (setq i (point) i2 i)
4785                 (if ender
4786                     (if (memq (following-char) '(?\  ?\t ?\n ?\f))
4787                         (progn
4788                           (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4789                               (goto-char (match-end 0))
4790                             (skip-chars-forward " \t\n\f"))
4791                           (setq i2 (point))))
4792                   (forward-char -1))
4793                 (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4794                 (if ender (modify-syntax-entry ender "." st))
4795                 (setq set-st nil)
4796                 (setq ender (cperl-forward-re lim end nil st-l err-l
4797                                               argument starter ender)
4798                       ender (nth 2 ender)))))
4799       (error (goto-char lim)
4800              (setq set-st nil)
4801              (if reset-st
4802                  (set-syntax-table reset-st))
4803              (or end
4804                  (message
4805                   "End of `%s%s%c ... %c' string/RE not found: %s"
4806                   argument
4807                   (if ostart (format "%c ... %c" ostart (or oend ostart)) "")
4808                   starter (or ender starter) bb)
4809                  (or (car err-l) (setcar err-l b)))))
4810     (if set-st
4811         (progn
4812           (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4813           (if ender (modify-syntax-entry ender "." st))))
4814     ;; i: have 2 args, after end of the first arg
4815     ;; i2: start of the second arg, if any (before delim iff `ender').
4816     ;; ender: the last arg bounded by parens-like chars, the second one of them
4817     ;; starter: the starting delimiter of the first arg
4818     ;; go-forward: has 2 args, and the second part is empty
4819     (list i i2 ender starter go-forward)))
4820
4821 (defun cperl-forward-group-in-re (&optional st-l)
4822   "Find the end of a group in a REx.
4823 Return the error message (if any).  Does not work if delimiter is `)'.
4824 Works before syntax recognition is done."
4825   ;; Works *before* syntax recognition is done
4826   (or st-l (setq st-l (list nil)))      ; Avoid overwriting '()
4827   (let (st b reset-st)
4828     (condition-case b
4829         (progn
4830           (setq st (cperl-cached-syntax-table st-l))
4831           (modify-syntax-entry ?\( "()" st)
4832           (modify-syntax-entry ?\) ")(" st)
4833           (setq reset-st (syntax-table))
4834           (set-syntax-table st)
4835           (forward-sexp 1))
4836       (error (message
4837               "cperl-forward-group-in-re: error %s" b)))
4838     ;; now restore the initial state
4839     (if st
4840         (progn
4841           (modify-syntax-entry ?\( "." st)
4842           (modify-syntax-entry ?\) "." st)))
4843     (if reset-st
4844         (set-syntax-table reset-st))
4845     b))
4846
4847
4848 (defvar font-lock-string-face)
4849 ;;(defvar font-lock-reference-face)
4850 (defvar font-lock-constant-face)
4851 (defsubst cperl-postpone-fontification (b e type val &optional now)
4852   ;; Do after syntactic fontification?
4853   (if cperl-syntaxify-by-font-lock
4854       (or now (put-text-property b e 'cperl-postpone (cons type val)))
4855     (put-text-property b e type val)))
4856
4857 ;;; Here is how the global structures (those which cannot be
4858 ;;; recognized locally) are marked:
4859 ;;      a) PODs:
4860 ;;              Start-to-end is marked `in-pod' ==> t
4861 ;;              Each non-literal part is marked `syntax-type' ==> `pod'
4862 ;;              Each literal part is marked `syntax-type' ==> `in-pod'
4863 ;;      b) HEREs:
4864 ;;              Start-to-end is marked `here-doc-group' ==> t
4865 ;;              The body is marked `syntax-type' ==> `here-doc'
4866 ;;              The delimiter is marked `syntax-type' ==> `here-doc-delim'
4867 ;;      c) FORMATs:
4868 ;;              First line (to =) marked `first-format-line' ==> t
4869 ;;              After-this--to-end is marked `syntax-type' ==> `format'
4870 ;;      d) 'Q'uoted string:
4871 ;;              part between markers inclusive is marked `syntax-type' ==> `string'
4872 ;;              part between `q' and the first marker is marked `syntax-type' ==> `prestring'
4873 ;;      e) Attributes of subroutines: `attrib-group' ==> t
4874 ;;              (or 0 if declaration); up to `{' or ';': `syntax-type' => `sub-decl'.
4875 ;;      f) Multiline my/our declaration lists etc: `syntax-type' => `multiline'
4876
4877 (defun cperl-unwind-to-safe (before &optional end)
4878   ;; if BEFORE, go to the previous start-of-line on each step of unwinding
4879   (let ((pos (point)) opos)
4880     (while (and pos (progn
4881                       (beginning-of-line)
4882                       (get-text-property (setq pos (point)) 'syntax-type)))
4883       (setq opos pos
4884             pos (cperl-beginning-of-property pos 'syntax-type))
4885       (if (eq pos (point-min))
4886           (setq pos nil))
4887       (if pos
4888           (if before
4889               (progn
4890                 (goto-char (cperl-1- pos))
4891                 (beginning-of-line)
4892                 (setq pos (point)))
4893             (goto-char (setq pos (cperl-1- pos))))
4894         ;; Up to the start
4895         (goto-char (point-min))))
4896     ;; Skip empty lines
4897     (and (looking-at "\n*=")
4898          (/= 0 (skip-chars-backward "\n"))
4899          (forward-char))
4900     (setq pos (point))
4901     (if end
4902         ;; Do the same for end, going small steps
4903         (save-excursion
4904           (while (and end (get-text-property end 'syntax-type))
4905             (setq pos end
4906                   end (next-single-property-change end 'syntax-type nil (point-max)))
4907             (if end (progn (goto-char end)
4908                            (or (bolp) (forward-line 1))
4909                            (setq end (point)))))
4910           (or end pos)))))
4911
4912 (defvar cperl-nonoverridable-face)
4913 (defvar font-lock-function-name-face)
4914 (defvar font-lock-comment-face)
4915
4916 (defun cperl-find-sub-attrs (&optional st-l b-fname e-fname pos)
4917   "Syntaxically mark (and fontify) attributes of a subroutine.
4918 Should be called with the point before leading colon of an attribute."
4919   ;; Works *before* syntax recognition is done
4920   (or st-l (setq st-l (list nil)))      ; Avoid overwriting '()
4921   (let (st b p reset-st after-first (start (point)) start1 end1)
4922     (condition-case b
4923         (while (looking-at
4924                 (concat
4925                  "\\("                  ; 1=optional? colon
4926                    ":" cperl-maybe-white-and-comment-rex ; 2=whitespace/comment?
4927                  "\\)"
4928                  (if after-first "?" "")
4929                  ;; No space between name and paren allowed...
4930                  "\\(\\sw+\\)"          ; 3=name
4931                  "\\((\\)?"))           ; 4=optional paren
4932           (and (match-beginning 1)
4933                (cperl-postpone-fontification
4934                 (match-beginning 0) (cperl-1+ (match-beginning 0))
4935                 'face font-lock-constant-face))
4936           (setq start1 (match-beginning 3) end1 (match-end 3))
4937           (cperl-postpone-fontification start1 end1
4938                                         'face font-lock-constant-face)
4939           (goto-char end1)              ; end or before `('
4940           (if (match-end 4)             ; Have attribute arguments...
4941               (progn
4942                 (if st nil
4943                   (setq st (cperl-cached-syntax-table st-l))
4944                   (modify-syntax-entry ?\( "()" st)
4945                   (modify-syntax-entry ?\) ")(" st))
4946                 (setq reset-st (syntax-table) p (point))
4947                 (set-syntax-table st)
4948                 (forward-sexp 1)
4949                 (set-syntax-table reset-st)
4950                 (setq reset-st nil)
4951                 (cperl-commentify p (point) t))) ; mark as string
4952           (forward-comment (buffer-size))
4953           (setq after-first t))
4954       (error (message
4955               "L%d: attribute `%s': %s"
4956               (count-lines (point-min) (point)) (buffer-substring start1 end1) b)
4957              (setq start nil)))
4958     (and start
4959          (progn
4960            (put-text-property start (point)
4961                               'attrib-group (if (looking-at "{") t 0))
4962            (and pos
4963                 (< 1 (count-lines (+ 3 pos) (point))) ; end of `sub'
4964                 ;; Apparently, we do not need `multiline': faces added now
4965                 (put-text-property (+ 3 pos) (cperl-1+ (point))
4966                                    'syntax-type 'sub-decl))
4967            (and b-fname                 ; Fontify here: the following condition
4968                 (cperl-postpone-fontification ; is too hard to determine by
4969                  b-fname e-fname 'face ; a REx, so do it here
4970                 (if (looking-at "{")
4971                     font-lock-function-name-face
4972                   font-lock-variable-name-face)))))
4973     ;; now restore the initial state
4974     (if st
4975         (progn
4976           (modify-syntax-entry ?\( "." st)
4977           (modify-syntax-entry ?\) "." st)))
4978     (if reset-st
4979         (set-syntax-table reset-st))))
4980
4981 (defsubst cperl-look-at-leading-count (is-x-REx e)
4982   (if (re-search-forward (concat "\\=" (if is-x-REx "[ \t\n]*" "") "[{?+*]")
4983                          (1- e) t)      ; return nil on failure, no moving
4984       (if (eq ?\{ (preceding-char)) nil
4985         (cperl-postpone-fontification
4986          (1- (point)) (point)
4987          'face font-lock-function-name-face))))
4988
4989 ;;; Debugging this may require (setq max-specpdl-size 2000)...
4990 (defun cperl-find-pods-heres (&optional min max non-inter end ignore-max end-of-here-doc)
4991   "Scans the buffer for hard-to-parse Perl constructions.
4992 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify
4993 the sections using `cperl-pod-head-face', `cperl-pod-face',
4994 `cperl-here-face'."
4995   (interactive)
4996  (or min (setq min (point-min)
4997                 cperl-syntax-state nil
4998                 cperl-syntax-done-to min))
4999   (or max (setq max (point-max)))
5000   (let* ((cperl-pod-here-fontify (eval cperl-pod-here-fontify)) go tmpend
5001          face head-face here-face b e bb tag qtag b1 e1 argument i c tail tb
5002          is-REx is-x-REx REx-subgr-start REx-subgr-end was-subgr i2 hairy-RE
5003          (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
5004          (modified (buffer-modified-p)) overshoot
5005          (after-change-functions nil)
5006          (cperl-font-locking t)
5007          (use-syntax-state (and cperl-syntax-state
5008                                 (>= min (car cperl-syntax-state))))
5009          (state-point (if use-syntax-state
5010                           (car cperl-syntax-state)
5011                         (point-min)))
5012          (state (if use-syntax-state
5013                     (cdr cperl-syntax-state)))
5014          ;; (st-l '(nil)) (err-l '(nil)) ; Would overwrite - propagates from a function call to a function call!
5015          (st-l (list nil)) (err-l (list nil))
5016          ;; Somehow font-lock may be not loaded yet...
5017          (font-lock-string-face (if (boundp 'font-lock-string-face)
5018                                     font-lock-string-face
5019                                   'font-lock-string-face))
5020          (font-lock-constant-face (if (boundp 'font-lock-constant-face)
5021                                       font-lock-constant-face
5022                                     'font-lock-constant-face))
5023          (font-lock-function-name-face
5024           (if (boundp 'font-lock-function-name-face)
5025               font-lock-function-name-face
5026             'font-lock-function-name-face))
5027          (font-lock-comment-face
5028           (if (boundp 'font-lock-comment-face)
5029               font-lock-comment-face
5030             'font-lock-comment-face))
5031          (cperl-nonoverridable-face
5032           (if (boundp 'cperl-nonoverridable-face)
5033               cperl-nonoverridable-face
5034             'cperl-nonoverridable-face))
5035          (stop-point (if ignore-max
5036                          (point-max)
5037                        max))
5038          (search
5039           (concat
5040            "\\(\\`\n?\\|^\n\\)="        ; POD
5041            "\\|"
5042            ;; One extra () before this:
5043            "<<"                         ; HERE-DOC
5044            "\\("                        ; 1 + 1
5045            ;; First variant "BLAH" or just ``.
5046            "[ \t]*"                     ; Yes, whitespace is allowed!
5047            "\\([\"'`]\\)"               ; 2 + 1 = 3
5048            "\\([^\"'`\n]*\\)"           ; 3 + 1
5049            "\\3"
5050            "\\|"
5051            ;; Second variant: Identifier or \ID (same as 'ID') or empty
5052            "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
5053            ;; Do not have <<= or << 30 or <<30 or << $blah.
5054            ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
5055            "\\(\\)"             ; To preserve count of pars :-( 6 + 1
5056            "\\)"
5057            "\\|"
5058            ;; 1+6 extra () before this:
5059            "^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$" ;FRMAT
5060            (if cperl-use-syntax-table-text-property
5061                (concat
5062                 "\\|"
5063                 ;; 1+6+2=9 extra () before this:
5064                 "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>" ; QUOTED CONSTRUCT
5065                 "\\|"
5066                 ;; 1+6+2+1=10 extra () before this:
5067                 "\\([?/<]\\)"   ; /blah/ or ?blah? or <file*glob>
5068                 "\\|"
5069                 ;; 1+6+2+1+1=11 extra () before this
5070                 "\\<sub\\>"             ;  sub with proto/attr
5071                 "\\("
5072                    cperl-white-and-comment-rex
5073                    "\\(::[a-zA-Z_:'0-9]*\\|[a-zA-Z_'][a-zA-Z_:'0-9]*\\)\\)?" ; name
5074                 "\\("
5075                    cperl-maybe-white-and-comment-rex
5076                    "\\(([^()]*)\\|:[^:]\\)\\)" ; prototype or attribute start
5077                 "\\|"
5078                 ;; 1+6+2+1+1+6=17 extra () before this:
5079                 "\\$\\(['{]\\)"         ; $' or ${foo}
5080                 "\\|"
5081                 ;; 1+6+2+1+1+6+1=18 extra () before this (old pack'var syntax;
5082                 ;; we do not support intervening comments...):
5083                 "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'"
5084                 ;; 1+6+2+1+1+6+1+1=19 extra () before this:
5085                 "\\|"
5086                 "__\\(END\\|DATA\\)__"  ; __END__ or __DATA__
5087                 ;; 1+6+2+1+1+6+1+1+1=20 extra () before this:
5088                 "\\|"
5089                 "\\\\\\(['`\"($]\\)")   ; BACKWACKED something-hairy
5090              ""))))
5091     (unwind-protect
5092         (progn
5093           (save-excursion
5094             (or non-inter
5095                 (message "Scanning for \"hard\" Perl constructions..."))
5096             ;;(message "find: %s --> %s" min max)
5097             (and cperl-pod-here-fontify
5098                  ;; We had evals here, do not know why...
5099                  (setq face cperl-pod-face
5100                        head-face cperl-pod-head-face
5101                        here-face cperl-here-face))
5102             (remove-text-properties min max
5103                                     '(syntax-type t in-pod t syntax-table t
5104                                                   attrib-group t
5105                                                   cperl-postpone t
5106                                                   syntax-subtype t
5107                                                   rear-nonsticky t
5108                                                   front-sticky t
5109                                                   here-doc-group t
5110                                                   first-format-line t
5111                                                   REx-part2 t
5112                                                   indentable t))
5113             ;; Need to remove face as well...
5114             (goto-char min)
5115             (and (eq system-type 'emx)
5116                  (eq (point) 1)
5117                  (let ((case-fold-search t))
5118                    (looking-at "extproc[ \t]")) ; Analogue of #!
5119                  (cperl-commentify min
5120                                    (save-excursion (end-of-line) (point))
5121                                    nil))
5122             (while (and
5123                     (< (point) max)
5124                     (re-search-forward search max t))
5125               (setq tmpend nil)         ; Valid for most cases
5126               (setq b (match-beginning 0)
5127                     state (save-excursion (parse-partial-sexp
5128                                            state-point b nil nil state))
5129                     state-point b)
5130               (cond
5131                ;; 1+6+2+1+1+6=17 extra () before this:
5132                ;;    "\\$\\(['{]\\)"
5133                ((match-beginning 18) ; $' or ${foo}
5134                 (if (eq (preceding-char) ?\') ; $'
5135                     (progn
5136                       (setq b (1- (point))
5137                             state (parse-partial-sexp
5138                                    state-point (1- b) nil nil state)
5139                             state-point (1- b))
5140                       (if (nth 3 state) ; in string
5141                           (cperl-modify-syntax-type (1- b) cperl-st-punct))
5142                       (goto-char (1+ b)))
5143                   ;; else: ${
5144                   (setq bb (match-beginning 0))
5145                   (cperl-modify-syntax-type bb cperl-st-punct)))
5146                ;; No processing in strings/comments beyond this point:
5147                ((or (nth 3 state) (nth 4 state))
5148                 t)                      ; Do nothing in comment/string
5149                ((match-beginning 1)     ; POD section
5150                 ;;  "\\(\\`\n?\\|^\n\\)="
5151                 (setq b (match-beginning 0)
5152                       state (parse-partial-sexp
5153                              state-point b nil nil state)
5154                       state-point b)
5155                 (if (or (nth 3 state) (nth 4 state)
5156                         (looking-at "cut\\>"))
5157                     (if (or (nth 3 state) (nth 4 state) ignore-max)
5158                         nil             ; Doing a chunk only
5159                       (message "=cut is not preceded by a POD section")
5160                       (or (car err-l) (setcar err-l (point))))
5161                   (beginning-of-line)
5162
5163                   (setq b (point)
5164                         bb b
5165                         tb (match-beginning 0)
5166                         b1 nil)         ; error condition
5167                   ;; We do not search to max, since we may be called from
5168                   ;; some hook of fontification, and max is random
5169                   (or (re-search-forward "^\n=cut\\>" stop-point 'toend)
5170                       (progn
5171                         (goto-char b)
5172                         (if (re-search-forward "\n=cut\\>" stop-point 'toend)
5173                             (progn
5174                               (message "=cut is not preceded by an empty line")
5175                               (setq b1 t)
5176                               (or (car err-l) (setcar err-l b))))))
5177                   (beginning-of-line 2) ; An empty line after =cut is not POD!
5178                   (setq e (point))
5179                   (and (> e max)
5180                        (progn
5181                          (remove-text-properties
5182                           max e '(syntax-type t in-pod t syntax-table t
5183                                               attrib-group t
5184                                               cperl-postpone t
5185                                               syntax-subtype t
5186                                               here-doc-group t
5187                                               rear-nonsticky t
5188                                               front-sticky t
5189                                               first-format-line t
5190                                               REx-part2 t
5191                                               indentable t))
5192                          (setq tmpend tb)))
5193                   (put-text-property b e 'in-pod t)
5194                   (put-text-property b e 'syntax-type 'in-pod)
5195                   (goto-char b)
5196                   (while (re-search-forward "\n\n[ \t]" e t)
5197                     ;; We start 'pod 1 char earlier to include the preceding line
5198                     (beginning-of-line)
5199                     (put-text-property (cperl-1- b) (point) 'syntax-type 'pod)
5200                     (cperl-put-do-not-fontify b (point) t)
5201                     ;; mark the non-literal parts as PODs
5202                     (if cperl-pod-here-fontify
5203                         (cperl-postpone-fontification b (point) 'face face t))
5204                     (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
5205                     (beginning-of-line)
5206                     (setq b (point)))
5207                   (put-text-property (cperl-1- (point)) e 'syntax-type 'pod)
5208                   (cperl-put-do-not-fontify (point) e t)
5209                   (if cperl-pod-here-fontify
5210                       (progn
5211                         ;; mark the non-literal parts as PODs
5212                         (cperl-postpone-fontification (point) e 'face face t)
5213                         (goto-char bb)
5214                         (if (looking-at
5215                              "=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
5216                             ;; mark the headers
5217                             (cperl-postpone-fontification
5218                              (match-beginning 1) (match-end 1)
5219                              'face head-face))
5220                         (while (re-search-forward
5221                                 ;; One paragraph
5222                                 "^\n=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
5223                                 e 'toend)
5224                           ;; mark the headers
5225                           (cperl-postpone-fontification
5226                            (match-beginning 1) (match-end 1)
5227                            'face head-face))))
5228                   (cperl-commentify bb e nil)
5229                   (goto-char e)
5230                   (or (eq e (point-max))
5231                       (forward-char -1)))) ; Prepare for immediate POD start.
5232                ;; Here document
5233                ;; We can do many here-per-line;
5234                ;; but multiline quote on the same line as <<HERE confuses us...
5235                ;; ;; One extra () before this:
5236                ;;"<<"
5237                ;;  "\\("                        ; 1 + 1
5238                ;;  ;; First variant "BLAH" or just ``.
5239                ;;     "[ \t]*"                  ; Yes, whitespace is allowed!
5240                ;;     "\\([\"'`]\\)"    ; 2 + 1
5241                ;;     "\\([^\"'`\n]*\\)"        ; 3 + 1
5242                ;;     "\\3"
5243                ;;  "\\|"
5244                ;;  ;; Second variant: Identifier or \ID or empty
5245                ;;    "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
5246                ;;    ;; Do not have <<= or << 30 or <<30 or << $blah.
5247                ;;    ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
5248                ;;    "\\(\\)"           ; To preserve count of pars :-( 6 + 1
5249                ;;  "\\)"
5250                ((match-beginning 2)     ; 1 + 1
5251                 (setq b (point)
5252                       tb (match-beginning 0)
5253                       c (and            ; not HERE-DOC
5254                          (match-beginning 5)
5255                          (save-match-data
5256                            (or (looking-at "[ \t]*(") ; << function_call()
5257                                (save-excursion ; 1 << func_name, or $foo << 10
5258                                  (condition-case nil
5259                                      (progn
5260                                        (goto-char tb)
5261                ;;; XXX What to do: foo <<bar ???
5262                ;;; XXX Need to support print {a} <<B ???
5263                                        (forward-sexp -1)
5264                                        (save-match-data 
5265                                         ; $foo << b; $f .= <<B;
5266                                         ; ($f+1) << b; a($f) . <<B;
5267                                         ; foo 1, <<B; $x{a} <<b;
5268                                          (cond
5269                                           ((looking-at "[0-9$({]")
5270                                            (forward-sexp 1)
5271                                            (looking-at "[ \t]*<<")))))
5272                                    (error nil))) ; func(<<EOF)
5273                                (and (not (match-beginning 6)) ; Empty
5274                                     (looking-at
5275                                      "[ \t]*[=0-9$@%&(]"))))))
5276                 (if c                   ; Not here-doc
5277                     nil                 ; Skip it.
5278                   (setq c (match-end 2)) ; 1 + 1
5279                   (if (match-beginning 5) ;4 + 1
5280                       (setq b1 (match-beginning 5) ; 4 + 1
5281                             e1 (match-end 5)) ; 4 + 1
5282                     (setq b1 (match-beginning 4) ; 3 + 1
5283                           e1 (match-end 4))) ; 3 + 1
5284                   (setq tag (buffer-substring b1 e1)
5285                         qtag (regexp-quote tag))
5286                   (cond (cperl-pod-here-fontify
5287                          ;; Highlight the starting delimiter
5288                          (cperl-postpone-fontification b1 e1 'face font-lock-constant-face)
5289                          (cperl-put-do-not-fontify b1 e1 t)))
5290                   (forward-line)
5291                   (setq i (point))
5292                   (if end-of-here-doc
5293                       (goto-char end-of-here-doc))
5294                   (setq b (point))
5295                   ;; We do not search to max, since we may be called from
5296                   ;; some hook of fontification, and max is random
5297                   (or (and (re-search-forward (concat "^" qtag "$")
5298                                               stop-point 'toend)
5299                            (eq (following-char) ?\n))
5300                     (progn              ; Pretend we matched at the end
5301                       (goto-char (point-max))
5302                       (re-search-forward "\\'")
5303                       (message "End of here-document `%s' not found." tag)
5304                       (or (car err-l) (setcar err-l b))))
5305                   (if cperl-pod-here-fontify
5306                       (progn
5307                         ;; Highlight the ending delimiter
5308                         (cperl-postpone-fontification (match-beginning 0) (match-end 0)
5309                                                       'face font-lock-constant-face)
5310                         (cperl-put-do-not-fontify b (match-end 0) t)
5311                         ;; Highlight the HERE-DOC
5312                         (cperl-postpone-fontification b (match-beginning 0)
5313                                                       'face here-face)))
5314                   (setq e1 (cperl-1+ (match-end 0)))
5315                   (put-text-property b (match-beginning 0)
5316                                      'syntax-type 'here-doc)
5317                   (put-text-property (match-beginning 0) e1
5318                                      'syntax-type 'here-doc-delim)
5319                   (put-text-property b e1 'here-doc-group t)
5320                   ;; This makes insertion at the start of HERE-DOC update
5321                   ;; the whole construct:
5322                   (put-text-property b (cperl-1+ b) 'front-sticky '(syntax-type))
5323                   (cperl-commentify b e1 nil)
5324                   (cperl-put-do-not-fontify b (match-end 0) t)
5325                   ;; Cache the syntax info...
5326                   (setq cperl-syntax-state (cons state-point state))
5327                   ;; ... and process the rest of the line...
5328                   (setq overshoot
5329                         (elt            ; non-inter ignore-max
5330                          (cperl-find-pods-heres c i t end t e1) 1))
5331                   (if (and overshoot (> overshoot (point)))
5332                       (goto-char overshoot)
5333                     (setq overshoot e1))
5334                   (if (> e1 max)
5335                       (setq tmpend tb))))
5336                ;; format
5337                ((match-beginning 8)
5338                 ;; 1+6=7 extra () before this:
5339                 ;;"^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
5340                 (setq b (point)
5341                       name (if (match-beginning 8) ; 7 + 1
5342                                (buffer-substring (match-beginning 8) ; 7 + 1
5343                                                  (match-end 8)) ; 7 + 1
5344                              "")
5345                       tb (match-beginning 0))
5346                 (setq argument nil)
5347                 (put-text-property (save-excursion
5348                                      (beginning-of-line)
5349                                      (point))
5350                                    b 'first-format-line 't)
5351                 (if cperl-pod-here-fontify
5352                     (while (and (eq (forward-line) 0)
5353                                 (not (looking-at "^[.;]$")))
5354                       (cond
5355                        ((looking-at "^#")) ; Skip comments
5356                        ((and argument   ; Skip argument multi-lines
5357                              (looking-at "^[ \t]*{"))
5358                         (forward-sexp 1)
5359                         (setq argument nil))
5360                        (argument        ; Skip argument lines
5361                         (setq argument nil))
5362                        (t               ; Format line
5363                         (setq b1 (point))
5364                         (setq argument (looking-at "^[^\n]*[@^]"))
5365                         (end-of-line)
5366                         ;; Highlight the format line
5367                         (cperl-postpone-fontification b1 (point)
5368                                                       'face font-lock-string-face)
5369                         (cperl-commentify b1 (point) nil)
5370                         (cperl-put-do-not-fontify b1 (point) t))))
5371                   ;; We do not search to max, since we may be called from
5372                   ;; some hook of fontification, and max is random
5373                   (re-search-forward "^[.;]$" stop-point 'toend))
5374                 (beginning-of-line)
5375                 (if (looking-at "^\\.$") ; ";" is not supported yet
5376                     (progn
5377                       ;; Highlight the ending delimiter
5378                       (cperl-postpone-fontification (point) (+ (point) 2)
5379                                                     'face font-lock-string-face)
5380                       (cperl-commentify (point) (+ (point) 2) nil)
5381                       (cperl-put-do-not-fontify (point) (+ (point) 2) t))
5382                   (message "End of format `%s' not found." name)
5383                   (or (car err-l) (setcar err-l b)))
5384                 (forward-line)
5385                 (if (> (point) max)
5386                     (setq tmpend tb))
5387                 (put-text-property b (point) 'syntax-type 'format))
5388                ;; qq-like String or Regexp:
5389                ((or (match-beginning 10) (match-beginning 11))
5390                 ;; 1+6+2=9 extra () before this:
5391                 ;; "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>"
5392                 ;; "\\|"
5393                 ;; "\\([?/<]\\)"        ; /blah/ or ?blah? or <file*glob>
5394                 (setq b1 (if (match-beginning 10) 10 11)
5395                       argument (buffer-substring
5396                                 (match-beginning b1) (match-end b1))
5397                       b (point)         ; end of qq etc
5398                       i b
5399                       c (char-after (match-beginning b1))
5400                       bb (char-after (1- (match-beginning b1))) ; tmp holder
5401                       ;; bb == "Not a stringy"
5402                       bb (if (eq b1 10) ; user variables/whatever
5403                              (and (memq bb (append "$@%*#_:-&>" nil)) ; $#y)
5404                                   (cond ((eq bb ?-) (eq c ?s)) ; -s file test
5405                                         ((eq bb ?\:) ; $opt::s
5406                                          (eq (char-after
5407                                               (- (match-beginning b1) 2))
5408                                              ?\:))
5409                                         ((eq bb ?\>) ; $foo->s
5410                                          (eq (char-after
5411                                               (- (match-beginning b1) 2))
5412                                              ?\-))
5413                                         ((eq bb ?\&)
5414                                          (not (eq (char-after ; &&m/blah/
5415                                                    (- (match-beginning b1) 2))
5416                                                   ?\&)))
5417                                         (t t)))
5418                            ;; <file> or <$file>
5419                            (and (eq c ?\<)
5420                                 ;; Do not stringify <FH>, <$fh> :
5421                                 (save-match-data
5422                                   (looking-at
5423                                    "\\$?\\([_a-zA-Z:][_a-zA-Z0-9:]*\\)?>"))))
5424                       tb (match-beginning 0))
5425                 (goto-char (match-beginning b1))
5426                 (cperl-backward-to-noncomment (point-min))
5427                 (or bb
5428                     (if (eq b1 11)      ; bare /blah/ or ?blah? or <foo>
5429                         (setq argument ""
5430                               b1 nil
5431                               bb        ; Not a regexp?
5432                               (not
5433                                ;; What is below: regexp-p?
5434                                (and
5435                                 (or (memq (preceding-char)
5436                                           (append (if (memq c '(?\? ?\<))
5437                                                       ;; $a++ ? 1 : 2
5438                                                       "~{(=|&*!,;:["
5439                                                     "~{(=|&+-*!,;:[") nil))
5440                                     (and (eq (preceding-char) ?\})
5441                                          (cperl-after-block-p (point-min)))
5442                                     (and (eq (char-syntax (preceding-char)) ?w)
5443                                          (progn
5444                                            (forward-sexp -1)
5445 ;;; After these keywords `/' starts a RE.  One should add all the
5446 ;;; functions/builtins which expect an argument, but ...
5447                                            (if (eq (preceding-char) ?-)
5448                                                ;; -d ?foo? is a RE
5449                                                (looking-at "[a-zA-Z]\\>")
5450                                              (and
5451                                               (not (memq (preceding-char)
5452                                                          '(?$ ?@ ?& ?%)))
5453                                               (looking-at
5454                                                "\\(while\\|if\\|unless\\|until\\|and\\|or\\|not\\|xor\\|split\\|grep\\|map\\|print\\)\\>")))))
5455                                     (and (eq (preceding-char) ?.)
5456                                          (eq (char-after (- (point) 2)) ?.))
5457                                     (bobp))
5458                                 ;;  m|blah| ? foo : bar;
5459                                 (not
5460                                  (and (eq c ?\?)
5461                                       cperl-use-syntax-table-text-property
5462                                       (not (bobp))
5463                                       (progn
5464                                         (forward-char -1)
5465                                         (looking-at "\\s|"))))))
5466                               b (1- b))
5467                       ;; s y tr m
5468                       ;; Check for $a -> y
5469                       (setq b1 (preceding-char)
5470                             go (point))
5471                       (if (and (eq b1 ?>)
5472                                (eq (char-after (- go 2)) ?-))
5473                           ;; Not a regexp
5474                           (setq bb t))))
5475                 (or bb
5476                     (progn
5477                       (goto-char b)
5478                       (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
5479                           (goto-char (match-end 0))
5480                         (skip-chars-forward " \t\n\f"))
5481                       (cond ((and (eq (following-char) ?\})
5482                                   (eq b1 ?\{))
5483                              ;; Check for $a[23]->{ s }, @{s} and *{s::foo}
5484                              (goto-char (1- go))
5485                              (skip-chars-backward " \t\n\f")
5486                              (if (memq (preceding-char) (append "$@%&*" nil))
5487                                  (setq bb t) ; @{y}
5488                                (condition-case nil
5489                                    (forward-sexp -1)
5490                                  (error nil)))
5491                              (if (or bb
5492                                      (looking-at ; $foo -> {s}
5493                                       "[$@]\\$*\\([a-zA-Z0-9_:]+\\|[^{]\\)\\([ \t\n]*->\\)?[ \t\n]*{")
5494                                      (and ; $foo[12] -> {s}
5495                                       (memq (following-char) '(?\{ ?\[))
5496                                       (progn
5497                                         (forward-sexp 1)
5498                                         (looking-at "\\([ \t\n]*->\\)?[ \t\n]*{"))))
5499                                  (setq bb t)
5500                                (goto-char b)))
5501                             ((and (eq (following-char) ?=)
5502                                   (eq (char-after (1+ (point))) ?\>))
5503                              ;; Check for { foo => 1, s => 2 }
5504                              ;; Apparently s=> is never a substitution...
5505                              (setq bb t))
5506                             ((and (eq (following-char) ?:)
5507                                   (eq b1 ?\{) ; Check for $ { s::bar }
5508                                   (looking-at "::[a-zA-Z0-9_:]*[ \t\n\f]*}")
5509                                   (progn
5510                                     (goto-char (1- go))
5511                                     (skip-chars-backward " \t\n\f")
5512                                     (memq (preceding-char)
5513                                           (append "$@%&*" nil))))
5514                              (setq bb t))
5515                             ((eobp)
5516                              (setq bb t)))))
5517                 (if bb
5518                     (goto-char i)
5519                   ;; Skip whitespace and comments...
5520                   (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
5521                       (goto-char (match-end 0))
5522                     (skip-chars-forward " \t\n\f"))
5523                   (if (> (point) b)
5524                       (put-text-property b (point) 'syntax-type 'prestring))
5525                   ;; qtag means two-arg matcher, may be reset to
5526                   ;;   2 or 3 later if some special quoting is needed.
5527                   ;; e1 means matching-char matcher.
5528                   (setq b (point)       ; before the first delimiter
5529                         ;; has 2 args
5530                         i2 (string-match "^\\([sy]\\|tr\\)$" argument)
5531                         ;; We do not search to max, since we may be called from
5532                         ;; some hook of fontification, and max is random
5533                         i (cperl-forward-re stop-point end
5534                                             i2
5535                                             st-l err-l argument)
5536                         ;; If `go', then it is considered as 1-arg, `b1' is nil
5537                         ;; as in s/foo//x; the point is before final "slash"
5538                         b1 (nth 1 i)    ; start of the second part
5539                         tag (nth 2 i)   ; ender-char, true if second part
5540                                         ; is with matching chars []
5541                         go (nth 4 i)    ; There is a 1-char part after the end
5542                         i (car i)       ; intermediate point
5543                         e1 (point)      ; end
5544                         ;; Before end of the second part if non-matching: ///
5545                         tail (if (and i (not tag))
5546                                  (1- e1))
5547                         e (if i i e1)   ; end of the first part
5548                         qtag nil        ; need to preserve backslashitis
5549                         is-x-REx nil)   ; REx has //x modifier
5550                   ;; If s{} (), then b/b1 are at "{", "(", e1/i after ")", "}"
5551                   ;; Commenting \\ is dangerous, what about ( ?
5552                   (and i tail
5553                        (eq (char-after i) ?\\)
5554                        (setq qtag t))
5555                   (and (if go (looking-at ".\\sw*x")
5556                          (looking-at "\\sw*x")) ; qr//x
5557                        (setq is-x-REx t))
5558                   (if (null i)
5559                       ;; Considered as 1arg form
5560                       (progn
5561                         (cperl-commentify b (point) t)
5562                         (put-text-property b (point) 'syntax-type 'string)
5563                         (if (or is-x-REx
5564                                 ;; ignore other text properties:
5565                                 (string-match "^qw$" argument))
5566                             (put-text-property b (point) 'indentable t))
5567                         (and go
5568                              (setq e1 (cperl-1+ e1))
5569                              (or (eobp)
5570                                  (forward-char 1))))
5571                     (cperl-commentify b i t)
5572                     (if (looking-at "\\sw*e") ; s///e
5573                         (progn
5574                           ;; Cache the syntax info...
5575                           (setq cperl-syntax-state (cons state-point state))
5576                           (and
5577                            ;; silent:
5578                            (car (cperl-find-pods-heres b1 (1- (point)) t end))
5579                            ;; Error
5580                            (goto-char (1+ max)))
5581                           (if (and tag (eq (preceding-char) ?\>))
5582                               (progn
5583                                 (cperl-modify-syntax-type (1- (point)) cperl-st-ket)
5584                                 (cperl-modify-syntax-type i cperl-st-bra)))
5585                           (put-text-property b i 'syntax-type 'string)
5586                           (if is-x-REx
5587                               (put-text-property b i 'indentable t)))
5588                       (cperl-commentify b1 (point) t)
5589                       (put-text-property b (point) 'syntax-type 'string)
5590                       (if is-x-REx
5591                           (put-text-property b i 'indentable t))
5592                       (if qtag
5593                           (cperl-modify-syntax-type (1+ i) cperl-st-punct))
5594                       (setq tail nil)))
5595                   ;; Now: tail: if the second part is non-matching without ///e
5596                   (if (eq (char-syntax (following-char)) ?w)
5597                       (progn
5598                         (forward-word 1) ; skip modifiers s///s
5599                         (if tail (cperl-commentify tail (point) t))
5600                         (cperl-postpone-fontification
5601                          e1 (point) 'face 'cperl-nonoverridable-face)))
5602                   ;; Check whether it is m// which means "previous match"
5603                   ;; and highlight differently
5604                   (setq is-REx
5605                         (and (string-match "^\\([sm]?\\|qr\\)$" argument)
5606                              (or (not (= (length argument) 0))
5607                                  (not (eq c ?\<)))))
5608                   (if (and is-REx
5609                            (eq e (+ 2 b))
5610                            ;; split // *is* using zero-pattern
5611                            (save-excursion
5612                              (condition-case nil
5613                                  (progn
5614                                    (goto-char tb)
5615                                    (forward-sexp -1)
5616                                    (not (looking-at "split\\>")))
5617                                (error t))))
5618                       (cperl-postpone-fontification
5619                        b e 'face font-lock-function-name-face)
5620                     (if (or i2          ; Has 2 args
5621                             (and cperl-fontify-m-as-s
5622                                  (or
5623                                   (string-match "^\\(m\\|qr\\)$" argument)
5624                                   (and (eq 0 (length argument))
5625                                        (not (eq ?\< (char-after b)))))))
5626                         (progn
5627                           (cperl-postpone-fontification
5628                            b (cperl-1+ b) 'face font-lock-constant-face)
5629                           (cperl-postpone-fontification
5630                            (1- e) e 'face font-lock-constant-face)))
5631                     (if (and is-REx cperl-regexp-scan)
5632                         ;; Process RExen: embedded comments, charclasses and ]
5633                         (save-excursion
5634                           (goto-char (1+ b))
5635                           ;; First 
5636                           (cperl-look-at-leading-count is-x-REx e)
5637                           (setq hairy-RE
5638                                 (concat
5639                                  (if is-x-REx
5640                                      (if (eq (char-after b) ?\#)
5641                                          "\\((\\?\\\\#\\)\\|\\(\\\\#\\)"
5642                                        "\\((\\?#\\)\\|\\(#\\)")
5643                                    ;; keep the same count: add a fake group
5644                                    (if (eq (char-after b) ?\#)
5645                                        "\\((\\?\\\\#\\)\\(\\)"
5646                                      "\\((\\?#\\)\\(\\)"))
5647                                  "\\|"
5648                                     "\\(\\[\\)" ; 3=[
5649                                  "\\|"
5650                                     "\\(]\\)" ; 4=]
5651                                  "\\|"  ; 5=builtin 0-length, 6
5652                                     ;; XXXX: what if u is delim?
5653                                     "\\("
5654                                        "[)^$|]"
5655                                     "\\|"
5656                                        "[*?+]" ; Do not need \?? !
5657                                     "\\|"
5658                                        "{[0-9]+}"
5659                                     "\\|"
5660                                        "{[0-9]+,[0-9]*}"
5661                                     "\\|"
5662                                        "\\\\[luLUEQbBAzZG]"
5663                                     "\\|"
5664                                        "("
5665                                        "\\("
5666                                           "\\?[:=!>]"
5667                                        "\\|"
5668                                           "\\?[-imsx]+[:)]" ; (?i) (?-s:.)
5669                                        "\\|"
5670                                           "\\?([0-9]+)" ; (?(1)foo|bar)
5671                                        "\\|"
5672                                           "\\?<[=!]"
5673                                        "\\|"
5674                                           "\\?" ; (?(?=foo)bar|baz)
5675                                        "\\)?"
5676                                     "\\)"
5677                                  ;; XXXX Need {5,6}?
5678                                  "\\|"
5679                                     "\\\\\\(.\\)" ; 7=\SYMBOL
5680                                  ;; XXXX Will not be able to use it in s)))
5681                                  (if (eq (char-after b) ?\) ) ""
5682                                    (concat
5683                                     "\\|"
5684                                     (if (eq (char-after b) ?? ) ; 8 = (?{
5685                                         "\\((\\\\\\?\\(\\\\\\?\\)?{\\)"
5686                                       "\\((\\?\\(\\?\\)?{\\)"))))) ; 8 = opt ?
5687                           (while
5688                               (and (< (point) (1- e))
5689                                    (re-search-forward hairy-RE (1- e) 'to-end))
5690                             (goto-char (match-beginning 0))
5691                             (setq REx-subgr-start (point)
5692                                   was-subgr t)
5693                             (if (save-excursion
5694                                   (and
5695                                    nil  ; Not needed now, when we skip \SYMBOL
5696                                    (/= (1+ b) (point)) ; \ may be delim
5697                                    (eq (preceding-char) ?\\)
5698                                    (= (% (skip-chars-backward "\\\\") 2)
5699                                       (if (and (eq (char-after b) ?\#)
5700                                                (eq (following-char) ?\#))
5701                                           0
5702                                         -1))))
5703                                 ;; Not a subgr, avoid loop:
5704                                 (progn (setq was-subgr nil)
5705                                        (forward-char 1))
5706                               (cond
5707                                ((match-beginning 5) ; 0-length builtins
5708                                 (setq was-subgr nil) ; We do stuff here
5709                                 (goto-char (match-end 5))
5710                                 (if (>= (point) e)
5711                                     (goto-char (1- e)))
5712                                 (cperl-postpone-fontification
5713                                  (match-beginning 5) (point)
5714                                  'face font-lock-variable-name-face)
5715                                 (if (and (memq (string-to-char (match-string 5))
5716                                                (append "(|" nil))
5717                                          (not (string-match "(\?[-imsx]+)"
5718                                                             (match-string 5))))
5719                                     (cperl-look-at-leading-count is-x-REx e)))
5720                                ((match-beginning 7) ; \SYMBOL
5721                                 (forward-char 2)
5722                                 (if (>= (point) e)
5723                                     (goto-char (1- e))
5724                                   ;; 0-len special-alnums in other branch =>
5725                                   ;; Generic:  \non-alnum (1), \alnum NO
5726                                   ;; Is-delim: \non-alnum (1/spec-2) alnum-1 (=what hai)
5727                                   ;; How many chars to not highlight
5728                                   (setq was-subgr (if (eq (char-after b)
5729                                                           (string-to-char
5730                                                            (match-string 7)))
5731                                                       (if (string-match
5732                                                            "[][)^$|*?+]"
5733                                                            (match-string 7))
5734                                                           0
5735                                                         1)
5736                                                     (if (string-match
5737                                                          "[a-zA-Z0-9]"
5738                                                          (match-string 7))
5739                                                         nil
5740                                                       1)))
5741                                   (if was-subgr
5742                                       (cperl-postpone-fontification
5743                                        (- (point) 2) (- (point) was-subgr)
5744                                        'face font-lock-variable-name-face)))
5745                                 (setq was-subgr nil)) ; We do stuff here
5746                                ((match-beginning 3) ; [charclass]
5747                                 ;; Mismatch for /$patterns->[1]/
5748                                 (forward-char 1)
5749                                 (setq qtag 0) ; leaders
5750                                 (if (eq (char-after b) ?^ )
5751                                     (and (eq (following-char) ?\\ )
5752                                          (eq (char-after (cperl-1+ (point)))
5753                                              ?^ )
5754                                          (forward-char 2))
5755                                   (and (eq (following-char) ?^ )
5756                                        (forward-char 1)))
5757                                 (setq argument b ; continue?
5758                                       tag nil ; list of POSIX classes
5759                                       qtag (point))
5760                                 (if (eq (char-after b) ?\] )
5761                                     (and (eq (following-char) ?\\ )
5762                                          (eq (char-after (cperl-1+ (point)))
5763                                              ?\] )
5764                                          (setq qtag (1+ qtag))
5765                                          (forward-char 2))
5766                                   (and (eq (following-char) ?\] )
5767                                        (forward-char 1)))
5768                                 ;; Apparently, I can't put \] into a charclass
5769                                 ;; in m]]: m][\\\]\]] produces [\\]]
5770 ;;; POSIX?  [:word:] [:^word:] only inside []
5771 ;;;                                    "\\=\\(\\\\.\\|[^][\\\\]\\|\\[:\\^?\sw+:]\\|\\[[^:]\\)*]")
5772                                 (while 
5773                                     (and argument
5774                                          (re-search-forward
5775                                           (if (eq (char-after b) ?\] )
5776                                               "\\=\\(\\\\[^]]\\|[^]\\\\]\\)*\\\\]"
5777                                             "\\=\\(\\\\.\\|[^]\\\\]\\)*]")
5778                                           (1- e) 'toend))
5779                                          ;; Is this ] the end of POSIX class?
5780                                   (if (save-excursion
5781                                         (and
5782                                          (search-backward "[" argument t)
5783                                          (< REx-subgr-start (point))
5784                                          (not
5785                                           (and ; Should work with delim = \
5786                                            (eq (preceding-char) ?\\ )
5787                                            (= (% (skip-chars-backward
5788                                                   "\\\\") 2) 0)))
5789                                          (looking-at
5790                                           (cond
5791                                            ((eq (char-after b) ?\] )
5792                                             "\\\\*\\[:\\^?\\sw+:\\\\\\]")
5793                                            ((eq (char-after b) ?\: )
5794                                             "\\\\*\\[\\\\:\\^?\\sw+\\\\:]")
5795                                            ((eq (char-after b) ?^ )
5796                                             "\\\\*\\[:\\(\\\\\\^\\)?\\sw+:\]")
5797                                            ((eq (char-syntax (char-after b))
5798                                                 ?w)
5799                                             (concat
5800                                              "\\\\*\\[:\\(\\\\\\^\\)?\\(\\\\"
5801                                              (char-to-string (char-after b))
5802                                              "\\|\\sw\\)+:\]"))
5803                                            (t "\\\\*\\[:\\^?\\sw*:]")))
5804                                          (setq argument (point))))
5805                                       (setq tag (cons (cons argument (point))
5806                                                       tag)
5807                                             argument (point)) ; continue
5808                                     (setq argument nil)))
5809                                 (and argument
5810                                      (message "Couldn't find end of charclass in a REx, pos=%s"
5811                                              REx-subgr-start))
5812                                 (if (and cperl-use-syntax-table-text-property
5813                                          (> (- (point) 2) REx-subgr-start))
5814                                     (put-text-property
5815                                      (1+ REx-subgr-start) (1- (point))
5816                                      'syntax-table cperl-st-punct))
5817                                 (cperl-postpone-fontification
5818                                  REx-subgr-start qtag
5819                                  'face font-lock-variable-name-face)
5820                                 (cperl-postpone-fontification
5821                                  (if (eq (char-after b) ?\] )
5822                                      (- (point) 2)
5823                                    (1- (point)))
5824                                  (point) 'face font-lock-variable-name-face)
5825                                 (while tag
5826                                   (cperl-postpone-fontification
5827                                    (car (car tag)) (cdr (car tag))
5828                                    'face font-lock-type-face)
5829                                   (setq tag (cdr tag)))
5830                                 (setq was-subgr nil)) ; did facing already
5831                                ;; Now rare stuff:
5832                                ((and (match-beginning 2) ; #-comment
5833                                      (/= (match-beginning 2) (match-end 2)))
5834                                 (beginning-of-line 2)
5835                                 (if (> (point) e)
5836                                     (goto-char (1- e))))
5837                                ((match-beginning 4) ; character "]"
5838                                 (setq was-subgr nil) ; We do stuff here
5839                                 (goto-char (match-end 0))
5840                                 (if cperl-use-syntax-table-text-property
5841                                     (put-text-property
5842                                      (1- (point)) (point)
5843                                      'syntax-table cperl-st-punct))
5844                                 (cperl-postpone-fontification
5845                                  (1- (point)) (point)
5846                                  'face font-lock-function-name-face))
5847                                ((match-beginning 8) ; (?{})
5848                                 (setq was-subgr (point)
5849                                       tag (match-end 0))
5850                                 (if (or
5851                                      (setq qtag
5852                                            (cperl-forward-group-in-re st-l))
5853                                      (and (>= (point) e)
5854                                           (setq qtag "no matching `)' found"))
5855                                      (and
5856                                       (not (eq (char-after (- (point) 2))
5857                                                ?\} ))
5858                                       (setq qtag "Can't find })")))
5859                                     (progn
5860                                       (goto-char (1- e))
5861                                       (message qtag))
5862                                   (cperl-postpone-fontification
5863                                    (1- tag) (1- (point))
5864                                    'face font-lock-variable-name-face)
5865                                   (if cperl-use-syntax-table-text-property
5866                                       (progn
5867                                         (put-text-property
5868                                          (1- (point)) (point)
5869                                          'syntax-table cperl-st-cfence)
5870                                         (put-text-property
5871                                          was-subgr (1+ was-subgr)
5872                                          'syntax-table cperl-st-cfence))))
5873                                 (setq was-subgr nil))
5874                                (t       ; (?#)-comment
5875                                 ;; Inside "(" and "\" arn't special in any way
5876                                 ;; Works also if the outside delimiters are ().
5877                                 (or ;;(if (eq (char-after b) ?\) )
5878                                         ;;(re-search-forward
5879                                         ;; "[^\\\\]\\(\\\\\\\\\\)*\\\\)"
5880                                         ;; (1- e) 'toend)
5881                                       (search-forward ")" (1- e) 'toend)
5882                                       ;;)
5883                                     (message
5884                                      "Couldn't find end of (?#...)-comment in a REx, pos=%s"
5885                                      REx-subgr-start)))))
5886                             (if (>= (point) e)
5887                                 (goto-char (1- e)))
5888                             (cond
5889                              ((eq was-subgr t)
5890                               (setq REx-subgr-end (point))
5891                               (cperl-commentify
5892                                REx-subgr-start REx-subgr-end nil)
5893                               (cperl-postpone-fontification
5894                                REx-subgr-start REx-subgr-end
5895                                'face font-lock-comment-face))))))
5896                     (if (and is-REx is-x-REx)
5897                         (put-text-property (1+ b) (1- e)
5898                                            'syntax-subtype 'x-REx)))
5899                   (if i2
5900                       (progn
5901                         (cperl-postpone-fontification
5902                          (1- e1) e1 'face font-lock-constant-face)
5903                         (if (assoc (char-after b) cperl-starters)
5904                             (progn
5905                               (cperl-postpone-fontification
5906                                b1 (1+ b1) 'face font-lock-constant-face)
5907                               (put-text-property b1 (1+ b1)
5908                                            'REx-part2 t)))))
5909                   (if (> (point) max)
5910                       (setq tmpend tb))))
5911                ((match-beginning 17)    ; sub with prototype or attribute
5912                 ;; 1+6+2+1+1=11 extra () before this (sub with proto/attr):
5913                 ;;"\\<sub\\>\\("                        ;12
5914                 ;;   cperl-white-and-comment-rex        ;13
5915                 ;;   "\\([a-zA-Z_:'0-9]+\\)\\)?" ; name ;14
5916                 ;;"\\(" cperl-maybe-white-and-comment-rex       ;15,16
5917                 ;;   "\\(([^()]*)\\|:[^:]\\)\\)" ; 17:proto or attribute start
5918                 (setq b1 (match-beginning 14) e1 (match-end 14))
5919                 (if (memq (char-after (1- b))
5920                           '(?\$ ?\@ ?\% ?\& ?\*))
5921                     nil
5922                   (goto-char b)
5923                   (if (eq (char-after (match-beginning 17)) ?\( )
5924                       (progn
5925                         (cperl-commentify ; Prototypes; mark as string
5926                          (match-beginning 17) (match-end 17) t)
5927                         (goto-char (match-end 0))
5928                         ;; Now look for attributes after prototype:
5929                         (forward-comment (buffer-size))
5930                         (and (looking-at ":[^:]")
5931                              (cperl-find-sub-attrs st-l b1 e1 b)))
5932                     ;; treat attributes without prototype
5933                     (goto-char (match-beginning 17))
5934                     (cperl-find-sub-attrs st-l b1 e1 b))))
5935                ;; 1+6+2+1+1+6+1=18 extra () before this:
5936                ;;    "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'")
5937                ((match-beginning 19)    ; old $abc'efg syntax
5938                 (setq bb (match-end 0))
5939                 ;;;(if (nth 3 state) nil        ; in string
5940                 (put-text-property (1- bb) bb 'syntax-table cperl-st-word)
5941                 (goto-char bb))
5942                ;; 1+6+2+1+1+6+1+1=19 extra () before this:
5943                ;; "__\\(END\\|DATA\\)__"
5944                ((match-beginning 20)    ; __END__, __DATA__
5945                 (setq bb (match-end 0))
5946                 ;; (put-text-property b (1+ bb) 'syntax-type 'pod) ; Cheat
5947                 (cperl-commentify b bb nil)
5948                 (setq end t))
5949                ;; "\\\\\\(['`\"($]\\)"
5950                ((match-beginning 21)
5951                 ;; Trailing backslash; make non-quoting outside string/comment
5952                 (setq bb (match-end 0))
5953                 (goto-char b)
5954                 (skip-chars-backward "\\\\")
5955                 ;;;(setq i2 (= (% (skip-chars-backward "\\\\") 2) -1))
5956                 (cperl-modify-syntax-type b cperl-st-punct)
5957                 (goto-char bb))
5958                (t (error "Error in regexp of the sniffer")))
5959               (if (> (point) stop-point)
5960                   (progn
5961                     (if end
5962                         (message "Garbage after __END__/__DATA__ ignored")
5963                       (message "Unbalanced syntax found while scanning")
5964                       (or (car err-l) (setcar err-l b)))
5965                     (goto-char stop-point))))
5966             (setq cperl-syntax-state (cons state-point state)
5967                   ;; Do not mark syntax as done past tmpend???
5968                   cperl-syntax-done-to (or tmpend (max (point) max)))
5969             ;;(message "state-at=%s, done-to=%s" state-point cperl-syntax-done-to)
5970             )
5971           (if (car err-l) (goto-char (car err-l))
5972             (or non-inter
5973                 (message "Scanning for \"hard\" Perl constructions... done"))))
5974       (and (buffer-modified-p)
5975            (not modified)
5976            (set-buffer-modified-p nil))
5977       (set-syntax-table cperl-mode-syntax-table))
5978     (list (car err-l) overshoot)))
5979
5980 (defun cperl-find-pods-heres-region (min max)
5981   (interactive "r")
5982   (cperl-find-pods-heres min max))
5983
5984 (defun cperl-backward-to-noncomment (lim)
5985   ;; Stops at lim or after non-whitespace that is not in comment
5986   ;; XXXX Wrongly understands end-of-multiline strings with # as comment
5987   (let (stop p pr)
5988     (while (and (not stop) (> (point) (or lim (point-min))))
5989       (skip-chars-backward " \t\n\f" lim)
5990       (setq p (point))
5991       (beginning-of-line)
5992       (if (memq (setq pr (get-text-property (point) 'syntax-type))
5993                 '(pod here-doc here-doc-delim))
5994           (cperl-unwind-to-safe nil)
5995         (or (and (looking-at "^[ \t]*\\(#\\|$\\)")
5996                  (not (memq pr '(string prestring))))
5997             (progn (cperl-to-comment-or-eol) (bolp))
5998             (progn
5999               (skip-chars-backward " \t")
6000               (if (< p (point)) (goto-char p))
6001               (setq stop t)))))))
6002
6003 ;; Used only in `cperl-calculate-indent'...
6004 (defun cperl-block-p ()            ; Do not C-M-q !  One string contains ";" !
6005   ;; Positions is before ?\{.  Checks whether it starts a block.
6006   ;; No save-excursion!  This is more a distinguisher of a block/hash ref...
6007   (cperl-backward-to-noncomment (point-min))
6008   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label!  \C-@ at bobp
6009                                         ; Label may be mixed up with `$blah :'
6010       (save-excursion (cperl-after-label))
6011       (get-text-property (cperl-1- (point)) 'attrib-group)
6012       (and (memq (char-syntax (preceding-char)) '(?w ?_))
6013            (progn
6014              (backward-sexp)
6015              ;; sub {BLK}, print {BLK} $data, but NOT `bless', `return', `tr'
6016              (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
6017                       (not (looking-at "\\(bless\\|return\\|q[wqrx]?\\|tr\\|[smy]\\)\\>")))
6018                  ;; sub bless::foo {}
6019                  (progn
6020                    (cperl-backward-to-noncomment (point-min))
6021                    (and (eq (preceding-char) ?b)
6022                         (progn
6023                           (forward-sexp -1)
6024                           (looking-at "sub[ \t\n\f#]")))))))))
6025
6026 ;;; What is the difference of (cperl-after-block-p lim t) and (cperl-block-p)?
6027 ;;; No save-excursion; condition-case ...  In (cperl-block-p) the block
6028 ;;; may be a part of an in-statement construct, such as
6029 ;;;   ${something()}, print {FH} $data.
6030 ;;; Moreover, one takes positive approach (looks for else,grep etc)
6031 ;;; another negative (looks for bless,tr etc)
6032 (defun cperl-after-block-p (lim &optional pre-block)
6033   "Return true if the preceeding } (if PRE-BLOCK, following {) delimits a block.
6034 Would not look before LIM.  Assumes that LIM is a good place to begin a
6035 statement.  The kind of block we treat here is one after which a new
6036 statement would start; thus the block in ${func()} does not count."
6037   (save-excursion
6038     (condition-case nil
6039         (progn
6040           (or pre-block (forward-sexp -1))
6041           (cperl-backward-to-noncomment lim)
6042           (or (eq (point) lim)
6043               ;; if () {}   // sub f () {}   // sub f :a(') {}
6044               (eq (preceding-char) ?\) )
6045               ;; label: {}
6046               (save-excursion (cperl-after-label))
6047               ;; sub :attr {}
6048               (get-text-property (cperl-1- (point)) 'attrib-group)
6049               (if (memq (char-syntax (preceding-char)) '(?w ?_)) ; else {}
6050                   (save-excursion
6051                     (forward-sexp -1)
6052                     ;; else {}     but not    else::func {}
6053                     (or (and (looking-at "\\(else\\|continue\\|grep\\|map\\|BEGIN\\|END\\|CHECK\\|INIT\\)\\>")
6054                              (not (looking-at "\\(\\sw\\|_\\)+::")))
6055                         ;; sub f {}
6056                         (progn
6057                           (cperl-backward-to-noncomment lim)
6058                           (and (eq (preceding-char) ?b)
6059                                (progn
6060                                  (forward-sexp -1)
6061                                  (looking-at "sub[ \t\n\f#]"))))))
6062                 ;; What preceeds is not word...  XXXX Last statement in sub???
6063                 (cperl-after-expr-p lim))))
6064       (error nil))))
6065
6066 (defun cperl-after-expr-p (&optional lim chars test)
6067   "Return true if the position is good for start of expression.
6068 TEST is the expression to evaluate at the found position.  If absent,
6069 CHARS is a string that contains good characters to have before us (however,
6070 `}' is treated \"smartly\" if it is not in the list)."
6071   (let ((lim (or lim (point-min)))
6072         stop p pr)
6073     (cperl-update-syntaxification (point) (point))
6074     (save-excursion
6075       (while (and (not stop) (> (point) lim))
6076         (skip-chars-backward " \t\n\f" lim)
6077         (setq p (point))
6078         (beginning-of-line)
6079         ;;(memq (setq pr (get-text-property (point) 'syntax-type))
6080         ;;      '(pod here-doc here-doc-delim))
6081         (if (get-text-property (point) 'here-doc-group)
6082             (progn
6083               (goto-char
6084                (cperl-beginning-of-property (point) 'here-doc-group))
6085               (beginning-of-line 0)))
6086         (if (get-text-property (point) 'in-pod)
6087             (progn
6088               (goto-char
6089                (cperl-beginning-of-property (point) 'in-pod))
6090               (beginning-of-line 0)))
6091         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
6092           ;; Else: last iteration, or a label
6093           (cperl-to-comment-or-eol)     ; Will not move past "." after a format
6094           (skip-chars-backward " \t")
6095           (if (< p (point)) (goto-char p))
6096           (setq p (point))
6097           (if (and (eq (preceding-char) ?:)
6098                    (progn
6099                      (forward-char -1)
6100                      (skip-chars-backward " \t\n\f" lim)
6101                      (memq (char-syntax (preceding-char)) '(?w ?_))))
6102               (forward-sexp -1)         ; Possibly label.  Skip it
6103             (goto-char p)
6104             (setq stop t))))
6105       (or (bobp)                        ; ???? Needed
6106           (eq (point) lim)
6107           (looking-at "[ \t]*__\\(END\\|DATA\\)__") ; After this anything goes
6108           (progn
6109             (if test (eval test)
6110               (or (memq (preceding-char) (append (or chars "{;") nil))
6111                   (and (eq (preceding-char) ?\})
6112                        (cperl-after-block-p lim))
6113                   (and (eq (following-char) ?.) ; in format: see comment above
6114                        (eq (get-text-property (point) 'syntax-type)
6115                            'format)))))))))
6116
6117 (defun cperl-backward-to-start-of-continued-exp (lim)
6118   (if (memq (preceding-char) (append ")]}\"'`" nil))
6119       (forward-sexp -1))
6120   (beginning-of-line)
6121   (if (<= (point) lim)
6122       (goto-char (1+ lim)))
6123   (skip-chars-forward " \t"))
6124
6125 (defun cperl-after-block-and-statement-beg (lim)
6126   ;; We assume that we are after ?\}
6127   (and
6128    (cperl-after-block-p lim)
6129    (save-excursion
6130      (forward-sexp -1)
6131      (cperl-backward-to-noncomment (point-min))
6132      (or (bobp)
6133          (eq (point) lim)
6134          (not (= (char-syntax (preceding-char)) ?w))
6135          (progn
6136            (forward-sexp -1)
6137            (not
6138             (looking-at
6139              "\\(map\\|grep\\|printf?\\|system\\|exec\\|tr\\|s\\)\\>")))))))
6140
6141 \f
6142 (defvar innerloop-done nil)
6143 (defvar last-depth nil)
6144
6145 (defun cperl-indent-exp ()
6146   "Simple variant of indentation of continued-sexp.
6147
6148 Will not indent comment if it starts at `comment-indent' or looks like
6149 continuation of the comment on the previous line.
6150
6151 If `cperl-indent-region-fix-constructs', will improve spacing on
6152 conditional/loop constructs."
6153   (interactive)
6154   (save-excursion
6155     (let ((tmp-end (progn (end-of-line) (point))) top done)
6156       (save-excursion
6157         (beginning-of-line)
6158         (while (null done)
6159           (setq top (point))
6160           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
6161                                                -1)) -1)
6162             (setq top (point)))         ; Get the outermost parenths in line
6163           (goto-char top)
6164           (while (< (point) tmp-end)
6165             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
6166             (or (eolp) (forward-sexp 1)))
6167           (if (> (point) tmp-end)
6168               (save-excursion
6169                 (end-of-line)
6170                 (setq tmp-end (point)))
6171             (setq done t)))
6172         (goto-char tmp-end)
6173         (setq tmp-end (point-marker)))
6174       (if cperl-indent-region-fix-constructs
6175           (cperl-fix-line-spacing tmp-end))
6176       (cperl-indent-region (point) tmp-end))))
6177
6178 (defun cperl-fix-line-spacing (&optional end parse-data)
6179   "Improve whitespace in a conditional/loop construct.
6180 Returns some position at the last line."
6181   (interactive)
6182   (or end
6183       (setq end (point-max)))
6184   (let ((ee (save-excursion (end-of-line) (point)))
6185         (cperl-indent-region-fix-constructs
6186          (or cperl-indent-region-fix-constructs 1))
6187         p pp ml have-brace ret)
6188     (save-excursion
6189       (beginning-of-line)
6190       (setq ret (point))
6191       ;;  }? continue
6192       ;;  blah; }
6193       (if (not
6194            (or (looking-at "[ \t]*\\(els\\(e\\|if\\)\\|continue\\|if\\|while\\|for\\(each\\)?\\|until\\)")
6195                (setq have-brace (save-excursion (search-forward "}" ee t)))))
6196           nil                           ; Do not need to do anything
6197         ;; Looking at:
6198         ;; }
6199         ;; else
6200         (if (and cperl-merge-trailing-else
6201                  (looking-at
6202                   "[ \t]*}[ \t]*\n[ \t\n]*\\(els\\(e\\|if\\)\\|continue\\)\\>"))
6203             (progn
6204               (search-forward "}")
6205               (setq p (point))
6206               (skip-chars-forward " \t\n")
6207               (delete-region p (point))
6208               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6209               (beginning-of-line)))
6210         ;; Looking at:
6211         ;; }     else
6212         (if (looking-at "[ \t]*}\\(\t*\\|[ \t][ \t]+\\)\\<\\(els\\(e\\|if\\)\\|continue\\)\\>")
6213             (progn
6214               (search-forward "}")
6215               (delete-horizontal-space)
6216               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6217               (beginning-of-line)))
6218         ;; Looking at:
6219         ;; else   {
6220         (if (looking-at
6221              "[ \t]*}?[ \t]*\\<\\(\\els\\(e\\|if\\)\\|continue\\|unless\\|if\\|while\\|for\\(each\\)?\\|until\\)\\>\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
6222             (progn
6223               (forward-word 1)
6224               (delete-horizontal-space)
6225               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6226               (beginning-of-line)))
6227         ;; Looking at:
6228         ;; foreach my    $var
6229         (if (looking-at
6230              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)\\(\t*\\|[ \t][ \t]+\\)[^ \t\n]")
6231             (progn
6232               (forward-word 2)
6233               (delete-horizontal-space)
6234               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6235               (beginning-of-line)))
6236         ;; Looking at:
6237         ;; foreach my $var     (
6238         (if (looking-at
6239              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)[ \t]*\\$[_a-zA-Z0-9]+\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
6240             (progn
6241               (forward-sexp 3)
6242               (delete-horizontal-space)
6243               (insert
6244                (make-string cperl-indent-region-fix-constructs ?\ ))
6245               (beginning-of-line)))
6246         ;; Looking at:
6247         ;; } foreach my $var ()    {
6248         (if (looking-at
6249              "[ \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]*{")
6250             (progn
6251               (setq ml (match-beginning 8))
6252               (re-search-forward "[({]")
6253               (forward-char -1)
6254               (setq p (point))
6255               (if (eq (following-char) ?\( )
6256                   (progn
6257                     (forward-sexp 1)
6258                     (setq pp (point)))
6259                 ;; after `else' or nothing
6260                 (if ml                  ; after `else'
6261                     (skip-chars-backward " \t\n")
6262                   (beginning-of-line))
6263                 (setq pp nil))
6264               ;; Now after the sexp before the brace
6265               ;; Multiline expr should be special
6266               (setq ml (and pp (save-excursion (goto-char p)
6267                                                (search-forward "\n" pp t))))
6268               (if (and (or (not pp) (< pp end))
6269                        (looking-at "[ \t\n]*{"))
6270                   (progn
6271                     (cond
6272                      ((bolp)            ; Were before `{', no if/else/etc
6273                       nil)
6274                      ((looking-at "\\(\t*\\| [ \t]+\\){")
6275                       (delete-horizontal-space)
6276                       (if (if ml
6277                               cperl-extra-newline-before-brace-multiline
6278                             cperl-extra-newline-before-brace)
6279                           (progn
6280                             (delete-horizontal-space)
6281                             (insert "\n")
6282                             (setq ret (point))
6283                             (if (cperl-indent-line parse-data)
6284                                 (progn
6285                                   (cperl-fix-line-spacing end parse-data)
6286                                   (setq ret (point)))))
6287                         (insert
6288                          (make-string cperl-indent-region-fix-constructs ?\ ))))
6289                      ((and (looking-at "[ \t]*\n")
6290                            (not (if ml
6291                                     cperl-extra-newline-before-brace-multiline
6292                                   cperl-extra-newline-before-brace)))
6293                       (setq pp (point))
6294                       (skip-chars-forward " \t\n")
6295                       (delete-region pp (point))
6296                       (insert
6297                        (make-string cperl-indent-region-fix-constructs ?\ ))))
6298                     ;; Now we are before `{'
6299                     (if (looking-at "[ \t\n]*{[ \t]*[^ \t\n#]")
6300                         (progn
6301                           (skip-chars-forward " \t\n")
6302                           (setq pp (point))
6303                           (forward-sexp 1)
6304                           (setq p (point))
6305                           (goto-char pp)
6306                           (setq ml (search-forward "\n" p t))
6307                           (if (or cperl-break-one-line-blocks-when-indent ml)
6308                               ;; not good: multi-line BLOCK
6309                               (progn
6310                                 (goto-char (1+ pp))
6311                                 (delete-horizontal-space)
6312                                 (insert "\n")
6313                                 (setq ret (point))
6314                                 (if (cperl-indent-line parse-data)
6315                                     (setq ret (cperl-fix-line-spacing end parse-data)))))))))))
6316         (beginning-of-line)
6317         (setq p (point) pp (save-excursion (end-of-line) (point))) ; May be different from ee.
6318         ;; Now check whether there is a hanging `}'
6319         ;; Looking at:
6320         ;; } blah
6321         (if (and
6322              cperl-fix-hanging-brace-when-indent
6323              have-brace
6324              (not (looking-at "[ \t]*}[ \t]*\\(\\<\\(els\\(if\\|e\\)\\|continue\\|while\\|until\\)\\>\\|$\\|#\\)"))
6325              (condition-case nil
6326                  (progn
6327                    (up-list 1)
6328                    (if (and (<= (point) pp)
6329                             (eq (preceding-char) ?\} )
6330                             (cperl-after-block-and-statement-beg (point-min)))
6331                        t
6332                      (goto-char p)
6333                      nil))
6334                (error nil)))
6335             (progn
6336               (forward-char -1)
6337               (skip-chars-backward " \t")
6338               (if (bolp)
6339                   ;; `}' was the first thing on the line, insert NL *after* it.
6340                   (progn
6341                     (cperl-indent-line parse-data)
6342                     (search-forward "}")
6343                     (delete-horizontal-space)
6344                     (insert "\n"))
6345                 (delete-horizontal-space)
6346                 (or (eq (preceding-char) ?\;)
6347                     (bolp)
6348                     (and (eq (preceding-char) ?\} )
6349                          (cperl-after-block-p (point-min)))
6350                     (insert ";"))
6351                 (insert "\n")
6352                 (setq ret (point)))
6353               (if (cperl-indent-line parse-data)
6354                   (setq ret (cperl-fix-line-spacing end parse-data)))
6355               (beginning-of-line)))))
6356     ret))
6357
6358 (defvar cperl-update-start)             ; Do not need to make them local
6359 (defvar cperl-update-end)
6360 (defun cperl-delay-update-hook (beg end old-len)
6361   (setq cperl-update-start (min beg (or cperl-update-start (point-max))))
6362   (setq cperl-update-end (max end (or cperl-update-end (point-min)))))
6363
6364 (defun cperl-indent-region (start end)
6365   "Simple variant of indentation of region in CPerl mode.
6366 Should be slow.  Will not indent comment if it starts at `comment-indent'
6367 or looks like continuation of the comment on the previous line.
6368 Indents all the lines whose first character is between START and END
6369 inclusive.
6370
6371 If `cperl-indent-region-fix-constructs', will improve spacing on
6372 conditional/loop constructs."
6373   (interactive "r")
6374   (cperl-update-syntaxification end end)
6375   (save-excursion
6376     (let (cperl-update-start cperl-update-end (h-a-c after-change-functions))
6377       (let ((indent-info (if cperl-emacs-can-parse
6378                              (list nil nil nil) ; Cannot use '(), since will modify
6379                            nil))
6380             (pm 0) (imenu-scanning-message "Indenting... (%3d%%)")
6381             after-change-functions      ; Speed it up!
6382             st comm old-comm-indent new-comm-indent p pp i empty)
6383         (if h-a-c (add-hook 'after-change-functions 'cperl-delay-update-hook))
6384         (goto-char start)
6385         (setq old-comm-indent (and (cperl-to-comment-or-eol)
6386                                    (current-column))
6387               new-comm-indent old-comm-indent)
6388         (goto-char start)
6389         (setq end (set-marker (make-marker) end)) ; indentation changes pos
6390         (or (bolp) (beginning-of-line 2))
6391         (or (fboundp 'imenu-progress-message)
6392             (message "Indenting... For feedback load `imenu'..."))
6393         (while (and (<= (point) end) (not (eobp))) ; bol to check start
6394           (and (fboundp 'imenu-progress-message)
6395                (imenu-progress-message
6396                 pm (/ (* 100 (- (point) start)) (- end start -1))))
6397           (setq st (point))
6398           (if (or
6399                (setq empty (looking-at "[ \t]*\n"))
6400                (and (setq comm (looking-at "[ \t]*#"))
6401                     (or (eq (current-indentation) (or old-comm-indent
6402                                                       comment-column))
6403                         (setq old-comm-indent nil))))
6404               (if (and old-comm-indent
6405                        (not empty)
6406                        (= (current-indentation) old-comm-indent)
6407                        (not (eq (get-text-property (point) 'syntax-type) 'pod))
6408                        (not (eq (get-text-property (point) 'syntax-table)
6409                                 cperl-st-cfence)))
6410                   (let ((comment-column new-comm-indent))
6411                     (indent-for-comment)))
6412             (progn
6413               (setq i (cperl-indent-line indent-info))
6414               (or comm
6415                   (not i)
6416                   (progn
6417                     (if cperl-indent-region-fix-constructs
6418                         (goto-char (cperl-fix-line-spacing end indent-info)))
6419                     (if (setq old-comm-indent
6420                               (and (cperl-to-comment-or-eol)
6421                                    (not (memq (get-text-property (point)
6422                                                                  'syntax-type)
6423                                               '(pod here-doc)))
6424                                    (not (eq (get-text-property (point)
6425                                                                'syntax-table)
6426                                             cperl-st-cfence))
6427                                    (current-column)))
6428                         (progn (indent-for-comment)
6429                                (skip-chars-backward " \t")
6430                                (skip-chars-backward "#")
6431                                (setq new-comm-indent (current-column))))))))
6432           (beginning-of-line 2))
6433         (if (fboundp 'imenu-progress-message)
6434             (imenu-progress-message pm 100)
6435           (message nil)))
6436       ;; Now run the update hooks
6437       (and after-change-functions
6438            cperl-update-end
6439            (save-excursion
6440              (goto-char cperl-update-end)
6441              (insert " ")
6442              (delete-char -1)
6443              (goto-char cperl-update-start)
6444              (insert " ")
6445              (delete-char -1))))))
6446
6447 ;; Stolen from lisp-mode with a lot of improvements
6448
6449 (defun cperl-fill-paragraph (&optional justify iteration)
6450   "Like \\[fill-paragraph], but handle CPerl comments.
6451 If any of the current line is a comment, fill the comment or the
6452 block of it that point is in, preserving the comment's initial
6453 indentation and initial hashes.  Behaves usually outside of comment."
6454   (interactive "P")
6455   (let (;; Non-nil if the current line contains a comment.
6456         has-comment
6457         fill-paragraph-function         ; do not recurse
6458         ;; If has-comment, the appropriate fill-prefix for the comment.
6459         comment-fill-prefix
6460         ;; Line that contains code and comment (or nil)
6461         start
6462         c spaces len dc (comment-column comment-column))
6463     ;; Figure out what kind of comment we are looking at.
6464     (save-excursion
6465       (beginning-of-line)
6466       (cond
6467
6468        ;; A line with nothing but a comment on it?
6469        ((looking-at "[ \t]*#[# \t]*")
6470         (setq has-comment t
6471               comment-fill-prefix (buffer-substring (match-beginning 0)
6472                                                     (match-end 0))))
6473
6474        ;; A line with some code, followed by a comment?  Remember that the
6475        ;; semi which starts the comment shouldn't be part of a string or
6476        ;; character.
6477        ((cperl-to-comment-or-eol)
6478         (setq has-comment t)
6479         (looking-at "#+[ \t]*")
6480         (setq start (point) c (current-column)
6481               comment-fill-prefix
6482               (concat (make-string (current-column) ?\ )
6483                       (buffer-substring (match-beginning 0) (match-end 0)))
6484               spaces (progn (skip-chars-backward " \t")
6485                             (buffer-substring (point) start))
6486               dc (- c (current-column)) len (- start (point))
6487               start (point-marker))
6488         (delete-char len)
6489         (insert (make-string dc ?-))))) ; Placeholder (to avoid splitting???)
6490     (if (not has-comment)
6491         (fill-paragraph justify)       ; Do the usual thing outside of comment
6492       ;; Narrow to include only the comment, and then fill the region.
6493       (save-restriction
6494         (narrow-to-region
6495          ;; Find the first line we should include in the region to fill.
6496          (if start (progn (beginning-of-line) (point))
6497            (save-excursion
6498              (while (and (zerop (forward-line -1))
6499                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
6500              ;; We may have gone to far.  Go forward again.
6501              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
6502                  (forward-line 1))
6503              (point)))
6504          ;; Find the beginning of the first line past the region to fill.
6505          (save-excursion
6506            (while (progn (forward-line 1)
6507                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
6508            (point)))
6509         ;; Remove existing hashes
6510         (goto-char (point-min))
6511         (while (progn (forward-line 1) (< (point) (point-max)))
6512           (skip-chars-forward " \t")
6513           (if (looking-at "#+")
6514               (progn
6515                 (if (and (eq (point) (match-beginning 0))
6516                          (not (eq (point) (match-end 0)))) nil
6517                     (error
6518  "Bug in Emacs: `looking-at' in `narrow-to-region': match-data is garbage"))
6519                 (delete-char (- (match-end 0) (match-beginning 0))))))
6520
6521         ;; Lines with only hashes on them can be paragraph boundaries.
6522         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
6523               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
6524               (fill-prefix comment-fill-prefix))
6525           (fill-paragraph justify)))
6526       (if (and start)
6527           (progn
6528             (goto-char start)
6529             (if (> dc 0)
6530                 (progn (delete-char dc) (insert spaces)))
6531             (if (or (= (current-column) c) iteration) nil
6532               (setq comment-column c)
6533               (indent-for-comment)
6534               ;; Repeat once more, flagging as iteration
6535               (cperl-fill-paragraph justify t))))))
6536   t)
6537
6538 (defun cperl-do-auto-fill ()
6539   ;; Break out if the line is short enough
6540   (if (> (save-excursion
6541            (end-of-line)
6542            (current-column))
6543          fill-column)
6544       (let ((c (save-excursion (beginning-of-line)
6545                                (cperl-to-comment-or-eol) (point)))
6546             (s (memq (following-char) '(?\ ?\t))) marker)
6547         (if (>= c (point)) nil
6548           (setq marker (point-marker))
6549           (cperl-fill-paragraph)
6550           (goto-char marker)
6551           ;; Is not enough, sometimes marker is a start of line
6552           (if (bolp) (progn (re-search-forward "#+[ \t]*")
6553                             (goto-char (match-end 0))))
6554           ;; Following space could have gone:
6555           (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
6556             (insert " ")
6557             (backward-char 1))
6558           ;; Previous space could have gone:
6559           (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
6560
6561 (defun cperl-imenu-addback (lst &optional isback name)
6562   ;; We suppose that the lst is a DAG, unless the first element only
6563   ;; loops back, and ISBACK is set.  Thus this function cannot be
6564   ;; applied twice without ISBACK set.
6565   (cond ((not cperl-imenu-addback) lst)
6566         (t
6567          (or name
6568              (setq name "+++BACK+++"))
6569          (mapcar (lambda (elt)
6570                    (if (and (listp elt) (listp (cdr elt)))
6571                        (progn
6572                          ;; In the other order it goes up
6573                          ;; one level only ;-(
6574                          (setcdr elt (cons (cons name lst)
6575                                            (cdr elt)))
6576                          (cperl-imenu-addback (cdr elt) t name))))
6577                  (if isback (cdr lst) lst))
6578          lst)))
6579
6580 (defun cperl-imenu--create-perl-index (&optional regexp)
6581   (require 'cl)
6582   (require 'imenu)                      ; May be called from TAGS creator
6583   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '())
6584         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
6585         (index-meth-alist '()) meth
6586         packages ends-ranges p marker is-proto
6587         (prev-pos 0) is-pack index index1 name (end-range 0) package)
6588     (goto-char (point-min))
6589     (if noninteractive
6590         (message "Scanning Perl for index")
6591       (imenu-progress-message prev-pos 0))
6592     (cperl-update-syntaxification (point-max) (point-max))
6593     ;; Search for the function
6594     (progn ;;save-match-data
6595       (while (re-search-forward
6596               (or regexp cperl-imenu--function-name-regexp-perl)
6597               nil t)
6598         (or noninteractive
6599             (imenu-progress-message prev-pos))
6600         ;; 2=package-group, 5=package-name 8=sub-name
6601         (cond
6602          ((and                          ; Skip some noise if building tags
6603            (match-beginning 5)          ; package name
6604            ;;(eq (char-after (match-beginning 2)) ?p) ; package
6605            (not (save-match-data
6606                   (looking-at "[ \t\n]*;")))) ; Plain text word 'package'
6607           nil)
6608          ((and
6609            (or (match-beginning 2)
6610                (match-beginning 8))             ; package or sub
6611            ;; Skip if quoted (will not skip multi-line ''-strings :-():
6612            (null (get-text-property (match-beginning 1) 'syntax-table))
6613            (null (get-text-property (match-beginning 1) 'syntax-type))
6614            (null (get-text-property (match-beginning 1) 'in-pod)))
6615           (setq is-pack (match-beginning 2))
6616           ;; (if (looking-at "([^()]*)[ \t\n\f]*")
6617           ;;    (goto-char (match-end 0)))      ; Messes what follows
6618           (setq meth nil
6619                 p (point))
6620           (while (and ends-ranges (>= p (car ends-ranges)))
6621             ;; delete obsolete entries
6622             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
6623           (setq package (or (car packages) "")
6624                 end-range (or (car ends-ranges) 0))
6625           (if is-pack                   ; doing "package"
6626               (progn
6627                 (if (match-beginning 5) ; named package
6628                     (setq name (buffer-substring (match-beginning 5)
6629                                                  (match-end 5))
6630                           name (progn
6631                                  (set-text-properties 0 (length name) nil name)
6632                                  name)
6633                           package (concat name "::")
6634                           name (concat "package " name))
6635                   ;; Support nameless packages
6636                   (setq name "package;" package ""))
6637                 (setq end-range
6638                       (save-excursion
6639                         (parse-partial-sexp (point) (point-max) -1) (point))
6640                       ends-ranges (cons end-range ends-ranges)
6641                       packages (cons package packages)))
6642             (setq is-proto
6643                   (or (eq (following-char) ?\;)
6644                       (eq 0 (get-text-property (point) 'attrib-group)))))
6645           ;; Skip this function name if it is a prototype declaration.
6646           (if (and is-proto (not is-pack)) nil
6647             (or is-pack
6648                 (setq name
6649                       (buffer-substring (match-beginning 8) (match-end 8)))
6650                 (set-text-properties 0 (length name) nil name))
6651             (setq marker (make-marker))
6652             (set-marker marker (match-end (if is-pack 2 8)))
6653             (cond (is-pack nil)
6654                   ((string-match "[:']" name)
6655                    (setq meth t))
6656                   ((> p end-range) nil)
6657                   (t
6658                    (setq name (concat package name) meth t)))
6659             (setq index (cons name marker))
6660             (if is-pack
6661                 (push index index-pack-alist)
6662               (push index index-alist))
6663             (if meth (push index index-meth-alist))
6664             (push index index-unsorted-alist)))
6665          ((match-beginning 16)          ; POD section
6666           (setq name (buffer-substring (match-beginning 17) (match-end 17))
6667                 marker (make-marker))
6668           (set-marker marker (match-beginning 17))
6669           (set-text-properties 0 (length name) nil name)
6670           (setq name (concat (make-string
6671                               (* 3 (- (char-after (match-beginning 16)) ?1))
6672                               ?\ )
6673                              name)
6674                 index (cons name marker))
6675           (setq index1 (cons (concat "=" name) (cdr index)))
6676           (push index index-pod-alist)
6677           (push index1 index-unsorted-alist)))))
6678     (or noninteractive
6679         (imenu-progress-message prev-pos 100))
6680     (setq index-alist
6681           (if (default-value 'imenu-sort-function)
6682               (sort index-alist (default-value 'imenu-sort-function))
6683             (nreverse index-alist)))
6684     (and index-pod-alist
6685          (push (cons "+POD headers+..."
6686                      (nreverse index-pod-alist))
6687                index-alist))
6688     (and (or index-pack-alist index-meth-alist)
6689          (let ((lst index-pack-alist) hier-list pack elt group name)
6690            ;; Remove "package ", reverse and uniquify.
6691            (while lst
6692              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
6693              (if (assoc name hier-list) nil
6694                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
6695            (setq lst index-meth-alist)
6696            (while lst
6697              (setq elt (car lst) lst (cdr lst))
6698              (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
6699                     (setq pack (substring (car elt) 0 (match-beginning 0)))
6700                     (if (setq group (assoc pack hier-list))
6701                         (if (listp (cdr group))
6702                             ;; Have some functions already
6703                             (setcdr group
6704                                     (cons (cons (substring
6705                                                  (car elt)
6706                                                  (+ 2 (match-beginning 0)))
6707                                                 (cdr elt))
6708                                           (cdr group)))
6709                           (setcdr group (list (cons (substring
6710                                                      (car elt)
6711                                                      (+ 2 (match-beginning 0)))
6712                                                     (cdr elt)))))
6713                       (setq hier-list
6714                             (cons (cons pack
6715                                         (list (cons (substring
6716                                                      (car elt)
6717                                                      (+ 2 (match-beginning 0)))
6718                                                     (cdr elt))))
6719                                   hier-list))))))
6720            (push (cons "+Hierarchy+..."
6721                        hier-list)
6722                  index-alist)))
6723     (and index-pack-alist
6724          (push (cons "+Packages+..."
6725                      (nreverse index-pack-alist))
6726                index-alist))
6727     (and (or index-pack-alist index-pod-alist
6728              (default-value 'imenu-sort-function))
6729          index-unsorted-alist
6730          (push (cons "+Unsorted List+..."
6731                      (nreverse index-unsorted-alist))
6732                index-alist))
6733     (cperl-imenu-addback index-alist)))
6734
6735 \f
6736 ;; Suggested by Mark A. Hershberger
6737 (defun cperl-outline-level ()
6738   (looking-at outline-regexp)
6739   (cond ((not (match-beginning 1)) 0)   ; beginning-of-file
6740 ;;;; 2=package-group, 5=package-name 8=sub-name 16=head-level
6741         ((match-beginning 2) 0)         ; package
6742         ((match-beginning 8) 1)         ; sub
6743         ((match-beginning 16)
6744          (- (char-after (match-beginning 16)) ?0)) ; headN ==> N
6745         (t 5)))                         ; should not happen
6746
6747 \f
6748 (defvar cperl-compilation-error-regexp-alist
6749   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORKS).
6750   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
6751      2 3))
6752   "Alist that specifies how to match errors in perl output.")
6753
6754 (if (fboundp 'eval-after-load)
6755     (eval-after-load
6756         "mode-compile"
6757       '(setq perl-compilation-error-regexp-alist
6758              cperl-compilation-error-regexp-alist)))
6759
6760
6761 (defun cperl-windowed-init ()
6762   "Initialization under windowed version."
6763   (if (or (featurep 'ps-print) cperl-faces-init)
6764       ;; Need to init anyway:
6765       (or cperl-faces-init (cperl-init-faces))
6766     (add-hook 'font-lock-mode-hook
6767               (function
6768                (lambda ()
6769                  (if (memq major-mode '(perl-mode cperl-mode))
6770                      (progn
6771                        (or cperl-faces-init (cperl-init-faces)))))))
6772     (if (fboundp 'eval-after-load)
6773         (eval-after-load
6774             "ps-print"
6775           '(or cperl-faces-init (cperl-init-faces))))))
6776
6777 (defun cperl-load-font-lock-keywords ()
6778   (or cperl-faces-init (cperl-init-faces))
6779   perl-font-lock-keywords)
6780
6781 (defun cperl-load-font-lock-keywords-1 ()
6782   (or cperl-faces-init (cperl-init-faces))
6783   perl-font-lock-keywords-1)
6784
6785 (defun cperl-load-font-lock-keywords-2 ()
6786   (or cperl-faces-init (cperl-init-faces))
6787   perl-font-lock-keywords-2)
6788
6789 (defvar perl-font-lock-keywords-1 nil
6790   "Additional expressions to highlight in Perl mode.  Minimal set.")
6791 (defvar perl-font-lock-keywords nil
6792   "Additional expressions to highlight in Perl mode.  Default set.")
6793 (defvar perl-font-lock-keywords-2 nil
6794   "Additional expressions to highlight in Perl mode.  Maximal set.")
6795
6796 (defvar font-lock-background-mode)
6797 (defvar font-lock-display-type)
6798 (defun cperl-init-faces-weak ()
6799   ;; Allow `cperl-find-pods-heres' to run.
6800   (or (boundp 'font-lock-constant-face)
6801       (cperl-force-face font-lock-constant-face
6802                         "Face for constant and label names")
6803       ;;(setq font-lock-constant-face 'font-lock-constant-face)
6804       ))
6805
6806 (defun cperl-init-faces ()
6807   (condition-case errs
6808       (progn
6809         (require 'font-lock)
6810         (and (fboundp 'font-lock-fontify-anchored-keywords)
6811              (featurep 'font-lock-extra)
6812              (message "You have an obsolete package `font-lock-extra'.  Install `choose-color'."))
6813         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
6814           (if (fboundp 'font-lock-fontify-anchored-keywords)
6815               (setq font-lock-anchored t))
6816           (setq
6817            t-font-lock-keywords
6818            (list
6819             (list "[ \t]+$" 0 cperl-invalid-face t)
6820             (cons
6821              (concat
6822               "\\(^\\|[^$@%&\\]\\)\\<\\("
6823               (mapconcat
6824                'identity
6825                '("if" "until" "while" "elsif" "else" "unless" "for"
6826                  "foreach" "continue" "exit" "die" "last" "goto" "next"
6827                  "redo" "return" "local" "exec" "sub" "do" "dump" "use" "our"
6828                  "require" "package" "eval" "my" "BEGIN" "END" "CHECK" "INIT")
6829                "\\|")                   ; Flow control
6830               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
6831                                         ; In what follows we use `type' style
6832                                         ; for overwritable builtins
6833             (list
6834              (concat
6835               "\\(^\\|[^$@%&\\]\\)\\<\\("
6836               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm"
6837               ;; "and" "atan2" "bind" "binmode" "bless" "caller"
6838               ;; "chdir" "chmod" "chown" "chr" "chroot" "close"
6839               ;; "closedir" "cmp" "connect" "continue" "cos" "crypt"
6840               ;; "dbmclose" "dbmopen" "die" "dump" "endgrent"
6841               ;; "endhostent" "endnetent" "endprotoent" "endpwent"
6842               ;; "endservent" "eof" "eq" "exec" "exit" "exp" "fcntl"
6843               ;; "fileno" "flock" "fork" "formline" "ge" "getc"
6844               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr"
6845               ;; "gethostbyname" "gethostent" "getlogin"
6846               ;; "getnetbyaddr" "getnetbyname" "getnetent"
6847               ;; "getpeername" "getpgrp" "getppid" "getpriority"
6848               ;; "getprotobyname" "getprotobynumber" "getprotoent"
6849               ;; "getpwent" "getpwnam" "getpwuid" "getservbyname"
6850               ;; "getservbyport" "getservent" "getsockname"
6851               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int"
6852               ;; "ioctl" "join" "kill" "lc" "lcfirst" "le" "length"
6853               ;; "link" "listen" "localtime" "lock" "log" "lstat" "lt"
6854               ;; "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd" "ne"
6855               ;; "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
6856               ;; "quotemeta" "rand" "read" "readdir" "readline"
6857               ;; "readlink" "readpipe" "recv" "ref" "rename" "require"
6858               ;; "reset" "reverse" "rewinddir" "rindex" "rmdir" "seek"
6859               ;; "seekdir" "select" "semctl" "semget" "semop" "send"
6860               ;; "setgrent" "sethostent" "setnetent" "setpgrp"
6861               ;; "setpriority" "setprotoent" "setpwent" "setservent"
6862               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite"
6863               ;; "shutdown" "sin" "sleep" "socket" "socketpair"
6864               ;; "sprintf" "sqrt" "srand" "stat" "substr" "symlink"
6865               ;; "syscall" "sysopen" "sysread" "system" "syswrite" "tell"
6866               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst"
6867               ;; "umask" "unlink" "unpack" "utime" "values" "vec"
6868               ;; "wait" "waitpid" "wantarray" "warn" "write" "x" "xor"
6869               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|"
6870               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
6871               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
6872               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
6873               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
6874               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
6875               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
6876               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
6877               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
6878               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
6879               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
6880               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
6881               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
6882               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
6883               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
6884               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
6885               "\\(\\|ngth\\)\\|o\\(c\\(altime\\|k\\)\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
6886               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
6887               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
6888               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
6889               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
6890               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
6891               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
6892               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
6893               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
6894               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|open\\|tem\\|write\\)\\|"
6895               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
6896               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
6897               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
6898               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
6899               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\|PACKAGE__\\)"
6900               "\\)\\>") 2 'font-lock-type-face)
6901             ;; In what follows we use `other' style
6902             ;; for nonoverwritable builtins
6903             ;; Somehow 's', 'm' are not auto-generated???
6904             (list
6905              (concat
6906               "\\(^\\|[^$@%&\\]\\)\\<\\("
6907               ;; "AUTOLOAD" "BEGIN" "CHECK" "DESTROY" "END" "INIT" "__END__" "chomp"
6908               ;; "chop" "defined" "delete" "do" "each" "else" "elsif"
6909               ;; "eval" "exists" "for" "foreach" "format" "goto"
6910               ;; "grep" "if" "keys" "last" "local" "map" "my" "next"
6911               ;; "no" "our" "package" "pop" "pos" "print" "printf" "push"
6912               ;; "q" "qq" "qw" "qx" "redo" "return" "scalar" "shift"
6913               ;; "sort" "splice" "split" "study" "sub" "tie" "tr"
6914               ;; "undef" "unless" "unshift" "untie" "until" "use"
6915               ;; "while" "y"
6916               "AUTOLOAD\\|BEGIN\\|CHECK\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
6917               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
6918               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|INIT\\|if\\|keys\\|"
6919               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|our\\|"
6920               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
6921               "q\\(\\|q\\|w\\|x\\|r\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
6922               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
6923               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
6924               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
6925               "\\|[sm]"                 ; Added manually
6926               "\\)\\>") 2 'cperl-nonoverridable-face)
6927             ;;          (mapconcat 'identity
6928             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
6929             ;;                       "#include" "#define" "#undef")
6930             ;;                     "\\|")
6931             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
6932               font-lock-function-name-face keep) ; Not very good, triggers at "[a-z]"
6933             ;; This highlights declarations and definitions differenty.
6934             ;; We do not try to highlight in the case of attributes:
6935             ;; it is already done by `cperl-find-pods-heres'
6936             (list (concat "\\<sub"
6937                           cperl-white-and-comment-rex ; whitespace/comments
6938                           "\\([^ \n\t{;()]+\\)" ; 2=name (assume non-anonymous)
6939                           "\\("
6940                             cperl-maybe-white-and-comment-rex ;whitespace/comments?
6941                             "([^()]*)\\)?" ; prototype
6942                           cperl-maybe-white-and-comment-rex ; whitespace/comments?
6943                           "[{;]")
6944                   2 (if cperl-font-lock-multiline
6945                         '(if (eq (char-after (cperl-1- (match-end 0))) ?\{ )
6946                              'font-lock-function-name-face
6947                            'font-lock-variable-name-face)
6948                       ;; need to manually set 'multiline' for older font-locks
6949                       '(progn
6950                          (if (< 1 (count-lines (match-beginning 0)
6951                                                (match-end 0)))
6952                              (put-text-property
6953                               (+ 3 (match-beginning 0)) (match-end 0)
6954                               'syntax-type 'multiline))
6955                          (if (eq (char-after (cperl-1- (match-end 0))) ?\{ )
6956                              'font-lock-function-name-face
6957                            'font-lock-variable-name-face))))
6958             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
6959               2 font-lock-function-name-face)
6960             '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
6961               1 font-lock-function-name-face)
6962             (cond ((featurep 'font-lock-extra)
6963                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
6964                      (2 font-lock-string-face t)
6965                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
6966                   (font-lock-anchored
6967                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
6968                      (2 font-lock-string-face t)
6969                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
6970                       nil nil
6971                       (1 font-lock-string-face t))))
6972                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
6973                        2 font-lock-string-face t)))
6974             '("[\[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
6975               font-lock-string-face t)
6976             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1
6977               font-lock-constant-face)  ; labels
6978             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
6979               2 font-lock-constant-face)
6980             ;; Uncomment to get perl-mode-like vars
6981             ;;; '("[$*]{?\\(\\sw+\\)" 1 font-lock-variable-name-face)
6982             ;;; '("\\([@%]\\|\\$#\\)\\(\\sw+\\)"
6983             ;;;  (2 (cons font-lock-variable-name-face '(underline))))
6984             (cond ((featurep 'font-lock-extra)
6985                    '("^[ \t]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
6986                      (3 font-lock-variable-name-face)
6987                      (4 '(another 4 nil
6988                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
6989                                    (1 font-lock-variable-name-face)
6990                                    (2 '(restart 2 nil) nil t)))
6991                         nil t)))        ; local variables, multiple
6992                   (font-lock-anchored
6993                    ;; 1=my_etc, 2=white? 3=(+white? 4=white? 5=var
6994                    (` ((, (concat "\\<\\(my\\|local\\|our\\)"
6995                                   cperl-maybe-white-and-comment-rex
6996                                   "\\(("
6997                                      cperl-maybe-white-and-comment-rex
6998                                   "\\)?\\([$@%*]\\([a-zA-Z0-9_:]+\\|[^a-zA-Z0-9_]\\)\\)"))
6999                        (5 (, (if cperl-font-lock-multiline
7000                                  'font-lock-variable-name-face
7001                                '(progn  (setq cperl-font-lock-multiline-start
7002                                               (match-beginning 0))
7003                                         'font-lock-variable-name-face))))
7004                        ((, (concat "\\="
7005                                    cperl-maybe-white-and-comment-rex
7006                                    ","
7007                                    cperl-maybe-white-and-comment-rex
7008                                    "\\([$@%*]\\([a-zA-Z0-9_:]+\\|[^a-zA-Z0-9_]\\)\\)"))
7009                         ;; Bug in font-lock: limit is used not only to limit 
7010                         ;; searches, but to set the "extend window for
7011                         ;; facification" property.  Thus we need to minimize.
7012                         (, (if cperl-font-lock-multiline
7013                              '(if (match-beginning 3)
7014                                   (save-excursion
7015                                     (goto-char (match-beginning 3))
7016                                     (condition-case nil
7017                                         (forward-sexp 1)
7018                                       (error
7019                                        (condition-case nil
7020                                            (forward-char 200)
7021                                          (error nil)))) ; typeahead
7022                                     (1- (point))) ; report limit
7023                                 (forward-char -2)) ; disable continued expr
7024                              '(if (match-beginning 3)
7025                                   (point-max) ; No limit for continuation
7026                                 (forward-char -2)))) ; disable continued expr
7027                         (, (if cperl-font-lock-multiline
7028                                nil
7029                              '(progn    ; Do at end
7030                                 ;; "my" may be already fontified (POD),
7031                                 ;; so cperl-font-lock-multiline-start is nil
7032                                 (if (or (not cperl-font-lock-multiline-start)
7033                                         (> 2 (count-lines
7034                                               cperl-font-lock-multiline-start
7035                                               (point))))
7036                                     nil
7037                                   (put-text-property
7038                                    (1+ cperl-font-lock-multiline-start) (point)
7039                                    'syntax-type 'multiline))
7040                                 (setq cperl-font-lock-multiline-start nil))))
7041                         (3 font-lock-variable-name-face)))))
7042                   (t '("^[ \t{}]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
7043                        3 font-lock-variable-name-face)))
7044             '("\\<for\\(each\\)?\\([ \t]+\\(my\\|local\\|our\\)\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
7045               4 font-lock-variable-name-face)))
7046           (setq
7047            t-font-lock-keywords-1
7048            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
7049                 ;; not yet as of XEmacs 19.12, works with 21.1.11
7050                 (or
7051                  (not cperl-xemacs-p)
7052                  (string< "21.1.9" emacs-version)
7053                  (and (string< "21.1.10" emacs-version)
7054                       (string< emacs-version "21.1.2")))
7055                 '(
7056                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
7057                    (if (eq (char-after (match-beginning 2)) ?%)
7058                        cperl-hash-face
7059                      cperl-array-face)
7060                    t)                   ; arrays and hashes
7061                   ("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
7062                    1
7063                    (if (= (- (match-end 2) (match-beginning 2)) 1)
7064                        (if (eq (char-after (match-beginning 3)) ?{)
7065                            cperl-hash-face
7066                          cperl-array-face) ; arrays and hashes
7067                      font-lock-variable-name-face) ; Just to put something
7068                    t)
7069                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
7070                        ;;; Too much noise from \s* @s[ and friends
7071                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)"
7072                   ;;(3 font-lock-function-name-face t t)
7073                   ;;(4
7074                   ;; (if (cperl-slash-is-regexp)
7075                   ;;    font-lock-function-name-face 'default) nil t))
7076                   )))
7077           (if cperl-highlight-variables-indiscriminately
7078               (setq t-font-lock-keywords-1
7079                     (append t-font-lock-keywords-1
7080                             (list '("[$*]{?\\(\\sw+\\)" 1
7081                                     font-lock-variable-name-face)))))
7082           (setq perl-font-lock-keywords-1
7083                 (if cperl-syntaxify-by-font-lock
7084                     (cons 'cperl-fontify-update
7085                           t-font-lock-keywords)
7086                   t-font-lock-keywords)
7087                 perl-font-lock-keywords perl-font-lock-keywords-1
7088                 perl-font-lock-keywords-2 (append
7089                                            perl-font-lock-keywords-1
7090                                            t-font-lock-keywords-1)))
7091         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
7092         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
7093             (eval                       ; Avoid a warning
7094              '(font-lock-require-faces
7095                (list
7096                 ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
7097                 (list 'font-lock-comment-face
7098                       ["Firebrick"      "OrangeRed"     "DimGray"       "Gray80"]
7099                       nil
7100                       [nil              nil             t               t       t]
7101                       [nil              nil             t               t       t]
7102                       nil)
7103                 (list 'font-lock-string-face
7104                       ["RosyBrown"      "LightSalmon"   "Gray50"        "LightGray"]
7105                       nil
7106                       nil
7107                       [nil              nil             t               t       t]
7108                       nil)
7109                 (list 'font-lock-function-name-face
7110                       (vector
7111                        "Blue"           "LightSkyBlue"  "Gray50"        "LightGray"
7112                        (cdr (assq 'background-color ; if mono
7113                                   (frame-parameters))))
7114                       (vector
7115                        nil              nil             nil             nil
7116                        (cdr (assq 'foreground-color ; if mono
7117                                   (frame-parameters))))
7118                       [nil              nil             t               t       t]
7119                       nil
7120                       nil)
7121                 (list 'font-lock-variable-name-face
7122                       ["DarkGoldenrod"  "LightGoldenrod" "DimGray"      "Gray90"]
7123                       nil
7124                       [nil              nil             t               t       t]
7125                       [nil              nil             t               t       t]
7126                       nil)
7127                 (list 'font-lock-type-face
7128                       ["DarkOliveGreen" "PaleGreen"     "DimGray"       "Gray80"]
7129                       nil
7130                       [nil              nil             t               t       t]
7131                       nil
7132                       [nil              nil             t               t       t])
7133                 (list 'font-lock-constant-face
7134                       ["CadetBlue"      "Aquamarine"    "Gray50"        "LightGray"]
7135                       nil
7136                       [nil              nil             t               t       t]
7137                       nil
7138                       [nil              nil             t               t       t])
7139                 (list 'cperl-nonoverridable-face
7140                       ["chartreuse3"    ("orchid1" "orange")
7141                        nil              "Gray80"]
7142                       [nil              nil             "gray90"]
7143                       [nil              nil             nil             t       t]
7144                       [nil              nil             t               t]
7145                       [nil              nil             t               t       t])
7146                 (list 'cperl-array-face
7147                       ["blue"           "yellow"        nil             "Gray80"]
7148                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
7149                        "gray90"]
7150                       t
7151                       nil
7152                       nil)
7153                 (list 'cperl-hash-face
7154                       ["red"            "red"           nil             "Gray80"]
7155                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
7156                        "gray90"]
7157                       t
7158                       t
7159                       nil))))
7160           ;; Do it the dull way, without choose-color
7161           (defvar cperl-guessed-background nil
7162             "Display characteristics as guessed by cperl.")
7163           ;;      (or (fboundp 'x-color-defined-p)
7164           ;;          (defalias 'x-color-defined-p
7165           ;;            (cond ((fboundp 'color-defined-p) 'color-defined-p)
7166           ;;                  ;; XEmacs >= 19.12
7167           ;;                  ((fboundp 'valid-color-name-p) 'valid-color-name-p)
7168           ;;                  ;; XEmacs 19.11
7169           ;;                  (t 'x-valid-color-name-p))))
7170           (cperl-force-face font-lock-constant-face
7171                             "Face for constant and label names")
7172           (cperl-force-face font-lock-variable-name-face
7173                             "Face for variable names")
7174           (cperl-force-face font-lock-type-face
7175                             "Face for data types")
7176           (cperl-force-face cperl-nonoverridable-face
7177                             "Face for data types from another group")
7178           (cperl-force-face font-lock-comment-face
7179                             "Face for comments")
7180           (cperl-force-face font-lock-function-name-face
7181                             "Face for function names")
7182           (cperl-force-face cperl-hash-face
7183                             "Face for hashes")
7184           (cperl-force-face cperl-array-face
7185                             "Face for arrays")
7186           ;;(defvar font-lock-constant-face 'font-lock-constant-face)
7187           ;;(defvar font-lock-variable-name-face 'font-lock-variable-name-face)
7188           ;;(or (boundp 'font-lock-type-face)
7189           ;;    (defconst font-lock-type-face
7190           ;;    'font-lock-type-face
7191           ;;    "Face to use for data types."))
7192           ;;(or (boundp 'cperl-nonoverridable-face)
7193           ;;    (defconst cperl-nonoverridable-face
7194           ;;    'cperl-nonoverridable-face
7195           ;;    "Face to use for data types from another group."))
7196           ;;(if (not cperl-xemacs-p) nil
7197           ;;  (or (boundp 'font-lock-comment-face)
7198           ;;    (defconst font-lock-comment-face
7199           ;;      'font-lock-comment-face
7200           ;;      "Face to use for comments."))
7201           ;;  (or (boundp 'font-lock-keyword-face)
7202           ;;    (defconst font-lock-keyword-face
7203           ;;      'font-lock-keyword-face
7204           ;;      "Face to use for keywords."))
7205           ;;  (or (boundp 'font-lock-function-name-face)
7206           ;;    (defconst font-lock-function-name-face
7207           ;;      'font-lock-function-name-face
7208           ;;      "Face to use for function names.")))
7209           (if (and
7210                (not (cperl-is-face 'cperl-array-face))
7211                (cperl-is-face 'font-lock-emphasized-face))
7212               (copy-face 'font-lock-emphasized-face 'cperl-array-face))
7213           (if (and
7214                (not (cperl-is-face 'cperl-hash-face))
7215                (cperl-is-face 'font-lock-other-emphasized-face))
7216               (copy-face 'font-lock-other-emphasized-face
7217                          'cperl-hash-face))
7218           (if (and
7219                (not (cperl-is-face 'cperl-nonoverridable-face))
7220                (cperl-is-face 'font-lock-other-type-face))
7221               (copy-face 'font-lock-other-type-face
7222                          'cperl-nonoverridable-face))
7223           ;;(or (boundp 'cperl-hash-face)
7224           ;;    (defconst cperl-hash-face
7225           ;;    'cperl-hash-face
7226           ;;    "Face to use for hashes."))
7227           ;;(or (boundp 'cperl-array-face)
7228           ;;    (defconst cperl-array-face
7229           ;;    'cperl-array-face
7230           ;;    "Face to use for arrays."))
7231           ;; Here we try to guess background
7232           (let ((background
7233                  (if (boundp 'font-lock-background-mode)
7234                      font-lock-background-mode
7235                    'light))
7236                 (face-list (and (fboundp 'face-list) (face-list))))
7237 ;;;;        (fset 'cperl-is-face
7238 ;;;;              (cond ((fboundp 'find-face)
7239 ;;;;                     (symbol-function 'find-face))
7240 ;;;;                    (face-list
7241 ;;;;                     (function (lambda (face) (member face face-list))))
7242 ;;;;                    (t
7243 ;;;;                     (function (lambda (face) (boundp face))))))
7244             (defvar cperl-guessed-background
7245               (if (and (boundp 'font-lock-display-type)
7246                        (eq font-lock-display-type 'grayscale))
7247                   'gray
7248                 background)
7249               "Background as guessed by CPerl mode")
7250             (and (not (cperl-is-face 'font-lock-constant-face))
7251                  (cperl-is-face 'font-lock-reference-face)
7252                  (copy-face 'font-lock-reference-face 'font-lock-constant-face))
7253             (if (cperl-is-face 'font-lock-type-face) nil
7254               (copy-face 'default 'font-lock-type-face)
7255               (cond
7256                ((eq background 'light)
7257                 (set-face-foreground 'font-lock-type-face
7258                                      (if (x-color-defined-p "seagreen")
7259                                          "seagreen"
7260                                        "sea green")))
7261                ((eq background 'dark)
7262                 (set-face-foreground 'font-lock-type-face
7263                                      (if (x-color-defined-p "os2pink")
7264                                          "os2pink"
7265                                        "pink")))
7266                (t
7267                 (set-face-background 'font-lock-type-face "gray90"))))
7268             (if (cperl-is-face 'cperl-nonoverridable-face)
7269                 nil
7270               (copy-face 'font-lock-type-face 'cperl-nonoverridable-face)
7271               (cond
7272                ((eq background 'light)
7273                 (set-face-foreground 'cperl-nonoverridable-face
7274                                      (if (x-color-defined-p "chartreuse3")
7275                                          "chartreuse3"
7276                                        "chartreuse")))
7277                ((eq background 'dark)
7278                 (set-face-foreground 'cperl-nonoverridable-face
7279                                      (if (x-color-defined-p "orchid1")
7280                                          "orchid1"
7281                                        "orange")))))
7282 ;;;         (if (cperl-is-face 'font-lock-other-emphasized-face) nil
7283 ;;;           (copy-face 'bold-italic 'font-lock-other-emphasized-face)
7284 ;;;           (cond
7285 ;;;            ((eq background 'light)
7286 ;;;             (set-face-background 'font-lock-other-emphasized-face
7287 ;;;                                  (if (x-color-defined-p "lightyellow2")
7288 ;;;                                      "lightyellow2"
7289 ;;;                                    (if (x-color-defined-p "lightyellow")
7290 ;;;                                        "lightyellow"
7291 ;;;                                      "light yellow"))))
7292 ;;;            ((eq background 'dark)
7293 ;;;             (set-face-background 'font-lock-other-emphasized-face
7294 ;;;                                  (if (x-color-defined-p "navy")
7295 ;;;                                      "navy"
7296 ;;;                                    (if (x-color-defined-p "darkgreen")
7297 ;;;                                        "darkgreen"
7298 ;;;                                      "dark green"))))
7299 ;;;            (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
7300 ;;;         (if (cperl-is-face 'font-lock-emphasized-face) nil
7301 ;;;           (copy-face 'bold 'font-lock-emphasized-face)
7302 ;;;           (cond
7303 ;;;            ((eq background 'light)
7304 ;;;             (set-face-background 'font-lock-emphasized-face
7305 ;;;                                  (if (x-color-defined-p "lightyellow2")
7306 ;;;                                      "lightyellow2"
7307 ;;;                                    "lightyellow")))
7308 ;;;            ((eq background 'dark)
7309 ;;;             (set-face-background 'font-lock-emphasized-face
7310 ;;;                                  (if (x-color-defined-p "navy")
7311 ;;;                                      "navy"
7312 ;;;                                    (if (x-color-defined-p "darkgreen")
7313 ;;;                                        "darkgreen"
7314 ;;;                                      "dark green"))))
7315 ;;;            (t (set-face-background 'font-lock-emphasized-face "gray90"))))
7316             (if (cperl-is-face 'font-lock-variable-name-face) nil
7317               (copy-face 'italic 'font-lock-variable-name-face))
7318             (if (cperl-is-face 'font-lock-constant-face) nil
7319               (copy-face 'italic 'font-lock-constant-face))))
7320         (setq cperl-faces-init t))
7321     (error (message "cperl-init-faces (ignored): %s" errs))))
7322
7323
7324 (defun cperl-ps-print-init ()
7325   "Initialization of `ps-print' components for faces used in CPerl."
7326   (eval-after-load "ps-print"
7327     '(setq ps-bold-faces
7328            ;;                   font-lock-variable-name-face
7329            ;;                   font-lock-constant-face
7330            (append '(cperl-array-face
7331                      cperl-hash-face)
7332                    ps-bold-faces)
7333            ps-italic-faces
7334            ;;                   font-lock-constant-face
7335            (append '(cperl-nonoverridable-face
7336                      cperl-hash-face)
7337                    ps-italic-faces)
7338            ps-underlined-faces
7339            ;;        font-lock-type-face
7340            (append '(cperl-array-face
7341                      cperl-hash-face
7342                      underline
7343                      cperl-nonoverridable-face)
7344                    ps-underlined-faces))))
7345
7346 (defvar ps-print-face-extension-alist)
7347
7348 (defun cperl-ps-print (&optional file)
7349   "Pretty-print in CPerl style.
7350 If optional argument FILE is an empty string, prints to printer, otherwise
7351 to the file FILE.  If FILE is nil, prompts for a file name.
7352
7353 Style of printout regulated by the variable `cperl-ps-print-face-properties'."
7354   (interactive)
7355   (or file
7356       (setq file (read-from-minibuffer
7357                   "Print to file (if empty - to printer): "
7358                   (concat (buffer-file-name) ".ps")
7359                   nil nil 'file-name-history)))
7360   (or (> (length file) 0)
7361       (setq file nil))
7362   (require 'ps-print)                   ; To get ps-print-face-extension-alist
7363   (let ((ps-print-color-p t)
7364         (ps-print-face-extension-alist ps-print-face-extension-alist))
7365     (cperl-ps-extend-face-list cperl-ps-print-face-properties)
7366     (ps-print-buffer-with-faces file)))
7367
7368 ;;; (defun cperl-ps-print-init ()
7369 ;;;   "Initialization of `ps-print' components for faces used in CPerl."
7370 ;;;   ;; Guard against old versions
7371 ;;;   (defvar ps-underlined-faces nil)
7372 ;;;   (defvar ps-bold-faces nil)
7373 ;;;   (defvar ps-italic-faces nil)
7374 ;;;   (setq ps-bold-faces
7375 ;;;     (append '(font-lock-emphasized-face
7376 ;;;               cperl-array-face
7377 ;;;               font-lock-keyword-face
7378 ;;;               font-lock-variable-name-face
7379 ;;;               font-lock-constant-face
7380 ;;;               font-lock-reference-face
7381 ;;;               font-lock-other-emphasized-face
7382 ;;;               cperl-hash-face)
7383 ;;;             ps-bold-faces))
7384 ;;;   (setq ps-italic-faces
7385 ;;;     (append '(cperl-nonoverridable-face
7386 ;;;               font-lock-constant-face
7387 ;;;               font-lock-reference-face
7388 ;;;               font-lock-other-emphasized-face
7389 ;;;               cperl-hash-face)
7390 ;;;             ps-italic-faces))
7391 ;;;   (setq ps-underlined-faces
7392 ;;;     (append '(font-lock-emphasized-face
7393 ;;;               cperl-array-face
7394 ;;;               font-lock-other-emphasized-face
7395 ;;;               cperl-hash-face
7396 ;;;               cperl-nonoverridable-face font-lock-type-face)
7397 ;;;             ps-underlined-faces))
7398 ;;;   (cons 'font-lock-type-face ps-underlined-faces))
7399
7400
7401 (if (cperl-enable-font-lock) (cperl-windowed-init))
7402
7403 (defconst cperl-styles-entries
7404   '(cperl-indent-level cperl-brace-offset cperl-continued-brace-offset
7405     cperl-label-offset cperl-extra-newline-before-brace
7406     cperl-merge-trailing-else
7407     cperl-continued-statement-offset))
7408
7409 (defconst cperl-style-alist
7410   '(("CPerl"                         ; =GNU without extra-newline-before-brace
7411      (cperl-indent-level               .  2)
7412      (cperl-brace-offset               .  0)
7413      (cperl-continued-brace-offset     .  0)
7414      (cperl-label-offset               . -2)
7415      (cperl-extra-newline-before-brace .  nil)
7416      (cperl-merge-trailing-else        .  t)
7417      (cperl-continued-statement-offset .  2))
7418     ("PerlStyle"                        ; CPerl with 4 as indent
7419      (cperl-indent-level               .  4)
7420      (cperl-brace-offset               .  0)
7421      (cperl-continued-brace-offset     .  0)
7422      (cperl-label-offset               . -4)
7423      (cperl-extra-newline-before-brace .  nil)
7424      (cperl-merge-trailing-else        .  t)
7425      (cperl-continued-statement-offset .  4))
7426     ("GNU"
7427      (cperl-indent-level               .  2)
7428      (cperl-brace-offset               .  0)
7429      (cperl-continued-brace-offset     .  0)
7430      (cperl-label-offset               . -2)
7431      (cperl-extra-newline-before-brace .  t)
7432      (cperl-merge-trailing-else        .  nil)
7433      (cperl-continued-statement-offset .  2))
7434     ("K&R"
7435      (cperl-indent-level               .  5)
7436      (cperl-brace-offset               .  0)
7437      (cperl-continued-brace-offset     . -5)
7438      (cperl-label-offset               . -5)
7439      ;;(cperl-extra-newline-before-brace .  nil) ; ???
7440      (cperl-merge-trailing-else        .  nil)
7441      (cperl-continued-statement-offset .  5))
7442     ("BSD"
7443      (cperl-indent-level               .  4)
7444      (cperl-brace-offset               .  0)
7445      (cperl-continued-brace-offset     . -4)
7446      (cperl-label-offset               . -4)
7447      ;;(cperl-extra-newline-before-brace .  nil) ; ???
7448      (cperl-continued-statement-offset .  4))
7449     ("C++"
7450      (cperl-indent-level               .  4)
7451      (cperl-brace-offset               .  0)
7452      (cperl-continued-brace-offset     . -4)
7453      (cperl-label-offset               . -4)
7454      (cperl-continued-statement-offset .  4)
7455      (cperl-merge-trailing-else        .  nil)
7456      (cperl-extra-newline-before-brace .  t))
7457     ("Current")
7458     ("Whitesmith"
7459      (cperl-indent-level               .  4)
7460      (cperl-brace-offset               .  0)
7461      (cperl-continued-brace-offset     .  0)
7462      (cperl-label-offset               . -4)
7463      ;;(cperl-extra-newline-before-brace .  nil) ; ???
7464      (cperl-continued-statement-offset .  4)))
7465   "(Experimental) list of variables to set to get a particular indentation style.
7466 Should be used via `cperl-set-style' or via Perl menu.")
7467
7468 (defun cperl-set-style (style)
7469   "Set CPerl mode variables to use one of several different indentation styles.
7470 The arguments are a string representing the desired style.
7471 The list of styles is in `cperl-style-alist', available styles
7472 are GNU, K&R, BSD, C++ and Whitesmith.
7473
7474 The current value of style is memorized (unless there is a memorized
7475 data already), may be restored by `cperl-set-style-back'.
7476
7477 Chosing \"Current\" style will not change style, so this may be used for
7478 side-effect of memorizing only."
7479   (interactive
7480    (let ((list (mapcar (function (lambda (elt) (list (car elt))))
7481                        cperl-style-alist)))
7482      (list (completing-read "Enter style: " list nil 'insist))))
7483   (or cperl-old-style
7484       (setq cperl-old-style
7485             (mapcar (function
7486                      (lambda (name)
7487                        (cons name (eval name))))
7488                     cperl-styles-entries)))
7489   (let ((style (cdr (assoc style cperl-style-alist))) setting str sym)
7490     (while style
7491       (setq setting (car style) style (cdr style))
7492       (set (car setting) (cdr setting)))))
7493
7494 (defun cperl-set-style-back ()
7495   "Restore a style memorised by `cperl-set-style'."
7496   (interactive)
7497   (or cperl-old-style (error "The style was not changed"))
7498   (let (setting)
7499     (while cperl-old-style
7500       (setq setting (car cperl-old-style)
7501             cperl-old-style (cdr cperl-old-style))
7502       (set (car setting) (cdr setting)))))
7503
7504 (defun cperl-check-syntax ()
7505   (interactive)
7506   (require 'mode-compile)
7507   (let ((perl-dbg-flags (concat cperl-extra-perl-args " -wc")))
7508     (eval '(mode-compile))))            ; Avoid a warning
7509
7510 (defun cperl-info-buffer (type)
7511   ;; Returns buffer with documentation.  Creates if missing.
7512   ;; If TYPE, this vars buffer.
7513   ;; Special care is taken to not stomp over an existing info buffer
7514   (let* ((bname (if type "*info-perl-var*" "*info-perl*"))
7515          (info (get-buffer bname))
7516          (oldbuf (get-buffer "*info*")))
7517     (if info info
7518       (save-window-excursion
7519         ;; Get Info running
7520         (require 'info)
7521         (cond (oldbuf
7522                (set-buffer oldbuf)
7523                (rename-buffer "*info-perl-tmp*")))
7524         (save-window-excursion
7525           (info))
7526         (Info-find-node cperl-info-page (if type "perlvar" "perlfunc"))
7527         (set-buffer "*info*")
7528         (rename-buffer bname)
7529         (cond (oldbuf
7530                (set-buffer "*info-perl-tmp*")
7531                (rename-buffer "*info*")
7532                (set-buffer bname)))
7533         (make-local-variable 'window-min-height)
7534         (setq window-min-height 2)
7535         (current-buffer)))))
7536
7537 (defun cperl-word-at-point (&optional p)
7538   "Return the word at point or at P."
7539   (save-excursion
7540     (if p (goto-char p))
7541     (or (cperl-word-at-point-hard)
7542         (progn
7543           (require 'etags)
7544           (funcall (or (and (boundp 'find-tag-default-function)
7545                             find-tag-default-function)
7546                        (get major-mode 'find-tag-default-function)
7547                        ;; XEmacs 19.12 has `find-tag-default-hook'; it is
7548                        ;; automatically used within `find-tag-default':
7549                        'find-tag-default))))))
7550
7551 (defun cperl-info-on-command (command)
7552   "Show documentation for Perl command COMMAND in other window.
7553 If perl-info buffer is shown in some frame, uses this frame.
7554 Customized by setting variables `cperl-shrink-wrap-info-frame',
7555 `cperl-max-help-size'."
7556   (interactive
7557    (let* ((default (cperl-word-at-point))
7558           (read (read-string
7559                  (format "Find doc for Perl function (default %s): "
7560                          default))))
7561      (list (if (equal read "")
7562                default
7563              read))))
7564
7565   (let ((buffer (current-buffer))
7566         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
7567         pos isvar height iniheight frheight buf win fr1 fr2 iniwin not-loner
7568         max-height char-height buf-list)
7569     (if (string-match "^-[a-zA-Z]$" command)
7570         (setq cmd-desc "^-X[ \t\n]"))
7571     (setq isvar (string-match "^[$@%]" command)
7572           buf (cperl-info-buffer isvar)
7573           iniwin (selected-window)
7574           fr1 (window-frame iniwin))
7575     (set-buffer buf)
7576     (goto-char (point-min))
7577     (or isvar
7578         (progn (re-search-forward "^-X[ \t\n]")
7579                (forward-line -1)))
7580     (if (re-search-forward cmd-desc nil t)
7581         (progn
7582           ;; Go back to beginning of the group (ex, for qq)
7583           (if (re-search-backward "^[ \t\n\f]")
7584               (forward-line 1))
7585           (beginning-of-line)
7586           ;; Get some of
7587           (setq pos (point)
7588                 buf-list (list buf "*info-perl-var*" "*info-perl*"))
7589           (while (and (not win) buf-list)
7590             (setq win (get-buffer-window (car buf-list) t))
7591             (setq buf-list (cdr buf-list)))
7592           (or (not win)
7593               (eq (window-buffer win) buf)
7594               (set-window-buffer win buf))
7595           (and win (setq fr2 (window-frame win)))
7596           (if (or (not fr2) (eq fr1 fr2))
7597               (pop-to-buffer buf)
7598             (special-display-popup-frame buf) ; Make it visible
7599             (select-window win))
7600           (goto-char pos)               ; Needed (?!).
7601           ;; Resize
7602           (setq iniheight (window-height)
7603                 frheight (frame-height)
7604                 not-loner (< iniheight (1- frheight))) ; Are not alone
7605           (cond ((if not-loner cperl-max-help-size
7606                    cperl-shrink-wrap-info-frame)
7607                  (setq height
7608                        (+ 2
7609                           (count-lines
7610                            pos
7611                            (save-excursion
7612                              (if (re-search-forward
7613                                   "^[ \t][^\n]*\n+\\([^ \t\n\f]\\|\\'\\)" nil t)
7614                                  (match-beginning 0) (point-max)))))
7615                        max-height
7616                        (if not-loner
7617                            (/ (* (- frheight 3) cperl-max-help-size) 100)
7618                          (setq char-height (frame-char-height))
7619                          ;; Non-functioning under OS/2:
7620                          (if (eq char-height 1) (setq char-height 18))
7621                          ;; Title, menubar, + 2 for slack
7622                          (- (/ (x-display-pixel-height) char-height) 4)))
7623                  (if (> height max-height) (setq height max-height))
7624                  ;;(message "was %s doing %s" iniheight height)
7625                  (if not-loner
7626                      (enlarge-window (- height iniheight))
7627                    (set-frame-height (window-frame win) (1+ height)))))
7628           (set-window-start (selected-window) pos))
7629       (message "No entry for %s found." command))
7630     ;;(pop-to-buffer buffer)
7631     (select-window iniwin)))
7632
7633 (defun cperl-info-on-current-command ()
7634   "Show documentation for Perl command at point in other window."
7635   (interactive)
7636   (cperl-info-on-command (cperl-word-at-point)))
7637
7638 (defun cperl-imenu-info-imenu-search ()
7639   (if (looking-at "^-X[ \t\n]") nil
7640     (re-search-backward
7641      "^\n\\([-a-zA-Z_]+\\)[ \t\n]")
7642     (forward-line 1)))
7643
7644 (defun cperl-imenu-info-imenu-name ()
7645   (buffer-substring
7646    (match-beginning 1) (match-end 1)))
7647
7648 (defun cperl-imenu-on-info ()
7649   "Shows imenu for Perl Info Buffer.
7650 Opens Perl Info buffer if needed."
7651   (interactive)
7652   (let* ((buffer (current-buffer))
7653          imenu-create-index-function
7654          imenu-prev-index-position-function
7655          imenu-extract-index-name-function
7656          (index-item (save-restriction
7657                        (save-window-excursion
7658                          (set-buffer (cperl-info-buffer nil))
7659                          (setq imenu-create-index-function
7660                                'imenu-default-create-index-function
7661                                imenu-prev-index-position-function
7662                                'cperl-imenu-info-imenu-search
7663                                imenu-extract-index-name-function
7664                                'cperl-imenu-info-imenu-name)
7665                          (imenu-choose-buffer-index)))))
7666     (and index-item
7667          (progn
7668            (push-mark)
7669            (pop-to-buffer "*info-perl*")
7670            (cond
7671             ((markerp (cdr index-item))
7672              (goto-char (marker-position (cdr index-item))))
7673             (t
7674              (goto-char (cdr index-item))))
7675            (set-window-start (selected-window) (point))
7676            (pop-to-buffer buffer)))))
7677
7678 (defun cperl-lineup (beg end &optional step minshift)
7679   "Lineup construction in a region.
7680 Beginning of region should be at the start of a construction.
7681 All first occurrences of this construction in the lines that are
7682 partially contained in the region are lined up at the same column.
7683
7684 MINSHIFT is the minimal amount of space to insert before the construction.
7685 STEP is the tabwidth to position constructions.
7686 If STEP is nil, `cperl-lineup-step' will be used
7687 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
7688 Will not move the position at the start to the left."
7689   (interactive "r")
7690   (let (search col tcol seen b)
7691     (save-excursion
7692       (goto-char end)
7693       (end-of-line)
7694       (setq end (point-marker))
7695       (goto-char beg)
7696       (skip-chars-forward " \t\f")
7697       (setq beg (point-marker))
7698       (indent-region beg end nil)
7699       (goto-char beg)
7700       (setq col (current-column))
7701       (if (looking-at "[a-zA-Z0-9_]")
7702           (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
7703               (setq search
7704                     (concat "\\<"
7705                             (regexp-quote
7706                              (buffer-substring (match-beginning 0)
7707                                                (match-end 0))) "\\>"))
7708             (error "Cannot line up in a middle of the word"))
7709         (if (looking-at "$")
7710             (error "Cannot line up end of line"))
7711         (setq search (regexp-quote (char-to-string (following-char)))))
7712       (setq step (or step cperl-lineup-step cperl-indent-level))
7713       (or minshift (setq minshift 1))
7714       (while (progn
7715                (beginning-of-line 2)
7716                (and (< (point) end)
7717                     (re-search-forward search end t)
7718                     (goto-char (match-beginning 0))))
7719         (setq tcol (current-column) seen t)
7720         (if (> tcol col) (setq col tcol)))
7721       (or seen
7722           (error "The construction to line up occurred only once"))
7723       (goto-char beg)
7724       (setq col (+ col minshift))
7725       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
7726       (while
7727           (progn
7728             (cperl-make-indent col)
7729             (beginning-of-line 2)
7730             (and (< (point) end)
7731                  (re-search-forward search end t)
7732                  (goto-char (match-beginning 0)))))))) ; No body
7733
7734 (defun cperl-etags (&optional add all files) ;; NOT USED???
7735   "Run etags with appropriate options for Perl files.
7736 If optional argument ALL is `recursive', will process Perl files
7737 in subdirectories too."
7738   (interactive)
7739   (let ((cmd "etags")
7740         (args '("-l" "none" "-r"
7741                 ;;       1=fullname  2=package?             3=name                       4=proto?             5=attrs? (VERY APPROX!)
7742                 "/\\<sub[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)\\)[ \\t]*\\(([^()]*)[ \t]*\\)?\\([ \t]*:[^#{;]*\\)?\\([{#]\\|$\\)/\\3/"
7743                 "-r"
7744                 "/\\<package[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)\\)[ \\t]*\\([#;]\\|$\\)/\\1/"
7745                 "-r"
7746                 "/\\<\\(package\\)[ \\t]*;/\\1;/"))
7747         res)
7748     (if add (setq args (cons "-a" args)))
7749     (or files (setq files (list buffer-file-name)))
7750     (cond
7751      ((eq all 'recursive)
7752       ;;(error "Not implemented: recursive")
7753       (setq args (append (list "-e"
7754                                "sub wanted {push @ARGV, $File::Find::name if /\\.[pP][Llm]$/}
7755                                 use File::Find;
7756                                 find(\\&wanted, '.');
7757                                 exec @ARGV;"
7758                                cmd) args)
7759             cmd "perl"))
7760      (all
7761       ;;(error "Not implemented: all")
7762       (setq args (append (list "-e"
7763                                "push @ARGV, <*.PL *.pl *.pm>;
7764                                 exec @ARGV;"
7765                                cmd) args)
7766             cmd "perl"))
7767      (t
7768       (setq args (append args files))))
7769     (setq res (apply 'call-process cmd nil nil nil args))
7770     (or (eq res 0)
7771         (message "etags returned \"%s\"" res))))
7772
7773 (defun cperl-toggle-auto-newline ()
7774   "Toggle the state of `cperl-auto-newline'."
7775   (interactive)
7776   (setq cperl-auto-newline (not cperl-auto-newline))
7777   (message "Newlines will %sbe auto-inserted now."
7778            (if cperl-auto-newline "" "not ")))
7779
7780 (defun cperl-toggle-abbrev ()
7781   "Toggle the state of automatic keyword expansion in CPerl mode."
7782   (interactive)
7783   (abbrev-mode (if abbrev-mode 0 1))
7784   (message "Perl control structure will %sbe auto-inserted now."
7785            (if abbrev-mode "" "not ")))
7786
7787
7788 (defun cperl-toggle-electric ()
7789   "Toggle the state of parentheses doubling in CPerl mode."
7790   (interactive)
7791   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
7792   (message "Parentheses will %sbe auto-doubled now."
7793            (if (cperl-val 'cperl-electric-parens) "" "not ")))
7794
7795 (defun cperl-toggle-autohelp ()
7796   "Toggle the state of Auto-Help on Perl constructs (put in the message area).
7797 Delay of auto-help controlled by `cperl-lazy-help-time'."
7798   (interactive)
7799   (if (fboundp 'run-with-idle-timer)
7800       (progn
7801         (if cperl-lazy-installed
7802             (cperl-lazy-unstall)
7803           (cperl-lazy-install))
7804         (message "Perl help messages will %sbe automatically shown now."
7805                  (if cperl-lazy-installed "" "not ")))
7806     (message "Cannot automatically show Perl help messages - run-with-idle-timer missing.")))
7807
7808 (defun cperl-toggle-construct-fix ()
7809   "Toggle whether `indent-region'/`indent-sexp' fix whitespace too."
7810   (interactive)
7811   (setq cperl-indent-region-fix-constructs
7812         (if cperl-indent-region-fix-constructs
7813             nil
7814           1))
7815   (message "indent-region/indent-sexp will %sbe automatically fix whitespace."
7816            (if cperl-indent-region-fix-constructs "" "not ")))
7817
7818 (defun cperl-toggle-set-debug-unwind (arg &optional backtrace)
7819   "Toggle (or, with numeric argument, set) debugging state of syntaxification.
7820 Nonpositive numeric argument disables debugging messages.  The message
7821 summarizes which regions it was decided to rescan for syntactic constructs.
7822
7823 The message looks like this:
7824
7825   Syxify req=123..138 actual=101..146 done-to: 112=>146 statepos: 73=>117
7826
7827 Numbers are character positions in the buffer.  REQ provides the range to
7828 rescan requested by `font-lock'.  ACTUAL is the range actually resyntaxified;
7829 for correct operation it should start and end outside any special syntactic
7830 construct.  DONE-TO and STATEPOS indicate changes to internal caches maintained
7831 by CPerl."
7832   (interactive "P")
7833   (or arg
7834       (setq arg (if (eq cperl-syntaxify-by-font-lock 
7835                         (if backtrace 'backtrace 'message)) 0 1)))
7836   (setq arg (if (> arg 0) (if backtrace 'backtrace 'message) t))
7837   (setq cperl-syntaxify-by-font-lock arg)
7838   (message "Debugging messages of syntax unwind %sabled."
7839            (if (eq arg t) "dis" "en")))
7840
7841 ;;;; Tags file creation.
7842
7843 (defvar cperl-tmp-buffer " *cperl-tmp*")
7844
7845 (defun cperl-setup-tmp-buf ()
7846   (set-buffer (get-buffer-create cperl-tmp-buffer))
7847   (set-syntax-table cperl-mode-syntax-table)
7848   (buffer-disable-undo)
7849   (auto-fill-mode 0)
7850   (if cperl-use-syntax-table-text-property-for-tags
7851       (progn
7852         (make-local-variable 'parse-sexp-lookup-properties)
7853         ;; Do not introduce variable if not needed, we check it!
7854         (set 'parse-sexp-lookup-properties t))))
7855
7856 (defun cperl-xsub-scan ()
7857   (require 'cl)
7858   (require 'imenu)
7859   (let ((index-alist '())
7860         (prev-pos 0) index index1 name package prefix)
7861     (goto-char (point-min))
7862     (if noninteractive
7863         (message "Scanning XSUB for index")
7864       (imenu-progress-message prev-pos 0))
7865     ;; Search for the function
7866     (progn ;;save-match-data
7867       (while (re-search-forward
7868               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
7869               nil t)
7870         (or noninteractive
7871             (imenu-progress-message prev-pos))
7872         (cond
7873          ((match-beginning 2)           ; SECTION
7874           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
7875           (goto-char (match-beginning 0))
7876           (skip-chars-forward " \t")
7877           (forward-char 1)
7878           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
7879               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
7880             (setq prefix nil)))
7881          ((not package) nil)            ; C language section
7882          ((match-beginning 3)           ; XSUB
7883           (goto-char (1+ (match-beginning 3)))
7884           (setq index (imenu-example--name-and-position))
7885           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
7886           (if (and prefix (string-match (concat "^" prefix) name))
7887               (setq name (substring name (length prefix))))
7888           (cond ((string-match "::" name) nil)
7889                 (t
7890                  (setq index1 (cons (concat package "::" name) (cdr index)))
7891                  (push index1 index-alist)))
7892           (setcar index name)
7893           (push index index-alist))
7894          (t                             ; BOOT: section
7895           ;; (beginning-of-line)
7896           (setq index (imenu-example--name-and-position))
7897           (setcar index (concat package "::BOOT:"))
7898           (push index index-alist)))))
7899     (or noninteractive
7900         (imenu-progress-message prev-pos 100))
7901     index-alist))
7902
7903 (defvar cperl-unreadable-ok nil)
7904
7905 (defun cperl-find-tags (ifile xs topdir)
7906   (let ((b (get-buffer cperl-tmp-buffer)) ind lst elt pos ret rel
7907         (cperl-pod-here-fontify nil) f file)
7908     (save-excursion
7909       (if b (set-buffer b)
7910         (cperl-setup-tmp-buf))
7911       (erase-buffer)
7912       (condition-case err
7913           (setq file (car (insert-file-contents ifile)))
7914         (error (if cperl-unreadable-ok nil
7915                  (if (y-or-n-p
7916                       (format "File %s unreadable.  Continue? " ifile))
7917                      (setq cperl-unreadable-ok t)
7918                    (error "Aborting: unreadable file %s" ifile)))))
7919       (if (not file)
7920           (message "Unreadable file %s" ifile)
7921         (message "Scanning file %s ..." file)
7922         (if (and cperl-use-syntax-table-text-property-for-tags
7923                  (not xs))
7924             (condition-case err         ; after __END__ may have garbage
7925                 (cperl-find-pods-heres nil nil noninteractive)
7926               (error (message "While scanning for syntax: %s" err))))
7927         (if xs
7928             (setq lst (cperl-xsub-scan))
7929           (setq ind (cperl-imenu--create-perl-index))
7930           (setq lst (cdr (assoc "+Unsorted List+..." ind))))
7931         (setq lst
7932               (mapcar
7933                (function
7934                 (lambda (elt)
7935                   (cond ((string-match "^[_a-zA-Z]" (car elt))
7936                          (goto-char (cdr elt))
7937                          (beginning-of-line) ; pos should be of the start of the line
7938                          (list (car elt)
7939                                (point)
7940                                (1+ (count-lines 1 (point))) ; 1+ since at beg-o-l
7941                                (buffer-substring (progn
7942                                                    (goto-char (cdr elt))
7943                                                    ;; After name now...
7944                                                    (or (eolp) (forward-char 1))
7945                                                    (point))
7946                                                  (progn
7947                                                    (beginning-of-line)
7948                                                    (point))))))))
7949                lst))
7950         (erase-buffer)
7951         (while lst
7952           (setq elt (car lst) lst (cdr lst))
7953           (if elt
7954               (progn
7955                 (insert (elt elt 3)
7956                         127
7957                         (if (string-match "^package " (car elt))
7958                             (substring (car elt) 8)
7959                           (car elt) )
7960                         1
7961                         (number-to-string (elt elt 2)) ; Line
7962                         ","
7963                         (number-to-string (1- (elt elt 1))) ; Char pos 0-based
7964                         "\n")
7965                 (if (and (string-match "^[_a-zA-Z]+::" (car elt))
7966                          (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
7967                                        (elt elt 3)))
7968                     ;; Need to insert the name without package as well
7969                     (setq lst (cons (cons (substring (elt elt 3)
7970                                                      (match-beginning 1)
7971                                                      (match-end 1))
7972                                           (cdr elt))
7973                                     lst))))))
7974         (setq pos (point))
7975         (goto-char 1)
7976         (setq rel file)
7977         ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
7978         (set-text-properties 0 (length rel) nil rel)
7979         (and (equal topdir (substring rel 0 (length topdir)))
7980              (setq rel (substring file (length topdir))))
7981         (insert "\f\n" rel "," (number-to-string (1- pos)) "\n")
7982         (setq ret (buffer-substring 1 (point-max)))
7983         (erase-buffer)
7984         (or noninteractive
7985             (message "Scanning file %s finished" file))
7986         ret))))
7987
7988 (defun cperl-add-tags-recurse-noxs ()
7989   "Add to TAGS data for \"pure\" Perl files in the current directory and kids.
7990 Use as
7991   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
7992         -f cperl-add-tags-recurse-noxs
7993 "
7994   (cperl-write-tags nil nil t t nil t))
7995
7996 (defun cperl-add-tags-recurse-noxs-fullpath ()
7997   "Add to TAGS data for \"pure\" Perl in the current directory and kids.
7998 Writes down fullpath, so TAGS is relocatable (but if the build directory
7999 is relocated, the file TAGS inside it breaks). Use as
8000   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
8001         -f cperl-add-tags-recurse-noxs-fullpath
8002 "
8003   (cperl-write-tags nil nil t t nil t ""))
8004
8005 (defun cperl-add-tags-recurse ()
8006   "Add to TAGS file data for Perl files in the current directory and kids.
8007 Use as
8008   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
8009         -f cperl-add-tags-recurse
8010 "
8011   (cperl-write-tags nil nil t t))
8012
8013 (defun cperl-write-tags (&optional file erase recurse dir inbuffer noxs topdir)
8014   ;; If INBUFFER, do not select buffer, and do not save
8015   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
8016   (require 'etags)
8017   (if file nil
8018     (setq file (if dir default-directory (buffer-file-name)))
8019     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
8020   (or topdir
8021       (setq topdir default-directory))
8022   (let ((tags-file-name "TAGS")
8023         (case-fold-search (eq system-type 'emx))
8024         xs rel tm)
8025     (save-excursion
8026       (cond (inbuffer nil)              ; Already there
8027             ((file-exists-p tags-file-name)
8028              (if cperl-xemacs-p
8029                  (visit-tags-table-buffer)
8030                (visit-tags-table-buffer tags-file-name)))
8031             (t (set-buffer (find-file-noselect tags-file-name))))
8032       (cond
8033        (dir
8034         (cond ((eq erase 'ignore))
8035               (erase
8036                (erase-buffer)
8037                (setq erase 'ignore)))
8038         (let ((files
8039                (condition-case err
8040                    (directory-files file t
8041                                     (if recurse nil cperl-scan-files-regexp)
8042                                     t)
8043                  (error
8044                   (if cperl-unreadable-ok nil
8045                     (if (y-or-n-p
8046                          (format "Directory %s unreadable.  Continue? " file))
8047                         (setq cperl-unreadable-ok t
8048                               tm nil)   ; Return empty list
8049                       (error "Aborting: unreadable directory %s" file)))))))
8050           (mapcar (function
8051                    (lambda (file)
8052                      (cond
8053                       ((string-match cperl-noscan-files-regexp file)
8054                        nil)
8055                       ((not (file-directory-p file))
8056                        (if (string-match cperl-scan-files-regexp file)
8057                            (cperl-write-tags file erase recurse nil t noxs topdir)))
8058                       ((not recurse) nil)
8059                       (t (cperl-write-tags file erase recurse t t noxs topdir)))))
8060                   files)))
8061        (t
8062         (setq xs (string-match "\\.xs$" file))
8063         (if (not (and xs noxs))
8064             (progn
8065               (cond ((eq erase 'ignore) (goto-char (point-max)))
8066                     (erase (erase-buffer))
8067                     (t
8068                      (goto-char 1)
8069                      (setq rel file)
8070                      ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
8071                      (set-text-properties 0 (length rel) nil rel)
8072                      (and (equal topdir (substring rel 0 (length topdir)))
8073                           (setq rel (substring file (length topdir))))
8074                      (if (search-forward (concat "\f\n" rel ",") nil t)
8075                          (progn
8076                            (search-backward "\f\n")
8077                            (delete-region (point)
8078                                           (save-excursion
8079                                             (forward-char 1)
8080                                             (if (search-forward "\f\n"
8081                                                                 nil 'toend)
8082                                                 (- (point) 2)
8083                                               (point-max)))))
8084                        (goto-char (point-max)))))
8085               (insert (cperl-find-tags file xs topdir))))))
8086       (if inbuffer nil                  ; Delegate to the caller
8087         (save-buffer 0)                 ; No backup
8088         (if (fboundp 'initialize-new-tags-table) ; Do we need something special in XEmacs?
8089             (initialize-new-tags-table))))))
8090
8091 (defvar cperl-tags-hier-regexp-list
8092   (concat
8093    "^\\("
8094       "\\(package\\)\\>"
8095      "\\|"
8096       "sub\\>[^\n]+::"
8097      "\\|"
8098       "[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::" ; XSUB?
8099      "\\|"
8100       "[ \t]*BOOT:\C-?[^\n]+::"         ; BOOT section
8101    "\\)"))
8102
8103 (defvar cperl-hierarchy '(() ())
8104   "Global hierarchy of classes.")
8105
8106 (defun cperl-tags-hier-fill ()
8107   ;; Suppose we are in a tag table cooked by cperl.
8108   (goto-char 1)
8109   (let (type pack name pos line chunk ord cons1 file str info fileind)
8110     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
8111       (setq pos (match-beginning 0)
8112             pack (match-beginning 2))
8113       (beginning-of-line)
8114       (if (looking-at (concat
8115                        "\\([^\n]+\\)"
8116                        "\C-?"
8117                        "\\([^\n]+\\)"
8118                        "\C-a"
8119                        "\\([0-9]+\\)"
8120                        ","
8121                        "\\([0-9]+\\)"))
8122           (progn
8123             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
8124                   name (buffer-substring (match-beginning 2) (match-end 2))
8125                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
8126                   line (buffer-substring (match-beginning 3) (match-end 3))
8127                   ord (if pack 1 0)
8128                   file (file-of-tag)
8129                   fileind (format "%s:%s" file line)
8130                   ;; Moves to beginning of the next line:
8131                   info (cperl-etags-snarf-tag file line))
8132             ;; Move back
8133             (forward-char -1)
8134             ;; Make new member of hierarchy name ==> file ==> pos if needed
8135             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
8136                 ;; Name known
8137                 (setcdr cons1 (cons (cons fileind (vector file info))
8138                                     (cdr cons1)))
8139               ;; First occurrence of the name, start alist
8140               (setq cons1 (cons name (list (cons fileind (vector file info)))))
8141               (if pack
8142                   (setcar (cdr cperl-hierarchy)
8143                           (cons cons1 (nth 1 cperl-hierarchy)))
8144                 (setcar cperl-hierarchy
8145                         (cons cons1 (car cperl-hierarchy)))))))
8146       (end-of-line))))
8147
8148 (defun cperl-tags-hier-init (&optional update)
8149   "Show hierarchical menu of classes and methods.
8150 Finds info about classes by a scan of loaded TAGS files.
8151 Supposes that the TAGS files contain fully qualified function names.
8152 One may build such TAGS files from CPerl mode menu."
8153   (interactive)
8154   (require 'etags)
8155   (require 'imenu)
8156   (if (or update (null (nth 2 cperl-hierarchy)))
8157       (let ((remover (function (lambda (elt) ; (name (file1...) (file2..))
8158                                  (or (nthcdr 2 elt)
8159                                      ;; Only in one file
8160                                      (setcdr elt (cdr (nth 1 elt)))))))
8161             pack name cons1 to l1 l2 l3 l4 b)
8162         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
8163         (setq cperl-hierarchy (list l1 l2 l3))
8164         (if cperl-xemacs-p              ; Not checked
8165             (progn
8166               (or tags-file-name
8167                   ;; Does this work in XEmacs?
8168                   (call-interactively 'visit-tags-table))
8169               (message "Updating list of classes...")
8170               (set-buffer (get-file-buffer tags-file-name))
8171               (cperl-tags-hier-fill))
8172           (or tags-table-list
8173               (call-interactively 'visit-tags-table))
8174           (mapcar
8175            (function
8176             (lambda (tagsfile)
8177               (message "Updating list of classes... %s" tagsfile)
8178               (set-buffer (get-file-buffer tagsfile))
8179               (cperl-tags-hier-fill)))
8180            tags-table-list)
8181           (message "Updating list of classes... postprocessing..."))
8182         (mapcar remover (car cperl-hierarchy))
8183         (mapcar remover (nth 1 cperl-hierarchy))
8184         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
8185                        (cons "Methods: " (car cperl-hierarchy))))
8186         (cperl-tags-treeify to 1)
8187         (setcar (nthcdr 2 cperl-hierarchy)
8188                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
8189         (message "Updating list of classes: done, requesting display...")
8190         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
8191         ))
8192   (or (nth 2 cperl-hierarchy)
8193       (error "No items found"))
8194   (setq update
8195 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
8196         (if (if (fboundp 'display-popup-menus-p)
8197                 (let ((f 'display-popup-menus-p))
8198                   (funcall f))
8199               window-system)
8200             (x-popup-menu t (nth 2 cperl-hierarchy))
8201           (require 'tmm)
8202           (tmm-prompt (nth 2 cperl-hierarchy))))
8203   (if (and update (listp update))
8204       (progn (while (cdr update) (setq update (cdr update)))
8205              (setq update (car update)))) ; Get the last from the list
8206   (if (vectorp update)
8207       (progn
8208         (find-file (elt update 0))
8209         (cperl-etags-goto-tag-location (elt update 1))))
8210   (if (eq update -999) (cperl-tags-hier-init t)))
8211
8212 (defun cperl-tags-treeify (to level)
8213   ;; cadr of `to' is read-write.  On start it is a cons
8214   (let* ((regexp (concat "^\\(" (mapconcat
8215                                  'identity
8216                                  (make-list level "[_a-zA-Z0-9]+")
8217                                  "::")
8218                          "\\)\\(::\\)?"))
8219          (packages (cdr (nth 1 to)))
8220          (methods (cdr (nth 2 to)))
8221          l1 head tail cons1 cons2 ord writeto packs recurse
8222          root-packages root-functions ms many_ms same_name ps
8223          (move-deeper
8224           (function
8225            (lambda (elt)
8226              (cond ((and (string-match regexp (car elt))
8227                          (or (eq ord 1) (match-end 2)))
8228                     (setq head (substring (car elt) 0 (match-end 1))
8229                           tail (if (match-end 2) (substring (car elt)
8230                                                             (match-end 2)))
8231                           recurse t)
8232                     (if (setq cons1 (assoc head writeto)) nil
8233                       ;; Need to init new head
8234                       (setcdr writeto (cons (list head (list "Packages: ")
8235                                                   (list "Methods: "))
8236                                             (cdr writeto)))
8237                       (setq cons1 (nth 1 writeto)))
8238                     (setq cons2 (nth ord cons1)) ; Either packs or meths
8239                     (setcdr cons2 (cons elt (cdr cons2))))
8240                    ((eq ord 2)
8241                     (setq root-functions (cons elt root-functions)))
8242                    (t
8243                     (setq root-packages (cons elt root-packages))))))))
8244     (setcdr to l1)                      ; Init to dynamic space
8245     (setq writeto to)
8246     (setq ord 1)
8247     (mapcar move-deeper packages)
8248     (setq ord 2)
8249     (mapcar move-deeper methods)
8250     (if recurse
8251         (mapcar (function (lambda (elt)
8252                           (cperl-tags-treeify elt (1+ level))))
8253                 (cdr to)))
8254     ;;Now clean up leaders with one child only
8255     (mapcar (function (lambda (elt)
8256                         (if (not (and (listp (cdr elt))
8257                                       (eq (length elt) 2))) nil
8258                             (setcar elt (car (nth 1 elt)))
8259                             (setcdr elt (cdr (nth 1 elt))))))
8260             (cdr to))
8261     ;; Sort the roots of subtrees
8262     (if (default-value 'imenu-sort-function)
8263         (setcdr to
8264                 (sort (cdr to) (default-value 'imenu-sort-function))))
8265     ;; Now add back functions removed from display
8266     (mapcar (function (lambda (elt)
8267                         (setcdr to (cons elt (cdr to)))))
8268             (if (default-value 'imenu-sort-function)
8269                 (nreverse
8270                  (sort root-functions (default-value 'imenu-sort-function)))
8271               root-functions))
8272     ;; Now add back packages removed from display
8273     (mapcar (function (lambda (elt)
8274                         (setcdr to (cons (cons (concat "package " (car elt))
8275                                                (cdr elt))
8276                                          (cdr to)))))
8277             (if (default-value 'imenu-sort-function)
8278                 (nreverse
8279                  (sort root-packages (default-value 'imenu-sort-function)))
8280               root-packages))))
8281
8282 ;;;(x-popup-menu t
8283 ;;;   '(keymap "Name1"
8284 ;;;         ("Ret1" "aa")
8285 ;;;         ("Head1" "ab"
8286 ;;;          keymap "Name2"
8287 ;;;          ("Tail1" "x") ("Tail2" "y"))))
8288
8289 (defun cperl-list-fold (list name limit)
8290   (let (list1 list2 elt1 (num 0))
8291     (if (<= (length list) limit) list
8292       (setq list1 nil list2 nil)
8293       (while list
8294         (setq num (1+ num)
8295               elt1 (car list)
8296               list (cdr list))
8297         (if (<= num imenu-max-items)
8298             (setq list2 (cons elt1 list2))
8299           (setq list1 (cons (cons name
8300                                   (nreverse list2))
8301                             list1)
8302                 list2 (list elt1)
8303                 num 1)))
8304       (nreverse (cons (cons name
8305                             (nreverse list2))
8306                       list1)))))
8307
8308 (defun cperl-menu-to-keymap (menu &optional name)
8309   (let (list)
8310     (cons 'keymap
8311           (mapcar
8312            (function
8313             (lambda (elt)
8314               (cond ((listp (cdr elt))
8315                      (setq list (cperl-list-fold
8316                                  (cdr elt) (car elt) imenu-max-items))
8317                      (cons nil
8318                            (cons (car elt)
8319                                  (cperl-menu-to-keymap list))))
8320                     (t
8321                      (list (cdr elt) (car elt) t))))) ; t is needed in 19.34
8322            (cperl-list-fold menu "Root" imenu-max-items)))))
8323
8324 \f
8325 (defvar cperl-bad-style-regexp
8326   (mapconcat 'identity
8327              '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
8328                "[-<>=+^&|]+[^- \t\n=+<>~]") ; sign+ char
8329              "\\|")
8330   "Finds places such that insertion of a whitespace may help a lot.")
8331
8332 (defvar cperl-not-bad-style-regexp
8333   (mapconcat
8334    'identity
8335    '("[^-\t <>=+]\\(--\\|\\+\\+\\)"     ; var-- var++
8336      "[a-zA-Z0-9_][|&][a-zA-Z0-9_$]"    ; abc|def abc&def are often used.
8337      "&[(a-zA-Z0-9_$]"                  ; &subroutine &(var->field)
8338      "<\\$?\\sw+\\(\\.\\(\\sw\\|_\\)+\\)?>"     ; <IN> <stdin.h>
8339      "-[a-zA-Z][ \t]+[_$\"'`a-zA-Z]"    ; -f file, -t STDIN
8340      "-[0-9]"                           ; -5
8341      "\\+\\+"                           ; ++var
8342      "--"                               ; --var
8343      ".->"                              ; a->b
8344      "->"                               ; a SPACE ->b
8345      "\\[-"                             ; a[-1]
8346      "\\\\[&$@*\\\\]"                   ; \&func
8347      "^="                               ; =head
8348      "\\$."                             ; $|
8349      "<<[a-zA-Z_'\"`]"                  ; <<FOO, <<'FOO'
8350      "||"
8351      "&&"
8352      "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
8353      "-[a-zA-Z_0-9]+[ \t]*=>"           ; -option => value
8354      ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
8355      ;;"[*/+-|&<.]+="
8356      )
8357    "\\|")
8358   "If matches at the start of match found by `my-bad-c-style-regexp',
8359 insertion of a whitespace will not help.")
8360
8361 (defvar found-bad)
8362
8363 (defun cperl-find-bad-style ()
8364   "Find places in the buffer where insertion of a whitespace may help.
8365 Prompts user for insertion of spaces.
8366 Currently it is tuned to C and Perl syntax."
8367   (interactive)
8368   (let (found-bad (p (point)))
8369     (setq last-nonmenu-event 13)        ; To disable popup
8370     (goto-char (point-min))
8371     (map-y-or-n-p "Insert space here? "
8372                   (lambda (arg) (insert " "))
8373                   'cperl-next-bad-style
8374                   '("location" "locations" "insert a space into")
8375                   '((?\C-r (lambda (arg)
8376                              (let ((buffer-quit-function
8377                                     'exit-recursive-edit))
8378                                (message "Exit with Esc Esc")
8379                                (recursive-edit)
8380                                t))      ; Consider acted upon
8381                            "edit, exit with Esc Esc")
8382                     (?e (lambda (arg)
8383                           (let ((buffer-quit-function
8384                                  'exit-recursive-edit))
8385                             (message "Exit with Esc Esc")
8386                             (recursive-edit)
8387                             t))         ; Consider acted upon
8388                         "edit, exit with Esc Esc"))
8389                   t)
8390     (if found-bad (goto-char found-bad)
8391       (goto-char p)
8392       (message "No appropriate place found"))))
8393
8394 (defun cperl-next-bad-style ()
8395   (let (p (not-found t) (point (point)) found)
8396     (while (and not-found
8397                 (re-search-forward cperl-bad-style-regexp nil 'to-end))
8398       (setq p (point))
8399       (goto-char (match-beginning 0))
8400       (if (or
8401            (looking-at cperl-not-bad-style-regexp)
8402            ;; Check for a < -b and friends
8403            (and (eq (following-char) ?\-)
8404                 (save-excursion
8405                   (skip-chars-backward " \t\n")
8406                   (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\( ?\[ ?\{))))
8407            ;; Now check for syntax type
8408            (save-match-data
8409              (setq found (point))
8410              (beginning-of-defun)
8411              (let ((pps (parse-partial-sexp (point) found)))
8412                (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
8413           (goto-char (match-end 0))
8414         (goto-char (1- p))
8415         (setq not-found nil
8416               found-bad found)))
8417     (not not-found)))
8418
8419 \f
8420 ;;; Getting help
8421 (defvar cperl-have-help-regexp
8422   ;;(concat "\\("
8423   (mapconcat
8424    'identity
8425    '("[$@%*&][0-9a-zA-Z_:]+\\([ \t]*[[{]\\)?" ; Usual variable
8426      "[$@]\\^[a-zA-Z]"                  ; Special variable
8427      "[$@][^ \n\t]"                     ; Special variable
8428      "-[a-zA-Z]"                        ; File test
8429      "\\\\[a-zA-Z0]"                    ; Special chars
8430      "^=[a-z][a-zA-Z0-9_]*"             ; POD sections
8431      "[-!&*+,-./<=>?\\\\^|~]+"          ; Operator
8432      "[a-zA-Z_0-9:]+"                   ; symbol or number
8433      "x="
8434      "#!")
8435    ;;"\\)\\|\\("
8436    "\\|")
8437   ;;"\\)"
8438   ;;)
8439   "Matches places in the buffer we can find help for.")
8440
8441 (defvar cperl-message-on-help-error t)
8442 (defvar cperl-help-from-timer nil)
8443
8444 (defun cperl-word-at-point-hard ()
8445   ;; Does not save-excursion
8446   ;; Get to the something meaningful
8447   (or (eobp) (eolp) (forward-char 1))
8448   (re-search-backward "[-a-zA-Z0-9_:!&*+,-./<=>?\\\\^|~$%@]"
8449                       (save-excursion (beginning-of-line) (point))
8450                       'to-beg)
8451   ;;  (cond
8452   ;;   ((or (eobp) (looking-at "[][ \t\n{}();,]")) ; Not at a symbol
8453   ;;    (skip-chars-backward " \n\t\r({[]});,")
8454   ;;    (or (bobp) (backward-char 1))))
8455   ;; Try to backtrace
8456   (cond
8457    ((looking-at "[a-zA-Z0-9_:]")        ; symbol
8458     (skip-chars-backward "a-zA-Z0-9_:")
8459     (cond
8460      ((and (eq (preceding-char) ?^)     ; $^I
8461            (eq (char-after (- (point) 2)) ?\$))
8462       (forward-char -2))
8463      ((memq (preceding-char) (append "*$@%&\\" nil)) ; *glob
8464       (forward-char -1))
8465      ((and (eq (preceding-char) ?\=)
8466            (eq (current-column) 1))
8467       (forward-char -1)))               ; =head1
8468     (if (and (eq (preceding-char) ?\<)
8469              (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <FH>
8470         (forward-char -1)))
8471    ((and (looking-at "=") (eq (preceding-char) ?x)) ; x=
8472     (forward-char -1))
8473    ((and (looking-at "\\^") (eq (preceding-char) ?\$)) ; $^I
8474     (forward-char -1))
8475    ((looking-at "[-!&*+,-./<=>?\\\\^|~]")
8476     (skip-chars-backward "-!&*+,-./<=>?\\\\^|~")
8477     (cond
8478      ((and (eq (preceding-char) ?\$)
8479            (not (eq (char-after (- (point) 2)) ?\$))) ; $-
8480       (forward-char -1))
8481      ((and (eq (following-char) ?\>)
8482            (string-match "[a-zA-Z0-9_]" (char-to-string (preceding-char)))
8483            (save-excursion
8484              (forward-sexp -1)
8485              (and (eq (preceding-char) ?\<)
8486                   (looking-at "\\$?[a-zA-Z0-9_:]+>")))) ; <FH>
8487       (search-backward "<"))))
8488    ((and (eq (following-char) ?\$)
8489          (eq (preceding-char) ?\<)
8490          (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <$fh>
8491     (forward-char -1)))
8492   (if (looking-at cperl-have-help-regexp)
8493       (buffer-substring (match-beginning 0) (match-end 0))))
8494
8495 (defun cperl-get-help ()
8496   "Get one-line docs on the symbol at the point.
8497 The data for these docs is a little bit obsolete and may be in fact longer
8498 than a line.  Your contribution to update/shorten it is appreciated."
8499   (interactive)
8500   (save-match-data                      ; May be called "inside" query-replace
8501     (save-excursion
8502       (let ((word (cperl-word-at-point-hard)))
8503         (if word
8504             (if (and cperl-help-from-timer ; Bail out if not in mainland
8505                      (not (string-match "^#!\\|\\\\\\|^=" word)) ; Show help even in comments/strings.
8506                      (or (memq (get-text-property (point) 'face)
8507                                '(font-lock-comment-face font-lock-string-face))
8508                          (memq (get-text-property (point) 'syntax-type)
8509                                '(pod here-doc format))))
8510                 nil
8511               (cperl-describe-perl-symbol word))
8512           (if cperl-message-on-help-error
8513               (message "Nothing found for %s..."
8514                        (buffer-substring (point) (min (+ 5 (point)) (point-max))))))))))
8515
8516 ;;; Stolen from perl-descr.el by Johan Vromans:
8517
8518 (defvar cperl-doc-buffer " *perl-doc*"
8519   "Where the documentation can be found.")
8520
8521 (defun cperl-describe-perl-symbol (val)
8522   "Display the documentation of symbol at point, a Perl operator."
8523   (let ((enable-recursive-minibuffers t)
8524         args-file regexp)
8525     (cond
8526      ((string-match "^[&*][a-zA-Z_]" val)
8527       (setq val (concat (substring val 0 1) "NAME")))
8528      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*\\[" val)
8529       (setq val (concat "@" (substring val 1 (match-end 1)))))
8530      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*{" val)
8531       (setq val (concat "%" (substring val 1 (match-end 1)))))
8532      ((and (string= val "x") (string-match "^x=" val))
8533       (setq val "x="))
8534      ((string-match "^\\$[\C-a-\C-z]" val)
8535       (setq val (concat "$^" (char-to-string (+ ?A -1 (aref val 1))))))
8536      ((string-match "^CORE::" val)
8537       (setq val "CORE::"))
8538      ((string-match "^SUPER::" val)
8539       (setq val "SUPER::"))
8540      ((and (string= "<" val) (string-match "^<\\$?[a-zA-Z0-9_:]+>" val))
8541       (setq val "<NAME>")))
8542     (setq regexp (concat "^"
8543                          "\\([^a-zA-Z0-9_:]+[ \t]+\\)?"
8544                          (regexp-quote val)
8545                          "\\([ \t([/]\\|$\\)"))
8546
8547     ;; get the buffer with the documentation text
8548     (cperl-switch-to-doc-buffer)
8549
8550     ;; lookup in the doc
8551     (goto-char (point-min))
8552     (let ((case-fold-search nil))
8553       (list
8554        (if (re-search-forward regexp (point-max) t)
8555            (save-excursion
8556              (beginning-of-line 1)
8557              (let ((lnstart (point)))
8558                (end-of-line)
8559                (message "%s" (buffer-substring lnstart (point)))))
8560          (if cperl-message-on-help-error
8561              (message "No definition for %s" val)))))))
8562
8563 (defvar cperl-short-docs 'please-ignore-this-line
8564   ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl)
8565   "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5]
8566 ...     Range (list context); flip/flop [no flop when flip] (scalar context).
8567 ! ...   Logical negation.
8568 ... != ...      Numeric inequality.
8569 ... !~ ...      Search pattern, substitution, or translation (negated).
8570 $!      In numeric context: errno.  In a string context: error string.
8571 $\"     The separator which joins elements of arrays interpolated in strings.
8572 $#      The output format for printed numbers.  Default is %.15g or close.
8573 $$      Process number of this script.  Changes in the fork()ed child process.
8574 $%      The current page number of the currently selected output channel.
8575
8576         The following variables are always local to the current block:
8577
8578 $1      Match of the 1st set of parentheses in the last match (auto-local).
8579 $2      Match of the 2nd set of parentheses in the last match (auto-local).
8580 $3      Match of the 3rd set of parentheses in the last match (auto-local).
8581 $4      Match of the 4th set of parentheses in the last match (auto-local).
8582 $5      Match of the 5th set of parentheses in the last match (auto-local).
8583 $6      Match of the 6th set of parentheses in the last match (auto-local).
8584 $7      Match of the 7th set of parentheses in the last match (auto-local).
8585 $8      Match of the 8th set of parentheses in the last match (auto-local).
8586 $9      Match of the 9th set of parentheses in the last match (auto-local).
8587 $&      The string matched by the last pattern match (auto-local).
8588 $'      The string after what was matched by the last match (auto-local).
8589 $`      The string before what was matched by the last match (auto-local).
8590
8591 $(      The real gid of this process.
8592 $)      The effective gid of this process.
8593 $*      Deprecated: Set to 1 to do multiline matching within a string.
8594 $+      The last bracket matched by the last search pattern.
8595 $,      The output field separator for the print operator.
8596 $-      The number of lines left on the page.
8597 $.      The current input line number of the last filehandle that was read.
8598 $/      The input record separator, newline by default.
8599 $0      Name of the file containing the current perl script (read/write).
8600 $:     String may be broken after these characters to fill ^-lines in a format.
8601 $;      Subscript separator for multi-dim array emulation.  Default \"\\034\".
8602 $<      The real uid of this process.
8603 $=      The page length of the current output channel.  Default is 60 lines.
8604 $>      The effective uid of this process.
8605 $?      The status returned by the last ``, pipe close or `system'.
8606 $@      The perl error message from the last eval or do @var{EXPR} command.
8607 $ARGV   The name of the current file used with <> .
8608 $[      Deprecated: The index of the first element/char in an array/string.
8609 $\\     The output record separator for the print operator.
8610 $]      The perl version string as displayed with perl -v.
8611 $^      The name of the current top-of-page format.
8612 $^A     The current value of the write() accumulator for format() lines.
8613 $^D     The value of the perl debug (-D) flags.
8614 $^E     Information about the last system error other than that provided by $!.
8615 $^F     The highest system file descriptor, ordinarily 2.
8616 $^H     The current set of syntax checks enabled by `use strict'.
8617 $^I     The value of the in-place edit extension (perl -i option).
8618 $^L     What formats output to perform a formfeed.  Default is \f.
8619 $^M     A buffer for emergency memory allocation when running out of memory.
8620 $^O     The operating system name under which this copy of Perl was built.
8621 $^P     Internal debugging flag.
8622 $^T     The time the script was started.  Used by -A/-M/-C file tests.
8623 $^W     True if warnings are requested (perl -w flag).
8624 $^X     The name under which perl was invoked (argv[0] in C-speech).
8625 $_      The default input and pattern-searching space.
8626 $|      Auto-flush after write/print on current output channel?  Default 0.
8627 $~      The name of the current report format.
8628 ... % ...       Modulo division.
8629 ... %= ...      Modulo division assignment.
8630 %ENV    Contains the current environment.
8631 %INC    List of files that have been require-d or do-ne.
8632 %SIG    Used to set signal handlers for various signals.
8633 ... & ...       Bitwise and.
8634 ... && ...      Logical and.
8635 ... &&= ...     Logical and assignment.
8636 ... &= ...      Bitwise and assignment.
8637 ... * ...       Multiplication.
8638 ... ** ...      Exponentiation.
8639 *NAME   Glob: all objects refered by NAME.  *NAM1 = *NAM2 aliases NAM1 to NAM2.
8640 &NAME(arg0, ...)        Subroutine call.  Arguments go to @_.
8641 ... + ...       Addition.               +EXPR   Makes EXPR into scalar context.
8642 ++      Auto-increment (magical on strings).    ++EXPR  EXPR++
8643 ... += ...      Addition assignment.
8644 ,       Comma operator.
8645 ... - ...       Subtraction.
8646 --      Auto-decrement (NOT magical on strings).        --EXPR  EXPR--
8647 ... -= ...      Subtraction assignment.
8648 -A      Access time in days since script started.
8649 -B      File is a non-text (binary) file.
8650 -C      Inode change time in days since script started.
8651 -M      Age in days since script started.
8652 -O      File is owned by real uid.
8653 -R      File is readable by real uid.
8654 -S      File is a socket .
8655 -T      File is a text file.
8656 -W      File is writable by real uid.
8657 -X      File is executable by real uid.
8658 -b      File is a block special file.
8659 -c      File is a character special file.
8660 -d      File is a directory.
8661 -e      File exists .
8662 -f      File is a plain file.
8663 -g      File has setgid bit set.
8664 -k      File has sticky bit set.
8665 -l      File is a symbolic link.
8666 -o      File is owned by effective uid.
8667 -p      File is a named pipe (FIFO).
8668 -r      File is readable by effective uid.
8669 -s      File has non-zero size.
8670 -t      Tests if filehandle (STDIN by default) is opened to a tty.
8671 -u      File has setuid bit set.
8672 -w      File is writable by effective uid.
8673 -x      File is executable by effective uid.
8674 -z      File has zero size.
8675 .       Concatenate strings.
8676 ..      Range (list context); flip/flop (scalar context) operator.
8677 .=      Concatenate assignment strings
8678 ... / ...       Division.       /PATTERN/ioxsmg Pattern match
8679 ... /= ...      Division assignment.
8680 /PATTERN/ioxsmg Pattern match.
8681 ... < ...    Numeric less than. <pattern>       Glob.   See <NAME>, <> as well.
8682 <NAME>  Reads line from filehandle NAME (a bareword or dollar-bareword).
8683 <pattern>       Glob (Unless pattern is bareword/dollar-bareword - see <NAME>).
8684 <>      Reads line from union of files in @ARGV (= command line) and STDIN.
8685 ... << ...      Bitwise shift left.     <<      start of HERE-DOCUMENT.
8686 ... <= ...      Numeric less than or equal to.
8687 ... <=> ...     Numeric compare.
8688 ... = ...       Assignment.
8689 ... == ...      Numeric equality.
8690 ... =~ ...      Search pattern, substitution, or translation
8691 ... > ...       Numeric greater than.
8692 ... >= ...      Numeric greater than or equal to.
8693 ... >> ...      Bitwise shift right.
8694 ... >>= ...     Bitwise shift right assignment.
8695 ... ? ... : ... Condition=if-then-else operator.   ?PAT? One-time pattern match.
8696 ?PATTERN?       One-time pattern match.
8697 @ARGV   Command line arguments (not including the command name - see $0).
8698 @INC    List of places to look for perl scripts during do/include/use.
8699 @_    Parameter array for subroutines; result of split() unless in list context.
8700 \\  Creates reference to what follows, like \$var, or quotes non-\w in strings.
8701 \\0     Octal char, e.g. \\033.
8702 \\E     Case modification terminator.  See \\Q, \\L, and \\U.
8703 \\L     Lowercase until \\E .  See also \l, lc.
8704 \\U     Upcase until \\E .  See also \u, uc.
8705 \\Q     Quote metacharacters until \\E .  See also quotemeta.
8706 \\a     Alarm character (octal 007).
8707 \\b     Backspace character (octal 010).
8708 \\c     Control character, e.g. \\c[ .
8709 \\e     Escape character (octal 033).
8710 \\f     Formfeed character (octal 014).
8711 \\l     Lowercase the next character.  See also \\L and \\u, lcfirst.
8712 \\n     Newline character (octal 012 on most systems).
8713 \\r     Return character (octal 015 on most systems).
8714 \\t     Tab character (octal 011).
8715 \\u     Upcase the next character.  See also \\U and \\l, ucfirst.
8716 \\x     Hex character, e.g. \\x1b.
8717 ... ^ ...       Bitwise exclusive or.
8718 __END__ Ends program source.
8719 __DATA__        Ends program source.
8720 __FILE__        Current (source) filename.
8721 __LINE__        Current line in current source.
8722 __PACKAGE__     Current package.
8723 ARGV    Default multi-file input filehandle.  <ARGV> is a synonym for <>.
8724 ARGVOUT Output filehandle with -i flag.
8725 BEGIN { ... }   Immediately executed (during compilation) piece of code.
8726 END { ... }     Pseudo-subroutine executed after the script finishes.
8727 CHECK { ... }   Pseudo-subroutine executed after the script is compiled.
8728 INIT { ... }    Pseudo-subroutine executed before the script starts running.
8729 DATA    Input filehandle for what follows after __END__ or __DATA__.
8730 accept(NEWSOCKET,GENERICSOCKET)
8731 alarm(SECONDS)
8732 atan2(X,Y)
8733 bind(SOCKET,NAME)
8734 binmode(FILEHANDLE)
8735 caller[(LEVEL)]
8736 chdir(EXPR)
8737 chmod(LIST)
8738 chop[(LIST|VAR)]
8739 chown(LIST)
8740 chroot(FILENAME)
8741 close(FILEHANDLE)
8742 closedir(DIRHANDLE)
8743 ... cmp ...     String compare.
8744 connect(SOCKET,NAME)
8745 continue of { block } continue { block }.  Is executed after `next' or at end.
8746 cos(EXPR)
8747 crypt(PLAINTEXT,SALT)
8748 dbmclose(%HASH)
8749 dbmopen(%HASH,DBNAME,MODE)
8750 defined(EXPR)
8751 delete($HASH{KEY})
8752 die(LIST)
8753 do { ... }|SUBR while|until EXPR        executes at least once
8754 do(EXPR|SUBR([LIST]))   (with while|until executes at least once)
8755 dump LABEL
8756 each(%HASH)
8757 endgrent
8758 endhostent
8759 endnetent
8760 endprotoent
8761 endpwent
8762 endservent
8763 eof[([FILEHANDLE])]
8764 ... eq ...      String equality.
8765 eval(EXPR) or eval { BLOCK }
8766 exec(LIST)
8767 exit(EXPR)
8768 exp(EXPR)
8769 fcntl(FILEHANDLE,FUNCTION,SCALAR)
8770 fileno(FILEHANDLE)
8771 flock(FILEHANDLE,OPERATION)
8772 for (EXPR;EXPR;EXPR) { ... }
8773 foreach [VAR] (@ARRAY) { ... }
8774 fork
8775 ... ge ...      String greater than or equal.
8776 getc[(FILEHANDLE)]
8777 getgrent
8778 getgrgid(GID)
8779 getgrnam(NAME)
8780 gethostbyaddr(ADDR,ADDRTYPE)
8781 gethostbyname(NAME)
8782 gethostent
8783 getlogin
8784 getnetbyaddr(ADDR,ADDRTYPE)
8785 getnetbyname(NAME)
8786 getnetent
8787 getpeername(SOCKET)
8788 getpgrp(PID)
8789 getppid
8790 getpriority(WHICH,WHO)
8791 getprotobyname(NAME)
8792 getprotobynumber(NUMBER)
8793 getprotoent
8794 getpwent
8795 getpwnam(NAME)
8796 getpwuid(UID)
8797 getservbyname(NAME,PROTO)
8798 getservbyport(PORT,PROTO)
8799 getservent
8800 getsockname(SOCKET)
8801 getsockopt(SOCKET,LEVEL,OPTNAME)
8802 gmtime(EXPR)
8803 goto LABEL
8804 ... gt ...      String greater than.
8805 hex(EXPR)
8806 if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXPR if EXPR
8807 index(STR,SUBSTR[,OFFSET])
8808 int(EXPR)
8809 ioctl(FILEHANDLE,FUNCTION,SCALAR)
8810 join(EXPR,LIST)
8811 keys(%HASH)
8812 kill(LIST)
8813 last [LABEL]
8814 ... le ...      String less than or equal.
8815 length(EXPR)
8816 link(OLDFILE,NEWFILE)
8817 listen(SOCKET,QUEUESIZE)
8818 local(LIST)
8819 localtime(EXPR)
8820 log(EXPR)
8821 lstat(EXPR|FILEHANDLE|VAR)
8822 ... lt ...      String less than.
8823 m/PATTERN/iogsmx
8824 mkdir(FILENAME,MODE)
8825 msgctl(ID,CMD,ARG)
8826 msgget(KEY,FLAGS)
8827 msgrcv(ID,VAR,SIZE,TYPE.FLAGS)
8828 msgsnd(ID,MSG,FLAGS)
8829 my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, or %HASH).
8830 our VAR or our (VAR1,...) Lexically enable a global variable ($V, @A, or %H).
8831 ... ne ...      String inequality.
8832 next [LABEL]
8833 oct(EXPR)
8834 open(FILEHANDLE[,EXPR])
8835 opendir(DIRHANDLE,EXPR)
8836 ord(EXPR)       ASCII value of the first char of the string.
8837 pack(TEMPLATE,LIST)
8838 package NAME    Introduces package context.
8839 pipe(READHANDLE,WRITEHANDLE)    Create a pair of filehandles on ends of a pipe.
8840 pop(ARRAY)
8841 print [FILEHANDLE] [(LIST)]
8842 printf [FILEHANDLE] (FORMAT,LIST)
8843 push(ARRAY,LIST)
8844 q/STRING/       Synonym for 'STRING'
8845 qq/STRING/      Synonym for \"STRING\"
8846 qx/STRING/      Synonym for `STRING`
8847 rand[(EXPR)]
8848 read(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
8849 readdir(DIRHANDLE)
8850 readlink(EXPR)
8851 recv(SOCKET,SCALAR,LEN,FLAGS)
8852 redo [LABEL]
8853 rename(OLDNAME,NEWNAME)
8854 require [FILENAME | PERL_VERSION]
8855 reset[(EXPR)]
8856 return(LIST)
8857 reverse(LIST)
8858 rewinddir(DIRHANDLE)
8859 rindex(STR,SUBSTR[,OFFSET])
8860 rmdir(FILENAME)
8861 s/PATTERN/REPLACEMENT/gieoxsm
8862 scalar(EXPR)
8863 seek(FILEHANDLE,POSITION,WHENCE)
8864 seekdir(DIRHANDLE,POS)
8865 select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT)
8866 semctl(ID,SEMNUM,CMD,ARG)
8867 semget(KEY,NSEMS,SIZE,FLAGS)
8868 semop(KEY,...)
8869 send(SOCKET,MSG,FLAGS[,TO])
8870 setgrent
8871 sethostent(STAYOPEN)
8872 setnetent(STAYOPEN)
8873 setpgrp(PID,PGRP)
8874 setpriority(WHICH,WHO,PRIORITY)
8875 setprotoent(STAYOPEN)
8876 setpwent
8877 setservent(STAYOPEN)
8878 setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
8879 shift[(ARRAY)]
8880 shmctl(ID,CMD,ARG)
8881 shmget(KEY,SIZE,FLAGS)
8882 shmread(ID,VAR,POS,SIZE)
8883 shmwrite(ID,STRING,POS,SIZE)
8884 shutdown(SOCKET,HOW)
8885 sin(EXPR)
8886 sleep[(EXPR)]
8887 socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
8888 socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
8889 sort [SUBROUTINE] (LIST)
8890 splice(ARRAY,OFFSET[,LENGTH[,LIST]])
8891 split[(/PATTERN/[,EXPR[,LIMIT]])]
8892 sprintf(FORMAT,LIST)
8893 sqrt(EXPR)
8894 srand(EXPR)
8895 stat(EXPR|FILEHANDLE|VAR)
8896 study[(SCALAR)]
8897 sub [NAME [(format)]] { BODY }  sub NAME [(format)];    sub [(format)] {...}
8898 substr(EXPR,OFFSET[,LEN])
8899 symlink(OLDFILE,NEWFILE)
8900 syscall(LIST)
8901 sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
8902 system(LIST)
8903 syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
8904 tell[(FILEHANDLE)]
8905 telldir(DIRHANDLE)
8906 time
8907 times
8908 tr/SEARCHLIST/REPLACEMENTLIST/cds
8909 truncate(FILE|EXPR,LENGTH)
8910 umask[(EXPR)]
8911 undef[(EXPR)]
8912 unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR
8913 unlink(LIST)
8914 unpack(TEMPLATE,EXPR)
8915 unshift(ARRAY,LIST)
8916 until (EXPR) { ... }                                    EXPR until EXPR
8917 utime(LIST)
8918 values(%HASH)
8919 vec(EXPR,OFFSET,BITS)
8920 wait
8921 waitpid(PID,FLAGS)
8922 wantarray       Returns true if the sub/eval is called in list context.
8923 warn(LIST)
8924 while  (EXPR) { ... }                                   EXPR while EXPR
8925 write[(EXPR|FILEHANDLE)]
8926 ... x ...       Repeat string or array.
8927 x= ...  Repetition assignment.
8928 y/SEARCHLIST/REPLACEMENTLIST/
8929 ... | ...       Bitwise or.
8930 ... || ...      Logical or.
8931 ~ ...           Unary bitwise complement.
8932 #!      OS interpreter indicator.  If contains `perl', used for options, and -x.
8933 AUTOLOAD {...}  Shorthand for `sub AUTOLOAD {...}'.
8934 CORE::          Prefix to access builtin function if imported sub obscures it.
8935 SUPER::         Prefix to lookup for a method in @ISA classes.
8936 DESTROY         Shorthand for `sub DESTROY {...}'.
8937 ... EQ ...      Obsolete synonym of `eq'.
8938 ... GE ...      Obsolete synonym of `ge'.
8939 ... GT ...      Obsolete synonym of `gt'.
8940 ... LE ...      Obsolete synonym of `le'.
8941 ... LT ...      Obsolete synonym of `lt'.
8942 ... NE ...      Obsolete synonym of `ne'.
8943 abs [ EXPR ]    absolute value
8944 ... and ...             Low-precedence synonym for &&.
8945 bless REFERENCE [, PACKAGE]     Makes reference into an object of a package.
8946 chomp [LIST]    Strips $/ off LIST/$_.  Returns count.  Special if $/ eq ''!
8947 chr             Converts a number to char with the same ordinal.
8948 else            Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
8949 elsif           Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
8950 exists $HASH{KEY}       True if the key exists.
8951 format [NAME] =  Start of output format.  Ended by a single dot (.) on a line.
8952 formline PICTURE, LIST  Backdoor into \"format\" processing.
8953 glob EXPR       Synonym of <EXPR>.
8954 lc [ EXPR ]     Returns lowercased EXPR.
8955 lcfirst [ EXPR ]        Returns EXPR with lower-cased first letter.
8956 grep EXPR,LIST  or grep {BLOCK} LIST    Filters LIST via EXPR/BLOCK.
8957 map EXPR, LIST  or map {BLOCK} LIST     Applies EXPR/BLOCK to elts of LIST.
8958 no PACKAGE [SYMBOL1, ...]  Partial reverse for `use'.  Runs `unimport' method.
8959 not ...         Low-precedence synonym for ! - negation.
8960 ... or ...              Low-precedence synonym for ||.
8961 pos STRING    Set/Get end-position of the last match over this string, see \\G.
8962 quotemeta [ EXPR ]      Quote regexp metacharacters.
8963 qw/WORD1 .../           Synonym of split('', 'WORD1 ...')
8964 readline FH     Synonym of <FH>.
8965 readpipe CMD    Synonym of `CMD`.
8966 ref [ EXPR ]    Type of EXPR when dereferenced.
8967 sysopen FH, FILENAME, MODE [, PERM]     (MODE is numeric, see Fcntl.)
8968 tie VAR, PACKAGE, LIST  Hide an object behind a simple Perl variable.
8969 tied            Returns internal object for a tied data.
8970 uc [ EXPR ]     Returns upcased EXPR.
8971 ucfirst [ EXPR ]        Returns EXPR with upcased first letter.
8972 untie VAR       Unlink an object from a simple Perl variable.
8973 use PACKAGE [SYMBOL1, ...]  Compile-time `require' with consequent `import'.
8974 ... xor ...             Low-precedence synonym for exclusive or.
8975 prototype \&SUB Returns prototype of the function given a reference.
8976 =head1          Top-level heading.
8977 =head2          Second-level heading.
8978 =head3          Third-level heading (is there such?).
8979 =over [ NUMBER ]        Start list.
8980 =item [ TITLE ]         Start new item in the list.
8981 =back           End list.
8982 =cut            Switch from POD to Perl.
8983 =pod            Switch from Perl to POD.
8984 ")
8985
8986 (defun cperl-switch-to-doc-buffer ()
8987   "Go to the perl documentation buffer and insert the documentation."
8988   (interactive)
8989   (let ((buf (get-buffer-create cperl-doc-buffer)))
8990     (if (interactive-p)
8991         (switch-to-buffer-other-window buf)
8992       (set-buffer buf))
8993     (if (= (buffer-size) 0)
8994         (progn
8995           (insert (documentation-property 'cperl-short-docs
8996                                           'variable-documentation))
8997           (setq buffer-read-only t)))))
8998
8999 (defun cperl-beautify-regexp-piece (b e embed level)
9000   ;; b is before the starting delimiter, e before the ending
9001   ;; e should be a marker, may be changed, but remains "correct".
9002   ;; EMBED is nil iff we process the whole REx.
9003   ;; The REx is guaranteed to have //x
9004   ;; LEVEL shows how many levels deep to go
9005   ;; position at enter and at leave is not defined
9006   (let (s c tmp (m (make-marker)) (m1 (make-marker)) c1 spaces inline code pos)
9007     (if (not embed)
9008         (goto-char (1+ b))
9009       (goto-char b)
9010       (cond ((looking-at "(\\?\\\\#")   ;  (?#) wrongly commented when //x-ing
9011              (forward-char 2)
9012              (delete-char 1)
9013              (forward-char 1))
9014             ((looking-at "(\\?[^a-zA-Z]")
9015              (forward-char 3))
9016             ((looking-at "(\\?")        ; (?i)
9017              (forward-char 2))
9018             (t
9019              (forward-char 1))))
9020     (setq c (if embed (current-indentation) (1- (current-column)))
9021           c1 (+ c (or cperl-regexp-indent-step cperl-indent-level)))
9022     (or (looking-at "[ \t]*[\n#]")
9023         (progn
9024           (insert "\n")))
9025     (goto-char e)
9026     (beginning-of-line)
9027     (if (re-search-forward "[^ \t]" e t)
9028         (progn                         ; Something before the ending delimiter
9029           (goto-char e)
9030           (delete-horizontal-space)
9031           (insert "\n")
9032           (cperl-make-indent c)
9033           (set-marker e (point))))
9034     (goto-char b)
9035     (end-of-line 2)
9036     (while (< (point) (marker-position e))
9037       (beginning-of-line)
9038       (setq s (point)
9039             inline t)
9040       (skip-chars-forward " \t")
9041       (delete-region s (point))
9042       (cperl-make-indent c1)
9043       (while (and
9044               inline
9045               (looking-at
9046                (concat "\\([a-zA-Z0-9]+[^*+{?]\\)" ; 1 word
9047                        "\\|"            ; Embedded variable
9048                        "\\$\\([a-zA-Z0-9_]+\\([[{]\\)?\\|[^\n \t)|]\\)" ; 2 3
9049                        "\\|"            ; $ ^
9050                        "[$^]"
9051                        "\\|"            ; simple-code simple-code*?
9052                        "\\(\\\\.\\|[^][()#|*+?\n]\\)\\([*+{?]\\??\\)?" ; 4 5
9053                        "\\|"            ; Class
9054                        "\\(\\[\\)"      ; 6
9055                        "\\|"            ; Grouping
9056                        "\\((\\(\\?\\)?\\)" ; 7 8
9057                        "\\|"            ; |
9058                        "\\(|\\)")))     ; 9
9059         (goto-char (match-end 0))
9060         (setq spaces t)
9061         (cond ((match-beginning 1)      ; Alphanum word + junk
9062                (forward-char -1))
9063               ((or (match-beginning 3)  ; $ab[12]
9064                    (and (match-beginning 5) ; X* X+ X{2,3}
9065                         (eq (preceding-char) ?\{)))
9066                (forward-char -1)
9067                (forward-sexp 1))
9068               ((and                     ; [], already syntaxified
9069                 (match-beginning 6)
9070                 cperl-regexp-scan
9071                 cperl-use-syntax-table-text-property)
9072                (forward-char -1)
9073                (forward-sexp 1)
9074                (or (eq (preceding-char) ?\])
9075                    (error "[]-group not terminated"))
9076                (re-search-forward
9077                 "\\=\\([*+?]\\|{[0-9]+\\(,[0-9]*\\)?}\\)\\??" e t))
9078               ((match-beginning 6)      ; []
9079                (setq tmp (point))
9080                (if (looking-at "\\^?\\]")
9081                    (goto-char (match-end 0)))
9082                ;; XXXX POSIX classes?!
9083                (while (and (not pos)
9084                            (re-search-forward "\\[:\\|\\]" e t))
9085                  (if (eq (preceding-char) ?:)
9086                      (or (re-search-forward ":\\]" e t)
9087                          (error "[:POSIX:]-group in []-group not terminated"))
9088                    (setq pos t)))
9089                (or (eq (preceding-char) ?\])
9090                    (error "[]-group not terminated"))
9091                (re-search-forward
9092                 "\\=\\([*+?]\\|{[0-9]+\\(,[0-9]*\\)?}\\)\\??" e t))
9093               ((match-beginning 7)      ; ()
9094                (goto-char (match-beginning 0))
9095                (setq pos (current-column))
9096                (or (eq pos c1)
9097                    (progn
9098                      (delete-horizontal-space)
9099                      (insert "\n")
9100                      (cperl-make-indent c1)))
9101                (setq tmp (point))
9102                (forward-sexp 1)
9103                ;;              (or (forward-sexp 1)
9104                ;;                  (progn
9105                ;;                    (goto-char tmp)
9106                ;;                    (error "()-group not terminated")))
9107                (set-marker m (1- (point)))
9108                (set-marker m1 (point))
9109                (if (= level 1)
9110                    (if (progn           ; indent rigidly if multiline
9111                          ;; In fact does not make a lot of sense, since
9112                          ;; the starting position can be already lost due
9113                          ;; to insertion of "\n" and " "
9114                          (goto-char tmp)
9115                          (search-forward "\n" m1 t))
9116                        (indent-rigidly (point) m1 (- c1 pos)))
9117                  (setq level (1- level))
9118                  (cond
9119                   ((not (match-beginning 8))
9120                    (cperl-beautify-regexp-piece tmp m t level))
9121                   ((eq (char-after (+ 2 tmp)) ?\{) ; Code
9122                    t)
9123                   ((eq (char-after (+ 2 tmp)) ?\() ; Conditional
9124                    (goto-char (+ 2 tmp))
9125                    (forward-sexp 1)
9126                    (cperl-beautify-regexp-piece (point) m t level))
9127                   ((eq (char-after (+ 2 tmp)) ?<) ; Lookbehind
9128                    (goto-char (+ 3 tmp))
9129                    (cperl-beautify-regexp-piece (point) m t level))
9130                   (t
9131                    (cperl-beautify-regexp-piece tmp m t level))))
9132                (goto-char m1)
9133                (cond ((looking-at "[*+?]\\??")
9134                       (goto-char (match-end 0)))
9135                      ((eq (following-char) ?\{)
9136                       (forward-sexp 1)
9137                       (if (eq (following-char) ?\?)
9138                           (forward-char))))
9139                (skip-chars-forward " \t")
9140                (setq spaces nil)
9141                (if (looking-at "[#\n]")
9142                    (progn
9143                      (or (eolp) (indent-for-comment))
9144                      (beginning-of-line 2))
9145                  (delete-horizontal-space)
9146                  (insert "\n"))
9147                (end-of-line)
9148                (setq inline nil))
9149               ((match-beginning 9)      ; |
9150                (forward-char -1)
9151                (setq tmp (point))
9152                (beginning-of-line)
9153                (if (re-search-forward "[^ \t]" tmp t)
9154                    (progn
9155                      (goto-char tmp)
9156                      (delete-horizontal-space)
9157                      (insert "\n"))
9158                  ;; first at line
9159                  (delete-region (point) tmp))
9160                (cperl-make-indent c)
9161                (forward-char 1)
9162                (skip-chars-forward " \t")
9163                (setq spaces nil)
9164                (if (looking-at "[#\n]")
9165                    (beginning-of-line 2)
9166                  (delete-horizontal-space)
9167                  (insert "\n"))
9168                (end-of-line)
9169                (setq inline nil)))
9170         (or (looking-at "[ \t\n]")
9171             (not spaces)
9172             (insert " "))
9173         (skip-chars-forward " \t"))
9174       (or (looking-at "[#\n]")
9175           (error "Unknown code `%s' in a regexp"
9176                  (buffer-substring (point) (1+ (point)))))
9177       (and inline (end-of-line 2)))
9178     ;; Special-case the last line of group
9179     (if (and (>= (point) (marker-position e))
9180              (/= (current-indentation) c))
9181         (progn
9182           (beginning-of-line)
9183           (cperl-make-indent c)))))
9184
9185 (defun cperl-make-regexp-x ()
9186   ;; Returns position of the start
9187   ;; XXX this is called too often!  Need to cache the result!
9188   (save-excursion
9189     (or cperl-use-syntax-table-text-property
9190         (error "I need to have a regexp marked!"))
9191     ;; Find the start
9192     (if (looking-at "\\s|")
9193         nil                             ; good already
9194       (if (looking-at "\\([smy]\\|qr\\)\\s|")
9195           (forward-char 1)
9196         (re-search-backward "\\s|")))   ; Assume it is scanned already.
9197     ;;(forward-char 1)
9198     (let ((b (point)) (e (make-marker)) have-x delim (c (current-column))
9199           (sub-p (eq (preceding-char) ?s)) s)
9200       (forward-sexp 1)
9201       (set-marker e (1- (point)))
9202       (setq delim (preceding-char))
9203       (if (and sub-p (eq delim (char-after (- (point) 2))))
9204           (error "Possible s/blah// - do not know how to deal with"))
9205       (if sub-p (forward-sexp 1))
9206       (if (looking-at "\\sw*x")
9207           (setq have-x t)
9208         (insert "x"))
9209       ;; Protect fragile " ", "#"
9210       (if have-x nil
9211         (goto-char (1+ b))
9212         (while (re-search-forward "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*[ \t\n#]" e t) ; Need to include (?#) too?
9213           (forward-char -1)
9214           (insert "\\")
9215           (forward-char 1)))
9216       b)))
9217
9218 (defun cperl-beautify-regexp (&optional deep)
9219   "Do it.  (Experimental, may change semantics, recheck the result.)
9220 We suppose that the regexp is scanned already."
9221   (interactive "P")
9222   (setq deep (if deep (prefix-numeric-value deep) -1))
9223   (save-excursion
9224     (goto-char (cperl-make-regexp-x))
9225     (let ((b (point)) (e (make-marker)))
9226       (forward-sexp 1)
9227       (set-marker e (1- (point)))
9228       (cperl-beautify-regexp-piece b e nil deep))))
9229
9230 (defun cperl-regext-to-level-start ()
9231   "Goto start of an enclosing group in regexp.
9232 We suppose that the regexp is scanned already."
9233   (interactive)
9234   (let ((limit (cperl-make-regexp-x)) done)
9235     (while (not done)
9236       (or (eq (following-char) ?\()
9237           (search-backward "(" (1+ limit) t)
9238           (error "Cannot find `(' which starts a group"))
9239       (setq done
9240             (save-excursion
9241               (skip-chars-backward "\\")
9242               (looking-at "\\(\\\\\\\\\\)*(")))
9243       (or done (forward-char -1)))))
9244
9245 (defun cperl-contract-level ()
9246   "Find an enclosing group in regexp and contract it.
9247 \(Experimental, may change semantics, recheck the result.)
9248 We suppose that the regexp is scanned already."
9249   (interactive)
9250   ;; (save-excursion            ; Can't, breaks `cperl-contract-levels'
9251   (cperl-regext-to-level-start)
9252   (let ((b (point)) (e (make-marker)) c)
9253     (forward-sexp 1)
9254     (set-marker e (1- (point)))
9255     (goto-char b)
9256     (while (re-search-forward "\\(#\\)\\|\n" e 'to-end)
9257       (cond
9258        ((match-beginning 1)             ; #-comment
9259         (or c (setq c (current-indentation)))
9260         (beginning-of-line 2)           ; Skip
9261         (cperl-make-indent c))
9262        (t
9263         (delete-char -1)
9264         (just-one-space))))))
9265
9266 (defun cperl-contract-levels ()
9267   "Find an enclosing group in regexp and contract all the kids.
9268 \(Experimental, may change semantics, recheck the result.)
9269 We suppose that the regexp is scanned already."
9270   (interactive)
9271   (save-excursion
9272     (condition-case nil
9273         (cperl-regext-to-level-start)
9274       (error                            ; We are outside outermost group
9275        (goto-char (cperl-make-regexp-x))))
9276     (let ((b (point)) (e (make-marker)) s c)
9277       (forward-sexp 1)
9278       (set-marker e (1- (point)))
9279       (goto-char (1+ b))
9280       (while (re-search-forward "\\(\\\\\\\\\\)\\|(" e t)
9281         (cond
9282          ((match-beginning 1)           ; Skip
9283           nil)
9284          (t                             ; Group
9285           (cperl-contract-level)))))))
9286
9287 (defun cperl-beautify-level (&optional deep)
9288   "Find an enclosing group in regexp and beautify it.
9289 \(Experimental, may change semantics, recheck the result.)
9290 We suppose that the regexp is scanned already."
9291   (interactive "P")
9292   (setq deep (if deep (prefix-numeric-value deep) -1))
9293   (save-excursion
9294     (cperl-regext-to-level-start)
9295     (let ((b (point)) (e (make-marker)))
9296       (forward-sexp 1)
9297       (set-marker e (1- (point)))
9298       (cperl-beautify-regexp-piece b e nil deep))))
9299
9300 (defun cperl-invert-if-unless ()
9301   "Change `if (A) {B}' into `B if A;' etc if possible."
9302   (interactive)
9303   (or (looking-at "\\<")
9304       (forward-sexp -1))
9305   (if (looking-at "\\<\\(if\\|unless\\|while\\|until\\|for\\|foreach\\)\\>")
9306       (let ((pos1 (point))
9307             pos2 pos3 pos4 pos5 s1 s2 state p pos45
9308             (s0 (buffer-substring (match-beginning 0) (match-end 0))))
9309         (forward-sexp 2)
9310         (setq pos3 (point))
9311         (forward-sexp -1)
9312         (setq pos2 (point))
9313         (if (eq (following-char) ?\( )
9314             (progn
9315               (goto-char pos3)
9316               (forward-sexp 1)
9317               (setq pos5 (point))
9318               (forward-sexp -1)
9319               (setq pos4 (point))
9320               ;; XXXX In fact may be `A if (B); {C}' ...
9321               (if (and (eq (following-char) ?\{ )
9322                        (progn
9323                          (cperl-backward-to-noncomment pos3)
9324                          (eq (preceding-char) ?\) )))
9325                   (if (condition-case nil
9326                           (progn
9327                             (goto-char pos5)
9328                             (forward-sexp 1)
9329                             (forward-sexp -1)
9330                             (looking-at "\\<els\\(e\\|if\\)\\>"))
9331                         (error nil))
9332                       (error
9333                        "`%s' (EXPR) {BLOCK} with `else'/`elsif'" s0)
9334                     (goto-char (1- pos5))
9335                     (cperl-backward-to-noncomment pos4)
9336                     (if (eq (preceding-char) ?\;)
9337                         (forward-char -1))
9338                     (setq pos45 (point))
9339                     (goto-char pos4)
9340                     (while (re-search-forward "\\<\\(for\\|foreach\\|if\\|unless\\|while\\|until\\)\\>\\|;" pos45 t)
9341                       (setq p (match-beginning 0)
9342                             s1 (buffer-substring p (match-end 0))
9343                             state (parse-partial-sexp pos4 p))
9344                       (or (nth 3 state)
9345                           (nth 4 state)
9346                           (nth 5 state)
9347                           (error "`%s' inside `%s' BLOCK" s1 s0))
9348                       (goto-char (match-end 0)))
9349                     ;; Finally got it
9350                     (goto-char (1+ pos4))
9351                     (skip-chars-forward " \t\n")
9352                     (setq s2 (buffer-substring (point) pos45))
9353                     (goto-char pos45)
9354                     (or (looking-at ";?[ \t\n]*}")
9355                         (progn
9356                           (skip-chars-forward "; \t\n")
9357                           (setq s2 (concat s2 "\n" (buffer-substring (point) (1- pos5))))))
9358                     (and (equal s2 "")
9359                          (setq s2 "1"))
9360                     (goto-char (1- pos3))
9361                     (cperl-backward-to-noncomment pos2)
9362                     (or (looking-at "[ \t\n]*)")
9363                         (goto-char (1- pos3)))
9364                     (setq p (point))
9365                     (goto-char (1+ pos2))
9366                     (skip-chars-forward " \t\n")
9367                     (setq s1 (buffer-substring (point) p))
9368                     (delete-region pos4 pos5)
9369                     (delete-region pos2 pos3)
9370                     (goto-char pos1)
9371                     (insert s2 " ")
9372                     (just-one-space)
9373                     (forward-word 1)
9374                     (setq pos1 (point))
9375                     (insert " " s1 ";")
9376                     (delete-horizontal-space)
9377                     (forward-char -1)
9378                     (delete-horizontal-space)
9379                     (goto-char pos1)
9380                     (just-one-space)
9381                     (cperl-indent-line))
9382                 (error "`%s' (EXPR) not with an {BLOCK}" s0)))
9383           (error "`%s' not with an (EXPR)" s0)))
9384     (error "Not at `if', `unless', `while', `until', `for' or `foreach'")))
9385
9386 ;;; By Anthony Foiani <afoiani@uswest.com>
9387 ;;; Getting help on modules in C-h f ?
9388 ;;; This is a modified version of `man'.
9389 ;;; Need to teach it how to lookup functions
9390 ;;;###autoload
9391 (defun cperl-perldoc (word)
9392   "Run `perldoc' on WORD."
9393   (interactive
9394    (list (let* ((default-entry (cperl-word-at-point))
9395                 (input (read-string
9396                         (format "perldoc entry%s: "
9397                                 (if (string= default-entry "")
9398                                     ""
9399                                   (format " (default %s)" default-entry))))))
9400            (if (string= input "")
9401                (if (string= default-entry "")
9402                    (error "No perldoc args given")
9403                  default-entry)
9404              input))))
9405   (require 'man)
9406   (let* ((case-fold-search nil)
9407          (is-func (and
9408                    (string-match "^[a-z]+$" word)
9409                    (string-match (concat "^" word "\\>")
9410                                  (documentation-property
9411                                   'cperl-short-docs
9412                                   'variable-documentation))))
9413          (manual-program (if is-func "perldoc -f" "perldoc")))
9414     (cond
9415      (cperl-xemacs-p
9416       (let ((Manual-program "perldoc")
9417             (Manual-switches (if is-func (list "-f"))))
9418         (manual-entry word)))
9419      (t
9420       (Man-getpage-in-background word)))))
9421
9422 ;;;###autoload
9423 (defun cperl-perldoc-at-point ()
9424   "Run a `perldoc' on the word around point."
9425   (interactive)
9426   (cperl-perldoc (cperl-word-at-point)))
9427
9428 (defcustom pod2man-program "pod2man"
9429   "*File name for `pod2man'."
9430   :type 'file
9431   :group 'cperl)
9432
9433 ;;; By Nick Roberts <Nick.Roberts@src.bae.co.uk> (with changes)
9434 (defun cperl-pod-to-manpage ()
9435   "Create a virtual manpage in Emacs from the Perl Online Documentation."
9436   (interactive)
9437   (require 'man)
9438   (let* ((pod2man-args (concat buffer-file-name " | nroff -man "))
9439          (bufname (concat "Man " buffer-file-name))
9440          (buffer (generate-new-buffer bufname)))
9441     (save-excursion
9442       (set-buffer buffer)
9443       (let ((process-environment (copy-sequence process-environment)))
9444         ;; Prevent any attempt to use display terminal fanciness.
9445         (setenv "TERM" "dumb")
9446         (set-process-sentinel
9447          (start-process pod2man-program buffer "sh" "-c"
9448                         (format (cperl-pod2man-build-command) pod2man-args))
9449          'Man-bgproc-sentinel)))))
9450
9451 ;;; Updated version by him too
9452 (defun cperl-build-manpage ()
9453   "Create a virtual manpage in Emacs from the POD in the file."
9454   (interactive)
9455   (require 'man)
9456   (cond
9457    (cperl-xemacs-p
9458     (let ((Manual-program "perldoc"))
9459       (manual-entry buffer-file-name)))
9460    (t
9461     (let* ((manual-program "perldoc"))
9462       (Man-getpage-in-background buffer-file-name)))))
9463
9464 (defun cperl-pod2man-build-command ()
9465   "Builds the entire background manpage and cleaning command."
9466   (let ((command (concat pod2man-program " %s 2>/dev/null"))
9467         (flist (and (boundp 'Man-filter-list) Man-filter-list)))
9468     (while (and flist (car flist))
9469       (let ((pcom (car (car flist)))
9470             (pargs (cdr (car flist))))
9471         (setq command
9472               (concat command " | " pcom " "
9473                       (mapconcat '(lambda (phrase)
9474                                     (if (not (stringp phrase))
9475                                         (error "Malformed Man-filter-list"))
9476                                     phrase)
9477                                  pargs " ")))
9478         (setq flist (cdr flist))))
9479     command))
9480
9481 ;;; Initial version contributed by Trey Belew
9482 (defun cperl-here-doc-spell (&optional beg end)
9483   "Spell-check HERE-documents in the Perl buffer.
9484 If a region is highlighted, restricts to the region."
9485   (interactive "")
9486   (cperl-pod-spell t beg end))
9487
9488 (defun cperl-pod-spell (&optional do-heres beg end)
9489   "Spell-check POD documentation.
9490 If invoked with prefix argument, will do HERE-DOCs instead.
9491 If a region is highlighted, restricts to the region."
9492   (interactive "P")
9493   (save-excursion
9494     (let (beg end)
9495       (if (cperl-mark-active)
9496           (setq beg (min (mark) (point))
9497                 end (max (mark) (point)))
9498         (setq beg (point-min)
9499               end (point-max)))
9500       (cperl-map-pods-heres (function
9501                              (lambda (s e p)
9502                                (if do-heres
9503                                    (setq e (save-excursion
9504                                              (goto-char e)
9505                                              (forward-line -1)
9506                                              (point))))
9507                                (ispell-region s e)
9508                                t))
9509                             (if do-heres 'here-doc-group 'in-pod)
9510                             beg end))))
9511
9512 (defun cperl-map-pods-heres (func &optional prop s end)
9513   "Executes a function over regions of pods or here-documents.
9514 PROP is the text-property to search for; default to `in-pod'.  Stop when
9515 function returns nil."
9516   (let (pos posend has-prop (cont t))
9517     (or prop (setq prop 'in-pod))
9518     (or s (setq s (point-min)))
9519     (or end (setq end (point-max)))
9520     (cperl-update-syntaxification end end)
9521     (save-excursion
9522       (goto-char (setq pos s))
9523       (while (and cont (< pos end))
9524         (setq has-prop (get-text-property pos prop))
9525         (setq posend (next-single-property-change pos prop nil end))
9526         (and has-prop
9527              (setq cont (funcall func pos posend prop)))
9528         (setq pos posend)))))
9529
9530 ;;; Based on code by Masatake YAMATO:
9531 (defun cperl-get-here-doc-region (&optional pos pod)
9532   "Return HERE document region around the point.
9533 Return nil if the point is not in a HERE document region.  If POD is non-nil,
9534 will return a POD section if point is in a POD section."
9535   (or pos (setq pos (point)))
9536   (cperl-update-syntaxification pos pos)
9537   (if (or (eq 'here-doc  (get-text-property pos 'syntax-type))
9538           (and pod
9539                (eq 'pod (get-text-property pos 'syntax-type))))
9540       (let ((b (cperl-beginning-of-property pos 'syntax-type))
9541             (e (next-single-property-change pos 'syntax-type)))
9542         (cons b (or e (point-max))))))
9543
9544 (defun cperl-narrow-to-here-doc (&optional pos)
9545   "Narrows editing region to the HERE-DOC at POS.
9546 POS defaults to the point."
9547   (interactive "d")
9548   (or pos (setq pos (point)))
9549   (let ((p (cperl-get-here-doc-region pos)))
9550     (or p (error "Not inside a HERE document"))
9551     (narrow-to-region (car p) (cdr p))
9552     (message
9553      "When you are finished with narrow editing, type C-x n w")))
9554
9555 (defun cperl-select-this-pod-or-here-doc (&optional pos)
9556   "Select the HERE-DOC (or POD section) at POS.
9557 POS defaults to the point."
9558   (interactive "d")
9559   (let ((p (cperl-get-here-doc-region pos t)))
9560     (if p
9561         (progn
9562           (goto-char (car p))
9563           (push-mark (cdr p) nil t))    ; Message, activate in transient-mode
9564       (message "I do not think POS is in POD or a HERE-doc..."))))
9565
9566 (defun cperl-facemenu-add-face-function (face end)
9567   "A callback to process user-initiated font-change requests.
9568 Translates `bold', `italic', and `bold-italic' requests to insertion of
9569 corresponding POD directives, and `underline' to C<> POD directive.
9570
9571 Such requests are usually bound to M-o LETTER."
9572   (or (get-text-property (point) 'in-pod)
9573       (error "Faces can only be set within POD"))
9574   (setq facemenu-end-add-face (if (eq face 'bold-italic) ">>" ">"))
9575   (cdr (or (assq face '((bold . "B<")
9576                         (italic . "I<")
9577                         (bold-italic . "B<I<")
9578                         (underline . "C<")))
9579            (error "Face %s not configured for cperl-mode"
9580                   face))))
9581 \f
9582 (defun cperl-time-fontification (&optional l step lim)
9583   "Times how long it takes to do incremental fontification in a region.
9584 L is the line to start at, STEP is the number of lines to skip when
9585 doing next incremental fontification, LIM is the maximal number of
9586 incremental fontification to perform.  Messages are accumulated in
9587 *Messages* buffer.
9588
9589 May be used for pinpointing which construct slows down buffer fontification:
9590 start with default arguments, then refine the slowdown regions."
9591   (interactive "nLine to start at: \nnStep to do incremental fontification: ")
9592   (or l (setq l 1))
9593   (or step (setq step 500))
9594   (or lim (setq lim 40))
9595   (let* ((timems (function (lambda ()
9596                              (let ((tt (current-time)))
9597                                (+ (* 1000 (nth 1 tt)) (/ (nth 2 tt) 1000))))))
9598          (tt (funcall timems)) (c 0) delta tot)
9599     (goto-line l)
9600     (cperl-mode)
9601     (setq tot (- (- tt (setq tt (funcall timems)))))
9602     (message "cperl-mode at %s: %s" l tot)
9603     (while (and (< c lim) (not (eobp)))
9604       (forward-line step)
9605       (setq l (+ l step))
9606       (setq c (1+ c))
9607       (cperl-update-syntaxification (point) (point))
9608       (setq delta (- (- tt (setq tt (funcall timems)))) tot (+ tot delta))
9609       (message "to %s:%6s,%7s" l delta tot))
9610     tot))
9611
9612 (defun cperl-emulate-lazy-lock (&optional window-size)
9613   "Emulate `lazy-lock' without `condition-case', so `debug-on-error' works.
9614 Start fontifying the buffer from the start (or end) using the given
9615 WINDOW-SIZE (units is lines).  Negative WINDOW-SIZE starts at end, and
9616 goes backwards; default is -50.  This function is not CPerl-specific; it
9617 may be used to debug problems with delayed incremental fontification."
9618   (interactive
9619    "nSize of window for incremental fontification, negative goes backwards: ")
9620   (or window-size (setq window-size -50))
9621   (let ((pos (if (> window-size 0)
9622                  (point-min)
9623                (point-max)))
9624         p)
9625     (goto-char pos)
9626     (normal-mode)
9627     ;; Why needed???  With older font-locks???
9628     (set (make-local-variable 'font-lock-cache-position) (make-marker))
9629     (while (if (> window-size 0)
9630                (< pos (point-max))
9631              (> pos (point-min)))
9632       (setq p (progn
9633                 (forward-line window-size)
9634                 (point)))
9635       (font-lock-fontify-region (min p pos) (max p pos))
9636       (setq pos p))))
9637
9638 \f
9639 (defun cperl-lazy-install ())           ; Avoid a warning
9640 (defun cperl-lazy-unstall ())           ; Avoid a warning
9641
9642 (if (fboundp 'run-with-idle-timer)
9643     (progn
9644       (defvar cperl-help-shown nil
9645         "Non-nil means that the help was already shown now.")
9646
9647       (defvar cperl-lazy-installed nil
9648         "Non-nil means that the lazy-help handlers are installed now.")
9649
9650       (defun cperl-lazy-install ()
9651         "Switches on Auto-Help on Perl constructs (put in the message area).
9652 Delay of auto-help controlled by `cperl-lazy-help-time'."
9653         (interactive)
9654         (make-variable-buffer-local 'cperl-help-shown)
9655         (if (and (cperl-val 'cperl-lazy-help-time)
9656                  (not cperl-lazy-installed))
9657             (progn
9658               (add-hook 'post-command-hook 'cperl-lazy-hook)
9659               (run-with-idle-timer
9660                (cperl-val 'cperl-lazy-help-time 1000000 5)
9661                t
9662                'cperl-get-help-defer)
9663               (setq cperl-lazy-installed t))))
9664
9665       (defun cperl-lazy-unstall ()
9666         "Switches off Auto-Help on Perl constructs (put in the message area).
9667 Delay of auto-help controlled by `cperl-lazy-help-time'."
9668         (interactive)
9669         (remove-hook 'post-command-hook 'cperl-lazy-hook)
9670         (cancel-function-timers 'cperl-get-help-defer)
9671         (setq cperl-lazy-installed nil))
9672
9673       (defun cperl-lazy-hook ()
9674         (setq cperl-help-shown nil))
9675
9676       (defun cperl-get-help-defer ()
9677         (if (not (memq major-mode '(perl-mode cperl-mode))) nil
9678           (let ((cperl-message-on-help-error nil) (cperl-help-from-timer t))
9679             (cperl-get-help)
9680             (setq cperl-help-shown t))))
9681       (cperl-lazy-install)))
9682
9683
9684 ;;; Plug for wrong font-lock:
9685
9686 (defun cperl-font-lock-unfontify-region-function (beg end)
9687   (let* ((modified (buffer-modified-p)) (buffer-undo-list t)
9688          (inhibit-read-only t) (inhibit-point-motion-hooks t)
9689          before-change-functions after-change-functions
9690          deactivate-mark buffer-file-name buffer-file-truename)
9691     (remove-text-properties beg end '(face nil))
9692     (if (and (not modified) (buffer-modified-p))
9693       (set-buffer-modified-p nil))))
9694
9695 (defun cperl-font-lock-fontify-region-function (beg end loudly)
9696   "Extends the region to safe positions, then calls the default function.
9697 Newer `font-lock's can do it themselves.
9698 We unwind only as far as needed for fontification.  Syntaxification may
9699 do extra unwind via `cperl-unwind-to-safe'."
9700   (save-excursion
9701     (goto-char beg)
9702     (while (and beg
9703                 (progn
9704                   (beginning-of-line)
9705                   (eq (get-text-property (setq beg (point)) 'syntax-type)
9706                       'multiline)))
9707       (if (setq beg (cperl-beginning-of-property beg 'syntax-type))
9708           (goto-char beg)))
9709     (setq beg (point))
9710     (goto-char end)
9711     (while (and end
9712                 (progn
9713                   (or (bolp) (condition-case nil
9714                                  (forward-line 1)
9715                                (error nil)))
9716                   (eq (get-text-property (setq end (point)) 'syntax-type)
9717                       'multiline)))
9718       (setq end (next-single-property-change end 'syntax-type nil (point-max)))
9719       (goto-char end))
9720     (setq end (point)))
9721   (font-lock-default-fontify-region beg end loudly))
9722
9723 (defvar cperl-d-l nil)
9724 (defun cperl-fontify-syntaxically (end)
9725   ;; Some vars for debugging only
9726   ;; (message "Syntaxifying...")
9727   (let ((dbg (point)) (iend end) (idone cperl-syntax-done-to)
9728         (istate (car cperl-syntax-state))
9729         start from-start edebug-backtrace-buffer)
9730     (if (eq cperl-syntaxify-by-font-lock 'backtrace)
9731         (progn
9732           (require 'edebug)
9733           (let ((f 'edebug-backtrace))
9734             (funcall f))))      ; Avoid compile-time warning
9735     (or cperl-syntax-done-to
9736         (setq cperl-syntax-done-to (point-min)
9737               from-start t))
9738     (setq start (if (and cperl-hook-after-change
9739                          (not from-start))
9740                     cperl-syntax-done-to ; Fontify without change; ignore start
9741                   ;; Need to forget what is after `start'
9742                   (min cperl-syntax-done-to (point))))
9743     (goto-char start)
9744     (beginning-of-line)
9745     (setq start (point))
9746     (and cperl-syntaxify-unwind
9747          (setq end (cperl-unwind-to-safe t end)
9748                start (point)))
9749     (and (> end start)
9750          (setq cperl-syntax-done-to start) ; In case what follows fails
9751          (cperl-find-pods-heres start end t nil t))
9752     (if (memq cperl-syntaxify-by-font-lock '(backtrace message))
9753         (message "Syxify req=%s..%s actual=%s..%s done-to: %s=>%s statepos: %s=>%s"
9754                  dbg iend start end idone cperl-syntax-done-to
9755                  istate (car cperl-syntax-state))) ; For debugging
9756     nil))                               ; Do not iterate
9757
9758 (defun cperl-fontify-update (end)
9759   (let ((pos (point-min)) prop posend)
9760     (setq end (point-max))
9761     (while (< pos end)
9762       (setq prop (get-text-property pos 'cperl-postpone)
9763             posend (next-single-property-change pos 'cperl-postpone nil end))
9764       (and prop (put-text-property pos posend (car prop) (cdr prop)))
9765       (setq pos posend)))
9766   nil)                                  ; Do not iterate
9767
9768 (defun cperl-fontify-update-bad (end)
9769   ;; Since fontification happens with different region than syntaxification,
9770   ;; do to the end of buffer, not to END;;; likewise, start earlier if needed
9771   (let* ((pos (point)) (prop (get-text-property pos 'cperl-postpone)) posend)
9772     (if prop
9773         (setq pos (or (cperl-beginning-of-property
9774                        (cperl-1+ pos) 'cperl-postpone)
9775                       (point-min))))
9776     (while (< pos end)
9777       (setq posend (next-single-property-change pos 'cperl-postpone))
9778       (and prop (put-text-property pos posend (car prop) (cdr prop)))
9779       (setq pos posend)
9780       (setq prop (get-text-property pos 'cperl-postpone))))
9781   nil)                                  ; Do not iterate
9782
9783 ;; Called when any modification is made to buffer text.
9784 (defun cperl-after-change-function (beg end old-len)
9785   ;; We should have been informed about changes by `font-lock'.  Since it
9786   ;; does not inform as which calls are defered, do it ourselves
9787   (if cperl-syntax-done-to
9788       (setq cperl-syntax-done-to (min cperl-syntax-done-to beg))))
9789
9790 (defun cperl-update-syntaxification (from to)
9791   (if (and cperl-use-syntax-table-text-property
9792            cperl-syntaxify-by-font-lock
9793            (or (null cperl-syntax-done-to)
9794                (< cperl-syntax-done-to to)))
9795       (progn
9796         (save-excursion
9797           (goto-char from)
9798           (cperl-fontify-syntaxically to)))))
9799
9800 (defvar cperl-version
9801   (let ((v  "$Revision: 5.16 $"))
9802     (string-match ":\\s *\\([0-9.]+\\)" v)
9803     (substring v (match-beginning 1) (match-end 1)))
9804   "Version of IZ-supported CPerl package this file is based on.")
9805
9806 (provide 'cperl-mode)
9807
9808 ;;; cperl-mode.el ends here