]> git.donarmstrong.com Git - lib.git/blob - emacs_el/cperl-mode.el
* update 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.19 2006/06/01 11:11:57 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 ;;; After 5.15:
1405 ;;; `cperl-find-pods-heres':    Highlight capturing parens in REx
1406
1407 ;;; After 5.16:
1408 ;;; `cperl-find-pods-heres':    Highlight '|' for alternation
1409 ;;;     Initialize `font-lock-warning-face' if not present
1410 ;;; `cperl-find-pods-heres':    Use `font-lock-warning-face' instead of
1411 ;;;                                      `font-lock-function-name-face'
1412 ;;; `cperl-look-at-leading-count': Likewise
1413 ;;; `cperl-find-pods-heres':    localize `font-lock-variable-name-face'
1414 ;;;                                     `font-lock-keyword-face' (needed for
1415 ;;;                                     batch processing) etc
1416 ;;;                             Use `font-lock-builtin-face' for builtin in REx
1417 ;;;                                     Now `font-lock-variable-name-face'
1418 ;;;                                     is used for interpolated variables.
1419 ;;;                             Use "talking aliases" for faces inside REx
1420 ;;;                             Highlight parts of REx (except in charclasses)
1421 ;;;                                     according to the syntax and/or semantic
1422 ;;;                             Syntax-mark a {}-part of (?{}) as "comment"
1423 ;;;                                     (it was the ()-part)
1424 ;;;                             Better logic to distinguish what is what in REx
1425 ;;; `cperl-tips-faces':         Document REx highlighting
1426 ;;; `cperl-praise':             Mention REx syntax highlight etc.
1427
1428 ;;; After 5.17:
1429 ;;; `cperl-find-sub-attrs':     Would not always manage to print error message
1430 ;;; `cperl-find-pods-heres':    localize `font-lock-constant-face'
1431
1432 ;;; After 5.18:
1433 ;;; `cperl-find-pods-heres':    Misprint in REx for parsing REx
1434 ;;;                             Very minor optimization
1435 ;;;                             `my-cperl-REx-modifiers-face' got quoted
1436 ;;;                             Recognize "print $foo <<END" as HERE-doc.
1437 ;;;                             Put `REx-interpolated' text attribute if needed
1438 ;;; `cperl-invert-if-unless-modifiers': New function.
1439 ;;; `cperl-backward-to-start-of-expr': Likewise
1440 ;;; `cperl-forward-to-end-of-expr': Likewise
1441 ;;; `cperl-invert-if-unless':   Works in "the opposite way" too.
1442 ;;;                             Cursor position on return is on the switch-word
1443 ;;;                             Indents comments better
1444 ;;; `REx-interpolated':         New text attribute
1445 ;;; `cperl-next-interpolated-REx': New function.
1446 ;;; `cperl-next-interpolated-REx-0': Likewise.
1447 ;;; `cperl-next-interpolated-REx-1': Likewise.
1448 ;;; "\C-c\C-x", "\C-c\C-y", "\C-c\C-v": New keybinding for these functions
1449 ;;; Perl/Regexp menu:           3 new entries for `cperl-next-interpolated-REx'
1450 ;;; `cperl-praise':             Mention finded interpolated RExen.
1451
1452 ;;; Code:
1453 \f
1454 (if (fboundp 'eval-when-compile)
1455     (eval-when-compile
1456       (condition-case nil
1457           (require 'custom)
1458         (error nil))
1459       (condition-case nil
1460           (require 'man)
1461         (error nil))
1462       (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1463       (defvar cperl-can-font-lock
1464         (or cperl-xemacs-p
1465             (and (boundp 'emacs-major-version)
1466                  (or window-system
1467                      (> emacs-major-version 20)))))
1468       (if cperl-can-font-lock
1469           (require 'font-lock))
1470       (defvar msb-menu-cond)
1471       (defvar gud-perldb-history)
1472       (defvar font-lock-background-mode) ; not in Emacs
1473       (defvar font-lock-display-type)   ; ditto
1474       (or (fboundp 'defgroup)
1475           (defmacro defgroup (name val doc &rest arr)
1476             nil))
1477       (or (fboundp 'custom-declare-variable)
1478           (defmacro defcustom (name val doc &rest arr)
1479             (` (defvar (, name) (, val) (, doc)))))
1480       (or (and (fboundp 'custom-declare-variable)
1481                (string< "19.31" emacs-version)) ;  Checked with 19.30: defface does not work
1482           (defmacro defface (&rest arr)
1483             nil))
1484       ;; Avoid warning (tmp definitions)
1485       (or (fboundp 'x-color-defined-p)
1486           (defmacro x-color-defined-p (col)
1487             (cond ((fboundp 'color-defined-p) (` (color-defined-p (, col))))
1488                   ;; XEmacs >= 19.12
1489                   ((fboundp 'valid-color-name-p) (` (valid-color-name-p (, col))))
1490                   ;; XEmacs 19.11
1491                   ((fboundp 'x-valid-color-name-p) (` (x-valid-color-name-p (, col))))
1492                   (t '(error "Cannot implement color-defined-p")))))
1493       (defmacro cperl-is-face (arg)     ; Takes quoted arg
1494         (cond ((fboundp 'find-face)
1495                (` (find-face (, arg))))
1496               (;;(and (fboundp 'face-list)
1497                ;;       (face-list))
1498                (fboundp 'face-list)
1499                (` (member (, arg) (and (fboundp 'face-list)
1500                                        (face-list)))))
1501               (t
1502                (` (boundp (, arg))))))
1503       (defmacro cperl-make-face (arg descr) ; Takes unquoted arg
1504         (cond ((fboundp 'make-face)
1505                (` (make-face (quote (, arg)))))
1506               (t
1507                (` (defvar (, arg) (quote (, arg)) (, descr))))))
1508       (defmacro cperl-force-face (arg descr) ; Takes unquoted arg
1509         (` (progn
1510              (or (cperl-is-face (quote (, arg)))
1511                  (cperl-make-face (, arg) (, descr)))
1512              (or (boundp (quote (, arg))) ; We use unquoted variants too
1513                  (defvar (, arg) (quote (, arg)) (, descr))))))
1514       (if cperl-xemacs-p
1515           (defmacro cperl-etags-snarf-tag (file line)
1516             (` (progn
1517                  (beginning-of-line 2)
1518                  (list (, file) (, line)))))
1519         (defmacro cperl-etags-snarf-tag (file line)
1520           (` (etags-snarf-tag))))
1521       (if cperl-xemacs-p
1522           (defmacro cperl-etags-goto-tag-location (elt)
1523             (`;;(progn
1524              ;; (switch-to-buffer (get-file-buffer (elt (, elt) 0)))
1525              ;; (set-buffer (get-file-buffer (elt (, elt) 0)))
1526              ;; Probably will not work due to some save-excursion???
1527              ;; Or save-file-position?
1528              ;; (message "Did I get to line %s?" (elt (, elt) 1))
1529              (goto-line (string-to-int (elt (, elt) 1)))))
1530         ;;)
1531         (defmacro cperl-etags-goto-tag-location (elt)
1532           (` (etags-goto-tag-location (, elt)))))))
1533
1534 (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1535
1536 (defvar cperl-can-font-lock
1537   (or cperl-xemacs-p
1538       (and (boundp 'emacs-major-version)
1539            (or window-system
1540                (> emacs-major-version 20)))))
1541
1542 (condition-case nil
1543     (require 'custom)
1544   (error nil))                          ; Already fixed by eval-when-compile
1545
1546 (defun cperl-choose-color (&rest list)
1547   (let (answer)
1548     (while list
1549       (or answer
1550           (if (or (x-color-defined-p (car list))
1551                   (null (cdr list)))
1552               (setq answer (car list))))
1553       (setq list (cdr list)))
1554     answer))
1555
1556 \f
1557 (defgroup cperl nil
1558   "Major mode for editing Perl code."
1559   :prefix "cperl-"
1560   :group 'languages)
1561
1562 (defgroup cperl-indentation-details nil
1563   "Indentation."
1564   :prefix "cperl-"
1565   :group 'cperl)
1566
1567 (defgroup cperl-affected-by-hairy nil
1568   "Variables affected by `cperl-hairy'."
1569   :prefix "cperl-"
1570   :group 'cperl)
1571
1572 (defgroup cperl-autoinsert-details nil
1573   "Auto-insert tuneup."
1574   :prefix "cperl-"
1575   :group 'cperl)
1576
1577 (defgroup cperl-faces nil
1578   "Fontification colors."
1579   :prefix "cperl-"
1580   :group 'cperl)
1581
1582 (defgroup cperl-speed nil
1583   "Speed vs. validity tuneup."
1584   :prefix "cperl-"
1585   :group 'cperl)
1586
1587 (defgroup cperl-help-system nil
1588   "Help system tuneup."
1589   :prefix "cperl-"
1590   :group 'cperl)
1591
1592 \f
1593 (defcustom cperl-extra-newline-before-brace nil
1594   "*Non-nil means that if, elsif, while, until, else, for, foreach
1595 and do constructs look like:
1596
1597         if ()
1598         {
1599         }
1600
1601 instead of:
1602
1603         if () {
1604         }"
1605   :type 'boolean
1606   :group 'cperl-autoinsert-details)
1607
1608 (defcustom cperl-extra-newline-before-brace-multiline
1609   cperl-extra-newline-before-brace
1610   "*Non-nil means the same as `cperl-extra-newline-before-brace', but
1611 for constructs with multiline if/unless/while/until/for/foreach condition."
1612   :type 'boolean
1613   :group 'cperl-autoinsert-details)
1614
1615 (defcustom cperl-indent-level 2
1616   "*Indentation of CPerl statements with respect to containing block."
1617   :type 'integer
1618   :group 'cperl-indentation-details)
1619
1620 (defcustom cperl-lineup-step nil
1621   "*`cperl-lineup' will always lineup at multiple of this number.
1622 If nil, the value of `cperl-indent-level' will be used."
1623   :type '(choice (const nil) integer)
1624   :group 'cperl-indentation-details)
1625
1626 (defcustom cperl-brace-imaginary-offset 0
1627   "*Imagined indentation of a Perl open brace that actually follows a statement.
1628 An open brace following other text is treated as if it were this far
1629 to the right of the start of its line."
1630   :type 'integer
1631   :group 'cperl-indentation-details)
1632
1633 (defcustom cperl-brace-offset 0
1634   "*Extra indentation for braces, compared with other text in same context."
1635   :type 'integer
1636   :group 'cperl-indentation-details)
1637 (defcustom cperl-label-offset -2
1638   "*Offset of CPerl label lines relative to usual indentation."
1639   :type 'integer
1640   :group 'cperl-indentation-details)
1641 (defcustom cperl-min-label-indent 1
1642   "*Minimal offset of CPerl label lines."
1643   :type 'integer
1644   :group 'cperl-indentation-details)
1645 (defcustom cperl-continued-statement-offset 2
1646   "*Extra indent for lines not starting new statements."
1647   :type 'integer
1648   :group 'cperl-indentation-details)
1649 (defcustom cperl-continued-brace-offset 0
1650   "*Extra indent for substatements that start with open-braces.
1651 This is in addition to cperl-continued-statement-offset."
1652   :type 'integer
1653   :group 'cperl-indentation-details)
1654 (defcustom cperl-close-paren-offset -1
1655   "*Extra indent for substatements that start with close-parenthesis."
1656   :type 'integer
1657   :group 'cperl-indentation-details)
1658
1659 (defcustom cperl-auto-newline nil
1660   "*Non-nil means automatically newline before and after braces,
1661 and after colons and semicolons, inserted in CPerl code.  The following
1662 \\[cperl-electric-backspace] will remove the inserted whitespace.
1663 Insertion after colons requires both this variable and
1664 `cperl-auto-newline-after-colon' set."
1665   :type 'boolean
1666   :group 'cperl-autoinsert-details)
1667
1668 (defcustom cperl-autoindent-on-semi nil
1669   "*Non-nil means automatically indent after insertion of (semi)colon.
1670 Active if `cperl-auto-newline' is false."
1671   :type 'boolean
1672   :group 'cperl-autoinsert-details)
1673
1674 (defcustom cperl-auto-newline-after-colon nil
1675   "*Non-nil means automatically newline even after colons.
1676 Subject to `cperl-auto-newline' setting."
1677   :type 'boolean
1678   :group 'cperl-autoinsert-details)
1679
1680 (defcustom cperl-tab-always-indent t
1681   "*Non-nil means TAB in CPerl mode should always reindent the current line,
1682 regardless of where in the line point is when the TAB command is used."
1683   :type 'boolean
1684   :group 'cperl-indentation-details)
1685
1686 (defcustom cperl-font-lock nil
1687   "*Non-nil (and non-null) means CPerl buffers will use `font-lock-mode'.
1688 Can be overwritten by `cperl-hairy' if nil."
1689   :type '(choice (const null) boolean)
1690   :group 'cperl-affected-by-hairy)
1691
1692 (defcustom cperl-electric-lbrace-space nil
1693   "*Non-nil (and non-null) means { after $ should be preceded by ` '.
1694 Can be overwritten by `cperl-hairy' if nil."
1695   :type '(choice (const null) boolean)
1696   :group 'cperl-affected-by-hairy)
1697
1698 (defcustom cperl-electric-parens-string "({[]})<"
1699   "*String of parentheses that should be electric in CPerl.
1700 Closing ones are electric only if the region is highlighted."
1701   :type 'string
1702   :group 'cperl-affected-by-hairy)
1703
1704 (defcustom cperl-electric-parens nil
1705   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
1706 Can be overwritten by `cperl-hairy' if nil."
1707   :type '(choice (const null) boolean)
1708   :group 'cperl-affected-by-hairy)
1709
1710 (defvar zmacs-regions)                  ; Avoid warning
1711
1712 (defcustom cperl-electric-parens-mark
1713   (and window-system
1714        (or (and (boundp 'transient-mark-mode) ; For Emacs
1715                 transient-mark-mode)
1716            (and (boundp 'zmacs-regions) ; For XEmacs
1717                 zmacs-regions)))
1718   "*Not-nil means that electric parens look for active mark.
1719 Default is yes if there is visual feedback on mark."
1720   :type 'boolean
1721   :group 'cperl-autoinsert-details)
1722
1723 (defcustom cperl-electric-linefeed nil
1724   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
1725 In any case these two mean plain and hairy linefeeds together.
1726 Can be overwritten by `cperl-hairy' if nil."
1727   :type '(choice (const null) boolean)
1728   :group 'cperl-affected-by-hairy)
1729
1730 (defcustom cperl-electric-keywords nil
1731   "*Not-nil (and non-null) means keywords are electric in CPerl.
1732 Can be overwritten by `cperl-hairy' if nil."
1733   :type '(choice (const null) boolean)
1734   :group 'cperl-affected-by-hairy)
1735
1736 (defcustom cperl-electric-backspace-untabify t
1737   "*Not-nil means electric-backspace will untabify in CPerl."
1738   :type 'boolean
1739   :group 'cperl-autoinsert-details)
1740
1741 (defcustom cperl-hairy nil
1742   "*Not-nil means most of the bells and whistles are enabled in CPerl.
1743 Affects: `cperl-font-lock', `cperl-electric-lbrace-space',
1744 `cperl-electric-parens', `cperl-electric-linefeed', `cperl-electric-keywords',
1745 `cperl-info-on-command-no-prompt', `cperl-clobber-lisp-bindings',
1746 `cperl-lazy-help-time'."
1747   :type 'boolean
1748   :group 'cperl-affected-by-hairy)
1749
1750 (defcustom cperl-comment-column 32
1751   "*Column to put comments in CPerl (use \\[cperl-indent] to lineup with code)."
1752   :type 'integer
1753   :group 'cperl-indentation-details)
1754
1755 (defcustom cperl-vc-sccs-header '("($sccs) = ('%W\%' =~ /(\\d+(\\.\\d+)+)/) ;")
1756   "*Special version of `vc-sccs-header' that is used in CPerl mode buffers."
1757   :type '(repeat string)
1758   :group 'cperl)
1759
1760 (defcustom cperl-vc-rcs-header '("($rcs) = (' $Id\$ ' =~ /(\\d+(\\.\\d+)+)/);")
1761   "*Special version of `vc-rcs-header' that is used in CPerl mode buffers."
1762   :type '(repeat string)
1763      :group 'cperl)
1764
1765 ;; This became obsolete...
1766 (defcustom cperl-vc-header-alist '()
1767   "*What to use as `vc-header-alist' in CPerl.
1768 Obsolete, with newer Emacsen use `cperl-vc-rcs-header' or
1769 `cperl-vc-sccs-header' instead.  If this list is empty, `vc-header-alist'
1770 will be reconstructed basing on these two variables."
1771   :type '(repeat (list symbol string))
1772   :group 'cperl)
1773
1774 (defcustom cperl-clobber-mode-lists
1775   (not
1776    (and
1777     (boundp 'interpreter-mode-alist)
1778     (assoc "miniperl" interpreter-mode-alist)
1779     (assoc "\\.\\([pP][Llm]\\|al\\)$" auto-mode-alist)))
1780   "*Whether to install us into `interpreter-' and `extension' mode lists."
1781   :type 'boolean
1782   :group 'cperl)
1783
1784 (defcustom cperl-info-on-command-no-prompt nil
1785   "*Not-nil (and non-null) means not to prompt on C-h f.
1786 The opposite behaviour is always available if prefixed with C-c.
1787 Can be overwritten by `cperl-hairy' if nil."
1788   :type '(choice (const null) boolean)
1789   :group 'cperl-affected-by-hairy)
1790
1791 (defcustom cperl-clobber-lisp-bindings nil
1792   "*Not-nil (and non-null) means not overwrite C-h f.
1793 The function is available on \\[cperl-info-on-command], \\[cperl-get-help].
1794 Can be overwritten by `cperl-hairy' if nil."
1795   :type '(choice (const null) boolean)
1796   :group 'cperl-affected-by-hairy)
1797
1798 (defcustom cperl-lazy-help-time nil
1799   "*Not-nil (and non-null) means to show lazy help after given idle time.
1800 Can be overwritten by `cperl-hairy' to be 5 sec if nil."
1801   :type '(choice (const null) (const nil) integer)
1802   :group 'cperl-affected-by-hairy)
1803
1804 (defcustom cperl-pod-face 'font-lock-comment-face
1805   "*The result of evaluation of this expression is used for POD highlighting."
1806   :type 'face
1807   :group 'cperl-faces)
1808
1809 (defcustom cperl-pod-head-face 'font-lock-variable-name-face
1810   "*The result of evaluation of this expression is used for POD highlighting.
1811 Font for POD headers."
1812   :type 'face
1813   :group 'cperl-faces)
1814
1815 (defcustom cperl-here-face 'font-lock-string-face
1816   "*The result of evaluation of this expression is used for here-docs highlighting."
1817   :type 'face
1818   :group 'cperl-faces)
1819
1820 ;;; Some double-evaluation happened with font-locks...  Needed with 21.2...
1821 (defvar cperl-singly-quote-face cperl-xemacs-p)
1822
1823 (defcustom cperl-invalid-face           ; Does not customize with '' on XEmacs
1824   (if cperl-singly-quote-face
1825       'underline ''underline) ; On older Emacsen was evaluated by `font-lock'
1826   (if cperl-singly-quote-face
1827       "*This face is used for highlighting trailing whitespace."
1828     "*The result of evaluation of this expression highlights trailing whitespace.")
1829   :type 'face
1830   :group 'cperl-faces)
1831
1832 (defcustom cperl-pod-here-fontify '(featurep 'font-lock)
1833   "*Not-nil after evaluation means to highlight POD and here-docs sections."
1834   :type 'boolean
1835   :group 'cperl-faces)
1836
1837 (defcustom cperl-fontify-m-as-s t
1838   "*Not-nil means highlight 1arg regular expressions operators same as 2arg."
1839   :type 'boolean
1840   :group 'cperl-faces)
1841
1842 (defcustom cperl-highlight-variables-indiscriminately nil
1843   "*Non-nil means perform additional highlighting on variables.
1844 Currently only changes how scalar variables are highlighted.
1845 Note that that variable is only read at initialization time for
1846 the variable `perl-font-lock-keywords-2', so changing it after you've
1847 entered CPerl mode the first time will have no effect."
1848   :type 'boolean
1849   :group 'cperl)
1850
1851 (defcustom cperl-pod-here-scan t
1852   "*Not-nil means look for POD and here-docs sections during startup.
1853 You can always make lookup from menu or using \\[cperl-find-pods-heres]."
1854   :type 'boolean
1855   :group 'cperl-speed)
1856
1857 (defcustom cperl-regexp-scan t
1858   "*Not-nil means make marking of regular expression more thorough.
1859 Effective only with `cperl-pod-here-scan'."
1860   :type 'boolean
1861   :group 'cperl-speed)
1862
1863 (defcustom cperl-hook-after-change t
1864   "*Not-nil means install hook to know which regions of buffer are changed.
1865 May significantly speed up delayed fontification.  Changes take effect
1866 after reload."
1867   :type 'boolean
1868   :group 'cperl-speed)
1869
1870 (defcustom cperl-imenu-addback nil
1871   "*Not-nil means add backreferences to generated `imenu's.
1872 May require patched `imenu' and `imenu-go'.  Obsolete."
1873   :type 'boolean
1874   :group 'cperl-help-system)
1875
1876 (defcustom cperl-max-help-size 66
1877   "*Non-nil means shrink-wrapping of info-buffer allowed up to these percents."
1878   :type '(choice integer (const nil))
1879   :group 'cperl-help-system)
1880
1881 (defcustom cperl-shrink-wrap-info-frame t
1882   "*Non-nil means shrink-wrapping of info-buffer-frame allowed."
1883   :type 'boolean
1884   :group 'cperl-help-system)
1885
1886 (defcustom cperl-info-page "perl"
1887   "*Name of the info page containing perl docs.
1888 Older version of this page was called `perl5', newer `perl'."
1889   :type 'string
1890   :group 'cperl-help-system)
1891
1892 (defcustom cperl-use-syntax-table-text-property
1893   (boundp 'parse-sexp-lookup-properties)
1894   "*Non-nil means CPerl sets up and uses `syntax-table' text property."
1895   :type 'boolean
1896   :group 'cperl-speed)
1897
1898 (defcustom cperl-use-syntax-table-text-property-for-tags
1899   cperl-use-syntax-table-text-property
1900   "*Non-nil means: set up and use `syntax-table' text property generating TAGS."
1901   :type 'boolean
1902   :group 'cperl-speed)
1903
1904 (defcustom cperl-scan-files-regexp "\\.\\([pP][Llm]\\|xs\\)$"
1905   "*Regexp to match files to scan when generating TAGS."
1906   :type 'regexp
1907   :group 'cperl)
1908
1909 (defcustom cperl-noscan-files-regexp
1910   "/\\(\\.\\.?\\|SCCS\\|RCS\\|CVS\\|blib\\)$"
1911   "*Regexp to match files/dirs to skip when generating TAGS."
1912   :type 'regexp
1913   :group 'cperl)
1914
1915 (defcustom cperl-regexp-indent-step nil
1916   "*Indentation used when beautifying regexps.
1917 If nil, the value of `cperl-indent-level' will be used."
1918   :type '(choice integer (const nil))
1919   :group 'cperl-indentation-details)
1920
1921 (defcustom cperl-indent-left-aligned-comments t
1922   "*Non-nil means that the comment starting in leftmost column should indent."
1923   :type 'boolean
1924   :group 'cperl-indentation-details)
1925
1926 (defcustom cperl-under-as-char t
1927   "*Non-nil means that the _ (underline) should be treated as word char."
1928   :type 'boolean
1929   :group 'cperl)
1930
1931 (defcustom cperl-extra-perl-args ""
1932   "*Extra arguments to use when starting Perl.
1933 Currently used with `cperl-check-syntax' only."
1934   :type 'string
1935   :group 'cperl)
1936
1937 (defcustom cperl-message-electric-keyword t
1938   "*Non-nil means that the `cperl-electric-keyword' prints a help message."
1939   :type 'boolean
1940   :group 'cperl-help-system)
1941
1942 (defcustom cperl-indent-region-fix-constructs 1
1943   "*Amount of space to insert between `}' and `else' or `elsif'
1944 in `cperl-indent-region'.  Set to nil to leave as is.  Values other
1945 than 1 and nil will probably not work."
1946   :type '(choice (const nil) (const 1))
1947   :group 'cperl-indentation-details)
1948
1949 (defcustom cperl-break-one-line-blocks-when-indent t
1950   "*Non-nil means that one-line if/unless/while/until/for/foreach BLOCKs
1951 need to be reformatted into multiline ones when indenting a region."
1952   :type 'boolean
1953   :group 'cperl-indentation-details)
1954
1955 (defcustom cperl-fix-hanging-brace-when-indent t
1956   "*Non-nil means that BLOCK-end `}' may be put on a separate line
1957 when indenting a region.
1958 Braces followed by else/elsif/while/until are excepted."
1959   :type 'boolean
1960   :group 'cperl-indentation-details)
1961
1962 (defcustom cperl-merge-trailing-else t
1963   "*Non-nil means that BLOCK-end `}' followed by else/elsif/continue
1964 may be merged to be on the same line when indenting a region."
1965   :type 'boolean
1966   :group 'cperl-indentation-details)
1967
1968 (defcustom cperl-indent-parens-as-block nil
1969   "*Non-nil means that non-block ()-, {}- and []-groups are indented as blocks,
1970 but for trailing \",\" inside the group, which won't increase indentation.
1971 One should tune up `cperl-close-paren-offset' as well."
1972   :type 'boolean
1973   :group 'cperl-indentation-details)
1974
1975 (defcustom cperl-syntaxify-by-font-lock
1976   (and cperl-can-font-lock
1977        (boundp 'parse-sexp-lookup-properties))
1978   "*Non-nil means that CPerl uses `font-lock's routines for syntaxification."
1979   :type '(choice (const message) boolean)
1980   :group 'cperl-speed)
1981
1982 (defcustom cperl-syntaxify-unwind
1983   t
1984   "*Non-nil means that CPerl unwinds to a start of a long construction
1985 when syntaxifying a chunk of buffer."
1986   :type 'boolean
1987   :group 'cperl-speed)
1988
1989 (defcustom cperl-syntaxify-for-menu
1990   t
1991   "*Non-nil means that CPerl syntaxifies up to the point before showing menu.
1992 This way enabling/disabling of menu items is more correct."
1993   :type 'boolean
1994   :group 'cperl-speed)
1995
1996 (defcustom cperl-ps-print-face-properties
1997   '((font-lock-keyword-face             nil nil         bold shadow)
1998     (font-lock-variable-name-face       nil nil         bold)
1999     (font-lock-function-name-face       nil nil         bold italic box)
2000     (font-lock-constant-face            nil "LightGray" bold)
2001     (cperl-array-face                   nil "LightGray" bold underline)
2002     (cperl-hash-face                    nil "LightGray" bold italic underline)
2003     (font-lock-comment-face             nil "LightGray" italic)
2004     (font-lock-string-face              nil nil         italic underline)
2005     (cperl-nonoverridable-face          nil nil         italic underline)
2006     (font-lock-type-face                nil nil         underline)
2007     (font-lock-warning-face             nil "LightGray" bold italic box)
2008     (underline                          nil "LightGray" strikeout))
2009   "List given as an argument to `ps-extend-face-list' in `cperl-ps-print'."
2010   :type '(repeat (cons symbol
2011                        (cons (choice (const nil) string)
2012                              (cons (choice (const nil) string)
2013                                    (repeat symbol)))))
2014   :group 'cperl-faces)
2015
2016 (if cperl-can-font-lock
2017     (progn
2018       (defvar cperl-dark-background
2019         (cperl-choose-color "navy" "os2blue" "darkgreen"))
2020       (defvar cperl-dark-foreground
2021         (cperl-choose-color "orchid1" "orange"))
2022
2023       (defface cperl-nonoverridable-face
2024         (` ((((class grayscale) (background light))
2025              (:background "Gray90" :italic t :underline t))
2026             (((class grayscale) (background dark))
2027              (:foreground "Gray80" :italic t :underline t :bold t))
2028             (((class color) (background light))
2029              (:foreground "chartreuse3"))
2030             (((class color) (background dark))
2031              (:foreground (, cperl-dark-foreground)))
2032             (t (:bold t :underline t))))
2033         "Font Lock mode face used to highlight array names."
2034         :group 'cperl-faces)
2035
2036       (defface cperl-array-face
2037         (` ((((class grayscale) (background light))
2038              (:background "Gray90" :bold t))
2039             (((class grayscale) (background dark))
2040              (:foreground "Gray80" :bold t))
2041             (((class color) (background light))
2042              (:foreground "Blue" :background "lightyellow2" :bold t))
2043             (((class color) (background dark))
2044              (:foreground "yellow" :background (, cperl-dark-background) :bold t))
2045             (t (:bold t))))
2046         "Font Lock mode face used to highlight array names."
2047         :group 'cperl-faces)
2048
2049       (defface cperl-hash-face
2050         (` ((((class grayscale) (background light))
2051              (:background "Gray90" :bold t :italic t))
2052             (((class grayscale) (background dark))
2053              (:foreground "Gray80" :bold t :italic t))
2054             (((class color) (background light))
2055              (:foreground "Red" :background "lightyellow2" :bold t :italic t))
2056             (((class color) (background dark))
2057              (:foreground "Red" :background (, cperl-dark-background) :bold t :italic t))
2058             (t (:bold t :italic t))))
2059         "Font Lock mode face used to highlight hash names."
2060         :group 'cperl-faces)))
2061
2062 \f
2063
2064 ;;; Short extra-docs.
2065
2066 (defvar cperl-tips 'please-ignore-this-line
2067   "Get maybe newer version of this package from
2068   http://ilyaz.org/software/emacs
2069 Subdirectory `cperl-mode' may contain yet newer development releases and/or
2070 patches to related files.
2071
2072 For best results apply to an older Emacs the patches from
2073   ftp://ftp.math.ohio-state.edu/pub/users/ilya/cperl-mode/patches
2074 \(this upgrades syntax-parsing abilities of RMS Emaxen v19.34 and
2075 v20.2 up to the level of RMS Emacs v20.3 - a must for a good Perl
2076 mode.)  As of beginning of 2003, XEmacs may provide a similar ability.
2077
2078 Get support packages choose-color.el (or font-lock-extra.el before
2079 19.30), imenu-go.el from the same place.  \(Look for other files there
2080 too... ;-).  Get a patch for imenu.el in 19.29.  Note that for 19.30 and
2081 later you should use choose-color.el *instead* of font-lock-extra.el
2082 \(and you will not get smart highlighting in C :-().
2083
2084 Note that to enable Compile choices in the menu you need to install
2085 mode-compile.el.
2086
2087 If your Emacs does not default to `cperl-mode' on Perl files, and you
2088 want it to: put the following into your .emacs file:
2089
2090   (autoload 'perl-mode \"cperl-mode\" \"alternate mode for editing Perl programs\" t)
2091
2092 or
2093
2094   (defalias 'perl-mode 'cperl-mode)
2095
2096 Get perl5-info from
2097   $CPAN/doc/manual/info/perl5-old/perl5-info.tar.gz
2098 Also, one can generate a newer documentation running `pod2texi' converter
2099   $CPAN/doc/manual/info/perl5/pod2texi-0.1.tar.gz
2100
2101 If you use imenu-go, run imenu on perl5-info buffer (you can do it
2102 from Perl menu).  If many files are related, generate TAGS files from
2103 Tools/Tags submenu in Perl menu.
2104
2105 If some class structure is too complicated, use Tools/Hierarchy-view
2106 from Perl menu, or hierarchic view of imenu.  The second one uses the
2107 current buffer only, the first one requires generation of TAGS from
2108 Perl/Tools/Tags menu beforehand.
2109
2110 Run Perl/Tools/Insert-spaces-if-needed to fix your lazy typing.
2111
2112 Switch auto-help on/off with Perl/Tools/Auto-help.
2113
2114 Though with contemporary Emaxen CPerl mode should maintain the correct
2115 parsing of Perl even when editing, sometimes it may be lost.  Fix this by
2116
2117   M-x norm RET
2118
2119 or
2120
2121   \\[normal-mode]
2122
2123 In cases of more severe confusion sometimes it is helpful to do
2124
2125   M-x load-l RET cperl-mode RET
2126   M-x norm RET
2127
2128 or
2129
2130   \\[load-library] cperl-mode RET
2131   \\[normal-mode]
2132
2133 Before reporting (non-)problems look in the problem section of online
2134 micro-docs on what I know about CPerl problems.")
2135
2136 (defvar cperl-problems 'please-ignore-this-line
2137   "Description of problems in CPerl mode.
2138 Some faces will not be shown on some versions of Emacs unless you
2139 install choose-color.el, available from
2140   http://ilyaz.org/software/emacs
2141
2142 `fill-paragraph' on a comment may leave the point behind the
2143 paragraph.  It also triggers a bug in some versions of Emacs (CPerl tries
2144 to detect it and bulk out).
2145
2146 See documentation of a variable `cperl-problems-old-emaxen' for the
2147 problems which disappear if you upgrade Emacs to a reasonably new
2148 version (20.3 for RMS Emacs, and those of 2004 for XEmacs).")
2149
2150 (defvar cperl-problems-old-emaxen 'please-ignore-this-line
2151   "Description of problems in CPerl mode specific for older Emacs versions.
2152
2153 Emacs had a _very_ restricted syntax parsing engine until RMS's Emacs
2154 20.1.  Most problems below are corrected starting from this version of
2155 Emacs, and all of them should be fixed in RMS's version 20.3.  (Or apply
2156 patches to Emacs 19.33/34 - see tips.)  XEmacs was very backward in
2157 this respect (until 2003).
2158
2159 Note that even with newer Emacsen in some very rare cases the details
2160 of interaction of `font-lock' and syntaxification may be not cleaned
2161 up yet.  You may get slightly different colors basing on the order of
2162 fontification and syntaxification.  Say, the initial faces is correct,
2163 but editing the buffer breaks this.
2164
2165 Even with older Emacsen CPerl mode tries to corrects some Emacs
2166 misunderstandings, however, for efficiency reasons the degree of
2167 correction is different for different operations.  The partially
2168 corrected problems are: POD sections, here-documents, regexps.  The
2169 operations are: highlighting, indentation, electric keywords, electric
2170 braces.
2171
2172 This may be confusing, since the regexp s#//#/#\; may be highlighted
2173 as a comment, but it will be recognized as a regexp by the indentation
2174 code.  Or the opposite case, when a POD section is highlighted, but
2175 may break the indentation of the following code (though indentation
2176 should work if the balance of delimiters is not broken by POD).
2177
2178 The main trick (to make $ a \"backslash\") makes constructions like
2179 ${aaa} look like unbalanced braces.  The only trick I can think of is
2180 to insert it as $ {aaa} (legal in perl5, not in perl4).
2181
2182 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
2183 as /($|\\s)/.  Note that such a transposition is not always possible.
2184
2185 The solution is to upgrade your Emacs or patch an older one.  Note
2186 that RMS's 20.2 has some bugs related to `syntax-table' text
2187 properties.  Patches are available on the main CPerl download site,
2188 and on CPAN.
2189
2190 If these bugs cannot be fixed on your machine (say, you have an inferior
2191 environment and cannot recompile), you may still disable all the fancy stuff
2192 via `cperl-use-syntax-table-text-property'.")
2193
2194 (defvar cperl-non-problems 'please-ignore-this-line
2195 "As you know from `problems' section, Perl syntax is too hard for CPerl on
2196 older Emacsen.  Here is what you can do if you cannot upgrade, or if
2197 you want to switch off these capabilities on RMS Emacs 20.2 (+patches) or 20.3
2198 or better.  Please skip this docs if you run a capable Emacs already.
2199
2200 Most of the time, if you write your own code, you may find an equivalent
2201 \(and almost as readable) expression (what is discussed below is usually
2202 not relevant on newer Emacsen, since they can do it automatically).
2203
2204 Try to help CPerl: add comments with embedded quotes to fix CPerl
2205 misunderstandings about the end of quotation:
2206
2207 $a='500$';      # ';
2208
2209 You won't need it too often.  The reason: $ \"quotes\" the following
2210 character (this saves a life a lot of times in CPerl), thus due to
2211 Emacs parsing rules it does not consider tick (i.e., ' ) after a
2212 dollar as a closing one, but as a usual character.  This is usually
2213 correct, but not in the above context.
2214
2215 Even with older Emacsen the indentation code is pretty wise.  The only
2216 drawback is that it relied on Emacs parsing to find matching
2217 parentheses.  And Emacs *could not* match parentheses in Perl 100%
2218 correctly.  So
2219         1 if s#//#/#;
2220 would not break indentation, but
2221         1 if ( s#//#/# );
2222 would.  Upgrade.
2223
2224 By similar reasons
2225         s\"abc\"def\";
2226 could confuse CPerl a lot.
2227
2228 If you still get wrong indentation in situation that you think the
2229 code should be able to parse, try:
2230
2231 a) Check what Emacs thinks about balance of your parentheses.
2232 b) Supply the code to me (IZ).
2233
2234 Pods were treated _very_ rudimentally.  Here-documents were not
2235 treated at all (except highlighting and inhibiting indentation).  Upgrade.
2236
2237 To speed up coloring the following compromises exist:
2238    a) sub in $mypackage::sub may be highlighted.
2239    b) -z in [a-z] may be highlighted.
2240    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
2241
2242
2243 Imenu in 19.31 is broken.  Set `imenu-use-keymap-menu' to t, and remove
2244 `car' before `imenu-choose-buffer-index' in `imenu'.
2245 `imenu-add-to-menubar' in 20.2 is broken.
2246 A lot of things on XEmacs may be broken too, judging by bug reports I
2247 receive.  Note that some releases of XEmacs are better than the others
2248 as far as bugs reports I see are concerned.")
2249
2250 (defvar cperl-praise 'please-ignore-this-line
2251   "Advantages of CPerl mode.
2252
2253 0) It uses the newest `syntax-table' property ;-);
2254
2255 1) It does 99% of Perl syntax correct (as opposed to 80-90% in Perl
2256 mode - but the latter number may have improved too in last years) even
2257 with old Emaxen which do not support `syntax-table' property.
2258
2259 When using `syntax-table' property for syntax assist hints, it should
2260 handle 99.995% of lines correct - or somesuch.  It automatically
2261 updates syntax assist hints when you edit your script.
2262
2263 2) It is generally believed to be \"the most user-friendly Emacs
2264 package\" whatever it may mean (I doubt that the people who say similar
2265 things tried _all_ the rest of Emacs ;-), but this was not a lonely
2266 voice);
2267
2268 3) Everything is customizable, one-by-one or in a big sweep;
2269
2270 4) It has many easily-accessable \"tools\":
2271         a) Can run program, check syntax, start debugger;
2272         b) Can lineup vertically \"middles\" of rows, like `=' in
2273                 a  = b;
2274                 cc = d;
2275         c) Can insert spaces where this impoves readability (in one
2276                 interactive sweep over the buffer);
2277         d) Has support for imenu, including:
2278                 1) Separate unordered list of \"interesting places\";
2279                 2) Separate TOC of POD sections;
2280                 3) Separate list of packages;
2281                 4) Hierarchical view of methods in (sub)packages;
2282                 5) and functions (by the full name - with package);
2283         e) Has an interface to INFO docs for Perl; The interface is
2284                 very flexible, including shrink-wrapping of
2285                 documentation buffer/frame;
2286         f) Has a builtin list of one-line explanations for perl constructs.
2287         g) Can show these explanations if you stay long enough at the
2288                 corresponding place (or on demand);
2289         h) Has an enhanced fontification (using 3 or 4 additional faces
2290                 comparing to font-lock - basically, different
2291                 namespaces in Perl have different colors);
2292         i) Can construct TAGS basing on its knowledge of Perl syntax,
2293                 the standard menu has 6 different way to generate
2294                 TAGS (if \"by directory\", .xs files - with C-language
2295                 bindings - are included in the scan);
2296         j) Can build a hierarchical view of classes (via imenu) basing
2297                 on generated TAGS file;
2298         k) Has electric parentheses, electric newlines, uses Abbrev
2299                 for electric logical constructs
2300                         while () {}
2301                 with different styles of expansion (context sensitive
2302                 to be not so bothering).  Electric parentheses behave
2303                 \"as they should\" in a presence of a visible region.
2304         l) Changes msb.el \"on the fly\" to insert a group \"Perl files\";
2305         m) Can convert from
2306                 if (A) { B }
2307            to
2308                 B if A;
2309
2310         n) Highlights (by user-choice) either 3-delimiters constructs
2311            (such as tr/a/b/), or regular expressions and `y/tr';
2312         o) Highlights trailing whitespace;
2313         p) Is able to manipulate Perl Regular Expressions to ease
2314            conversion to a more readable form.
2315         q) Can ispell POD sections and HERE-DOCs.
2316         r) Understands comments and character classes inside regular
2317            expressions; can find matching () and [] in a regular expression.
2318         s) Allows indentation of //x-style regular expressions;
2319         t) Highlights different symbols in regular expressions according
2320            to their function; much less problems with backslashitis;
2321         u) Allows to find regular expressions which contain interpolated parts.
2322
2323 5) The indentation engine was very smart, but most of tricks may be
2324 not needed anymore with the support for `syntax-table' property.  Has
2325 progress indicator for indentation (with `imenu' loaded).
2326
2327 6) Indent-region improves inline-comments as well; also corrects
2328 whitespace *inside* the conditional/loop constructs.
2329
2330 7) Fill-paragraph correctly handles multi-line comments;
2331
2332 8) Can switch to different indentation styles by one command, and restore
2333 the settings present before the switch.
2334
2335 9) When doing indentation of control constructs, may correct
2336 line-breaks/spacing between elements of the construct.
2337
2338 10) Uses a linear-time algorith for indentation of regions (on Emaxen with
2339 capable syntax engines).
2340
2341 11) Syntax-highlight, indentation, sexp-recognition inside regular expressions.
2342 ")
2343
2344 (defvar cperl-speed 'please-ignore-this-line
2345   "This is an incomplete compendium of what is available in other parts
2346 of CPerl documentation.  (Please inform me if I skept anything.)
2347
2348 There is a perception that CPerl is slower than alternatives.  This part
2349 of documentation is designed to overcome this misconception.
2350
2351 *By default* CPerl tries to enable the most comfortable settings.
2352 From most points of view, correctly working package is infinitely more
2353 comfortable than a non-correctly working one, thus by default CPerl
2354 prefers correctness over speed.  Below is the guide how to change
2355 settings if your preferences are different.
2356
2357 A)  Speed of loading the file.  When loading file, CPerl may perform a
2358 scan which indicates places which cannot be parsed by primitive Emacs
2359 syntax-parsing routines, and marks them up so that either
2360
2361     A1) CPerl may work around these deficiencies (for big chunks, mostly
2362         PODs and HERE-documents), or
2363     A2) On capable Emaxen CPerl will use improved syntax-handlings
2364         which reads mark-up hints directly.
2365
2366     The scan in case A2 is much more comprehensive, thus may be slower.
2367
2368     User can disable syntax-engine-helping scan of A2 by setting
2369        `cperl-use-syntax-table-text-property'
2370     variable to nil (if it is set to t).
2371
2372     One can disable the scan altogether (both A1 and A2) by setting
2373        `cperl-pod-here-scan'
2374     to nil.
2375
2376 B) Speed of editing operations.
2377
2378     One can add a (minor) speedup to editing operations by setting
2379        `cperl-use-syntax-table-text-property'
2380     variable to nil (if it is set to t).  This will disable
2381     syntax-engine-helping scan, thus will make many more Perl
2382     constructs be wrongly recognized by CPerl, thus may lead to
2383     wrongly matched parentheses, wrong indentation, etc.
2384
2385     One can unset `cperl-syntaxify-unwind'.  This might speed up editing
2386     of, say, long POD sections.")
2387
2388 (defvar cperl-tips-faces 'please-ignore-this-line
2389   "CPerl mode uses following faces for highlighting:
2390
2391   `cperl-array-face'            Array names
2392   `cperl-hash-face'             Hash names
2393   `font-lock-comment-face'      Comments, PODs and whatever is considered
2394                                 syntaxically to be not code
2395   `font-lock-constant-face'     HERE-doc delimiters, labels, delimiters of
2396                                 2-arg operators s/y/tr/ or of RExen,
2397   `font-lock-warning-face'      Special-cased m// and s//foo/,
2398   `font-lock-function-name-face' _ as a target of a file tests, file tests,
2399                                 subroutine names at the moment of definition
2400                                 (except those conflicting with Perl operators),
2401                                 package names (when recognized), format names
2402   `font-lock-keyword-face'      Control flow switch constructs, declarators
2403   `cperl-nonoverridable-face'   Non-overridable keywords, modifiers of RExen
2404   `font-lock-string-face'       Strings, qw() constructs, RExen, POD sections,
2405                                 literal parts and the terminator of formats
2406                                 and whatever is syntaxically considered
2407                                 as string literals
2408   `font-lock-type-face'         Overridable keywords
2409   `font-lock-variable-name-face' Variable declarations, indirect array and
2410                                 hash names, POD headers/item names
2411   `cperl-invalid-face'          Trailing whitespace
2412
2413 Note that in several situations the highlighting tries to inform about
2414 possible confusion, such as different colors for function names in
2415 declarations depending on what they (do not) override, or special cases
2416 m// and s/// which do not do what one would expect them to do.
2417
2418 Help with best setup of these faces for printout requested (for each of
2419 the faces: please specify bold, italic, underline, shadow and box.)
2420
2421 In regular expressions (except character classes):
2422   `font-lock-string-face'       \"Normal\" stuff and non-0-length constructs
2423   `font-lock-constant-face':    Delimiters
2424   `font-lock-warning-face'      Special-cased m// and s//foo/,
2425                                 Mismatched closing delimiters, parens
2426                                 we couldn't match, misplaced quantifiers,
2427                                 unrecognized escape sequences
2428   `cperl-nonoverridable-face'   Modifiers, as gism in m/REx/gism
2429   `font-lock-type-face'         POSIX classes inside charclasses,
2430                                 escape sequences with arguments (\x \23 \p \N)
2431                                 and others match-a-char escape sequences
2432   `font-lock-keyword-face'      Capturing parens, and |
2433   `font-lock-function-name-face' Special symbols: $ ^ . [ ] [^ ] (?{ }) (??{ })
2434   `font-lock-builtin-face'      \"Remaining\" 0-length constructs, executable
2435                                 parts of a REx, not-capturing parens
2436   `font-lock-variable-name-face' Interpolated constructs, embedded code
2437   `font-lock-comment-face'      Embedded comments
2438
2439 ")
2440
2441 \f
2442
2443 ;;; Portability stuff:
2444
2445 (defmacro cperl-define-key (emacs-key definition &optional xemacs-key)
2446   (` (define-key cperl-mode-map
2447        (, (if xemacs-key
2448               (` (if cperl-xemacs-p (, xemacs-key) (, emacs-key)))
2449             emacs-key))
2450        (, definition))))
2451
2452 (defvar cperl-del-back-ch
2453   (car (append (where-is-internal 'delete-backward-char)
2454                (where-is-internal 'backward-delete-char-untabify)))
2455   "Character generated by key bound to `delete-backward-char'.")
2456
2457 (and (vectorp cperl-del-back-ch) (= (length cperl-del-back-ch) 1)
2458      (setq cperl-del-back-ch (aref cperl-del-back-ch 0)))
2459
2460 (defun cperl-mark-active () (mark))     ; Avoid undefined warning
2461 (if cperl-xemacs-p
2462     (progn
2463       ;; "Active regions" are on: use region only if active
2464       ;; "Active regions" are off: use region unconditionally
2465       (defun cperl-use-region-p ()
2466         (if zmacs-regions (mark) t)))
2467   (defun cperl-use-region-p ()
2468     (if transient-mark-mode mark-active t))
2469   (defun cperl-mark-active () mark-active))
2470
2471 (defsubst cperl-enable-font-lock ()
2472   cperl-can-font-lock)
2473
2474 (defun cperl-putback-char (c)           ; Emacs 19
2475   (set 'unread-command-events (list c))) ; Avoid undefined warning
2476
2477 (if (boundp 'unread-command-events)
2478     (if cperl-xemacs-p
2479         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
2480           (setq unread-command-events (list (eval '(character-to-event c))))))
2481   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
2482     (set 'unread-command-event (eval '(character-to-event c))))) ; Avoid warnings
2483
2484 (or (fboundp 'uncomment-region)
2485     (defun uncomment-region (beg end)
2486       (interactive "r")
2487       (comment-region beg end -1)))
2488
2489 (defvar cperl-do-not-fontify
2490   (if (string< emacs-version "19.30")
2491       'fontified
2492     'lazy-lock)
2493   "Text property which inhibits refontification.")
2494
2495 (defsubst cperl-put-do-not-fontify (from to &optional post)
2496   ;; If POST, do not do it with postponed fontification
2497   (if (and post cperl-syntaxify-by-font-lock)
2498       nil
2499     (put-text-property (max (point-min) (1- from))
2500                        to cperl-do-not-fontify t)))
2501
2502 (defcustom cperl-mode-hook nil
2503   "Hook run by CPerl mode."
2504   :type 'hook
2505   :group 'cperl)
2506
2507 (defvar cperl-syntax-state nil)
2508 (defvar cperl-syntax-done-to nil)
2509 (defvar cperl-emacs-can-parse (> (length (save-excursion
2510                                            (parse-partial-sexp (point) (point)))) 9))
2511 \f
2512 ;; Make customization possible "in reverse"
2513 (defsubst cperl-val (symbol &optional default hairy)
2514   (cond
2515    ((eq (symbol-value symbol) 'null) default)
2516    (cperl-hairy (or hairy t))
2517    (t (symbol-value symbol))))
2518 \f
2519
2520 (defun cperl-make-indent (column &optional minimum keep)
2521   "Makes indent of the current line the requested amount.
2522 If ANEW, removes the old indentation.  Works around a bug in ancient
2523 versions of Emacs."
2524   (let ((prop (get-text-property (point) 'syntax-type)))
2525     (or keep
2526         (delete-horizontal-space))
2527     (indent-to column minimum)
2528     ;; In old versions (e.g., 19.33) `indent-to' would not inherit properties
2529     (and prop
2530          (> (current-column) 0)
2531          (save-excursion
2532            (beginning-of-line)
2533            (or (get-text-property (point) 'syntax-type)
2534                (and (looking-at "\\=[ \t]")
2535                       (put-text-property (point) (match-end 0)
2536                                          'syntax-type prop)))))))
2537
2538 ;;; Probably it is too late to set these guys already, but it can help later:
2539
2540 (and cperl-clobber-mode-lists
2541      (setq auto-mode-alist
2542       (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
2543      (and (boundp 'interpreter-mode-alist)
2544           (setq interpreter-mode-alist (append interpreter-mode-alist
2545                                                '(("miniperl" . perl-mode))))))
2546 (if (fboundp 'eval-when-compile)
2547     (eval-when-compile
2548       (mapcar (lambda (p)
2549                 (condition-case nil
2550                     (require p)
2551                   (error nil)))
2552               '(imenu easymenu etags timer man info))
2553       (if (fboundp 'ps-extend-face-list)
2554           (defmacro cperl-ps-extend-face-list (arg)
2555             (` (ps-extend-face-list (, arg))))
2556         (defmacro cperl-ps-extend-face-list (arg)
2557           (` (error "This version of Emacs has no `ps-extend-face-list'"))))
2558       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
2559       ;; macros instead of defsubsts don't work on Emacs, so we do the
2560       ;; expansion manually.  Any other suggestions?
2561       (if cperl-can-font-lock
2562           (require 'font-lock))
2563       (require 'cl)))
2564
2565 (defvar cperl-mode-abbrev-table nil
2566   "Abbrev table in use in CPerl mode buffers.")
2567
2568 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
2569
2570 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
2571
2572 (if cperl-mode-map nil
2573   (setq cperl-mode-map (make-sparse-keymap))
2574   (cperl-define-key "{" 'cperl-electric-lbrace)
2575   (cperl-define-key "[" 'cperl-electric-paren)
2576   (cperl-define-key "(" 'cperl-electric-paren)
2577   (cperl-define-key "<" 'cperl-electric-paren)
2578   (cperl-define-key "}" 'cperl-electric-brace)
2579   (cperl-define-key "]" 'cperl-electric-rparen)
2580   (cperl-define-key ")" 'cperl-electric-rparen)
2581   (cperl-define-key ";" 'cperl-electric-semi)
2582   (cperl-define-key ":" 'cperl-electric-terminator)
2583   (cperl-define-key "\C-j" 'newline-and-indent)
2584   (cperl-define-key "\C-c\C-j" 'cperl-linefeed)
2585   (cperl-define-key "\C-c\C-t" 'cperl-invert-if-unless)
2586   (cperl-define-key "\C-c\C-a" 'cperl-toggle-auto-newline)
2587   (cperl-define-key "\C-c\C-k" 'cperl-toggle-abbrev)
2588   (cperl-define-key "\C-c\C-w" 'cperl-toggle-construct-fix)
2589   (cperl-define-key "\C-c\C-f" 'auto-fill-mode)
2590   (cperl-define-key "\C-c\C-e" 'cperl-toggle-electric)
2591   (cperl-define-key "\C-c\C-b" 'cperl-find-bad-style)
2592   (cperl-define-key "\C-c\C-p" 'cperl-pod-spell)
2593   (cperl-define-key "\C-c\C-d" 'cperl-here-doc-spell)
2594   (cperl-define-key "\C-c\C-n" 'cperl-narrow-to-here-doc)
2595   (cperl-define-key "\C-c\C-v" 'cperl-next-interpolated-REx)
2596   (cperl-define-key "\C-c\C-x" 'cperl-next-interpolated-REx-0)
2597   (cperl-define-key "\C-c\C-y" 'cperl-next-interpolated-REx-1)
2598   (cperl-define-key "\C-c\C-ha" 'cperl-toggle-autohelp)
2599   (cperl-define-key "\C-c\C-hp" 'cperl-perldoc)
2600   (cperl-define-key "\C-c\C-hP" 'cperl-perldoc-at-point)
2601   (cperl-define-key "\e\C-q" 'cperl-indent-exp) ; Usually not bound
2602   (cperl-define-key [?\C-\M-\|] 'cperl-lineup
2603                     [(control meta |)])
2604   ;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
2605   ;;(cperl-define-key "\e;" 'cperl-indent-for-comment)
2606   (cperl-define-key "\177" 'cperl-electric-backspace)
2607   (cperl-define-key "\t" 'cperl-indent-command)
2608   ;; don't clobber the backspace binding:
2609   (cperl-define-key "\C-c\C-hF" 'cperl-info-on-command
2610                     [(control c) (control h) F])
2611   (if (cperl-val 'cperl-clobber-lisp-bindings)
2612       (progn
2613         (cperl-define-key "\C-hf"
2614                           ;;(concat (char-to-string help-char) "f") ; does not work
2615                           'cperl-info-on-command
2616                           [(control h) f])
2617         (cperl-define-key "\C-hv"
2618                           ;;(concat (char-to-string help-char) "v") ; does not work
2619                           'cperl-get-help
2620                           [(control h) v])
2621         (cperl-define-key "\C-c\C-hf"
2622                           ;;(concat (char-to-string help-char) "f") ; does not work
2623                           (key-binding "\C-hf")
2624                           [(control c) (control h) f])
2625         (cperl-define-key "\C-c\C-hv"
2626                           ;;(concat (char-to-string help-char) "v") ; does not work
2627                           (key-binding "\C-hv")
2628                           [(control c) (control h) v]))
2629     (cperl-define-key "\C-c\C-hf" 'cperl-info-on-current-command
2630                       [(control c) (control h) f])
2631     (cperl-define-key "\C-c\C-hv"
2632                       ;;(concat (char-to-string help-char) "v") ; does not work
2633                       'cperl-get-help
2634                       [(control c) (control h) v]))
2635   (if (and cperl-xemacs-p
2636            (<= emacs-minor-version 11) (<= emacs-major-version 19))
2637       (progn
2638         ;; substitute-key-definition is usefulness-deenhanced...
2639         ;;;;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
2640         (cperl-define-key "\e;" 'cperl-indent-for-comment)
2641         (cperl-define-key "\e\C-\\" 'cperl-indent-region))
2642     (or (boundp 'fill-paragraph-function)
2643         (substitute-key-definition
2644          'fill-paragraph 'cperl-fill-paragraph
2645          cperl-mode-map global-map))
2646     (substitute-key-definition
2647      'indent-sexp 'cperl-indent-exp
2648      cperl-mode-map global-map)
2649     (substitute-key-definition
2650      'indent-region 'cperl-indent-region
2651      cperl-mode-map global-map)
2652     (substitute-key-definition
2653      'indent-for-comment 'cperl-indent-for-comment
2654      cperl-mode-map global-map)))
2655
2656 (defvar cperl-menu)
2657 (defvar cperl-lazy-installed)
2658 (defvar cperl-old-style nil)
2659 (condition-case nil
2660     (progn
2661       (require 'easymenu)
2662       (easy-menu-define
2663        cperl-menu cperl-mode-map "Menu for CPerl mode"
2664        '("Perl"
2665          ["Beginning of function" beginning-of-defun t]
2666          ["End of function" end-of-defun t]
2667          ["Mark function" mark-defun t]
2668          ["Indent expression" cperl-indent-exp t]
2669          ["Fill paragraph/comment" cperl-fill-paragraph t]
2670          "----"
2671          ["Line up a construction" cperl-lineup (cperl-use-region-p)]
2672          ["Invert if/unless/while etc" cperl-invert-if-unless t]
2673          ("Regexp"
2674           ["Beautify" cperl-beautify-regexp
2675            cperl-use-syntax-table-text-property]
2676           ["Beautify one level deep" (cperl-beautify-regexp 1)
2677            cperl-use-syntax-table-text-property]
2678           ["Beautify a group" cperl-beautify-level
2679            cperl-use-syntax-table-text-property]
2680           ["Beautify a group one level deep" (cperl-beautify-level 1)
2681            cperl-use-syntax-table-text-property]
2682           ["Contract a group" cperl-contract-level
2683            cperl-use-syntax-table-text-property]
2684           ["Contract groups" cperl-contract-levels
2685            cperl-use-syntax-table-text-property]
2686           "----"
2687           ["Find next interpolated" cperl-next-interpolated-REx 
2688            (next-single-property-change (point-min) 'REx-interpolated)]
2689           ["Find next interpolated (no //o)"
2690            cperl-next-interpolated-REx-0
2691            (or (text-property-any (point-min) (point-max) 'REx-interpolated t)
2692                (text-property-any (point-min) (point-max) 'REx-interpolated 1))]
2693           ["Find next interpolated (neither //o nor whole-REx)"
2694            cperl-next-interpolated-REx-1
2695            (text-property-any (point-min) (point-max) 'REx-interpolated t)])
2696          ["Insert spaces if needed to fix style" cperl-find-bad-style t]
2697          ["Refresh \"hard\" constructions" cperl-find-pods-heres t]
2698          "----"
2699          ["Indent region" cperl-indent-region (cperl-use-region-p)]
2700          ["Comment region" cperl-comment-region (cperl-use-region-p)]
2701          ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
2702          "----"
2703          ["Run" mode-compile (fboundp 'mode-compile)]
2704          ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
2705                                         (get-buffer "*compilation*"))]
2706          ["Next error" next-error (get-buffer "*compilation*")]
2707          ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
2708          "----"
2709          ["Debugger" cperl-db t]
2710          "----"
2711          ("Tools"
2712           ["Imenu" imenu (fboundp 'imenu)]
2713           ["Imenu on Perl Info" cperl-imenu-on-info (featurep 'imenu)]
2714           "----"
2715           ["Ispell PODs" cperl-pod-spell
2716            ;; Better not to update syntaxification here:
2717            ;; debugging syntaxificatio can be broken by this???
2718            (or
2719             (get-text-property (point-min) 'in-pod)
2720             (< (progn
2721                  (and cperl-syntaxify-for-menu
2722                       (cperl-update-syntaxification (point-max) (point-max)))
2723                  (next-single-property-change (point-min) 'in-pod nil (point-max)))
2724                (point-max)))]
2725           ["Ispell HERE-DOCs" cperl-here-doc-spell
2726            (< (progn
2727                 (and cperl-syntaxify-for-menu
2728                      (cperl-update-syntaxification (point-max) (point-max)))
2729                 (next-single-property-change (point-min) 'here-doc-group nil (point-max)))
2730               (point-max))]
2731           ["Narrow to this HERE-DOC" cperl-narrow-to-here-doc
2732            (eq 'here-doc  (progn
2733                 (and cperl-syntaxify-for-menu
2734                      (cperl-update-syntaxification (point) (point)))
2735                 (get-text-property (point) 'syntax-type)))]
2736           ["Select this HERE-DOC or POD section"
2737            cperl-select-this-pod-or-here-doc
2738            (memq (progn
2739                    (and cperl-syntaxify-for-menu
2740                         (cperl-update-syntaxification (point) (point)))
2741                    (get-text-property (point) 'syntax-type))
2742                  '(here-doc pod))]
2743           "----"
2744           ["CPerl pretty print (exprmntl)" cperl-ps-print
2745            (fboundp 'ps-extend-face-list)]
2746           "----"
2747           ["Syntaxify region" cperl-find-pods-heres-region
2748            (cperl-use-region-p)]
2749           ["Profile syntaxification" cperl-time-fontification t]
2750           ["Debug errors in delayed fontification" cperl-emulate-lazy-lock t]
2751           ["Debug unwind for syntactic scan" cperl-toggle-set-debug-unwind t]
2752           ["Debug backtrace on syntactic scan (BEWARE!!!)"
2753            (cperl-toggle-set-debug-unwind nil t) t]
2754           "----"
2755           ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
2756           ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
2757           ("Tags"
2758 ;;;          ["Create tags for current file" cperl-etags t]
2759 ;;;          ["Add tags for current file" (cperl-etags t) t]
2760 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
2761 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
2762 ;;;          ["Create tags for Perl files in (sub)directories"
2763 ;;;           (cperl-etags nil 'recursive) t]
2764 ;;;          ["Add tags for Perl files in (sub)directories"
2765 ;;;           (cperl-etags t 'recursive) t])
2766 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
2767            ["Create tags for current file" (cperl-write-tags nil t) t]
2768            ["Add tags for current file" (cperl-write-tags) t]
2769            ["Create tags for Perl files in directory"
2770             (cperl-write-tags nil t nil t) t]
2771            ["Add tags for Perl files in directory"
2772             (cperl-write-tags nil nil nil t) t]
2773            ["Create tags for Perl files in (sub)directories"
2774             (cperl-write-tags nil t t t) t]
2775            ["Add tags for Perl files in (sub)directories"
2776             (cperl-write-tags nil nil t t) t]))
2777          ("Perl docs"
2778           ["Define word at point" imenu-go-find-at-position
2779            (fboundp 'imenu-go-find-at-position)]
2780           ["Help on function" cperl-info-on-command t]
2781           ["Help on function at point" cperl-info-on-current-command t]
2782           ["Help on symbol at point" cperl-get-help t]
2783           ["Perldoc" cperl-perldoc t]
2784           ["Perldoc on word at point" cperl-perldoc-at-point t]
2785           ["View manpage of POD in this file" cperl-build-manpage t]
2786           ["Auto-help on" cperl-lazy-install
2787            (and (fboundp 'run-with-idle-timer)
2788                 (not cperl-lazy-installed))]
2789           ["Auto-help off" cperl-lazy-unstall
2790            (and (fboundp 'run-with-idle-timer)
2791                 cperl-lazy-installed)])
2792          ("Toggle..."
2793           ["Auto newline" cperl-toggle-auto-newline t]
2794           ["Electric parens" cperl-toggle-electric t]
2795           ["Electric keywords" cperl-toggle-abbrev t]
2796           ["Fix whitespace on indent" cperl-toggle-construct-fix t]
2797           ["Auto-help on Perl constructs" cperl-toggle-autohelp t]
2798           ["Auto fill" auto-fill-mode t])
2799          ("Indent styles..."
2800           ["CPerl" (cperl-set-style "CPerl") t]
2801           ["PerlStyle" (cperl-set-style "PerlStyle") t]
2802           ["GNU" (cperl-set-style "GNU") t]
2803           ["C++" (cperl-set-style "C++") t]
2804           ["FSF" (cperl-set-style "FSF") t]
2805           ["BSD" (cperl-set-style "BSD") t]
2806           ["Whitesmith" (cperl-set-style "Whitesmith") t]
2807           ["Current" (cperl-set-style "Current") t]
2808           ["Memorized" (cperl-set-style-back) cperl-old-style])
2809          ("Micro-docs"
2810           ["Tips" (describe-variable 'cperl-tips) t]
2811           ["Problems" (describe-variable 'cperl-problems) t]
2812           ["Non-problems" (describe-variable 'cperl-non-problems) t]
2813           ["Speed" (describe-variable 'cperl-speed) t]
2814           ["Praise" (describe-variable 'cperl-praise) t]
2815           ["Faces" (describe-variable 'cperl-tips-faces) t]
2816           ["CPerl mode" (describe-function 'cperl-mode) t]
2817           ["CPerl version"
2818            (message "The version of master-file for this CPerl is %s"
2819                     cperl-version) t]))))
2820   (error nil))
2821
2822 (autoload 'c-macro-expand "cmacexp"
2823   "Display the result of expanding all C macros occurring in the region.
2824 The expansion is entirely correct because it uses the C preprocessor."
2825   t)
2826
2827 ;;; These two must be unwound, otherwise take exponential time
2828 (defconst cperl-maybe-white-and-comment-rex "[ \t\n]*\\(#[^\n]*\n[ \t\n]*\\)*"
2829 "Regular expression to match optional whitespace with interpspersed comments.
2830 Should contain exactly one group.")
2831
2832 ;;; This one is tricky to unwind; still very inefficient...
2833 (defconst cperl-white-and-comment-rex "\\([ \t\n]\\|#[^\n]*\n\\)+"
2834 "Regular expression to match whitespace with interpspersed comments.
2835 Should contain exactly one group.")
2836
2837
2838 ;;; Is incorporated in `cperl-imenu--function-name-regexp-perl'
2839 ;;; `cperl-outline-regexp', `defun-prompt-regexp'.
2840 ;;; Details of groups in this may be used in several functions; see comments
2841 ;;; near mentioned above variable(s)...
2842 ;;; sub($$):lvalue{}  sub:lvalue{} Both allowed...
2843 (defsubst cperl-after-sub-regexp (named attr) ; 9 groups without attr...
2844   "Match the text after `sub' in a subroutine declaration.
2845 If NAMED is nil, allows anonymous subroutines.  Matches up to the first \":\"
2846 of attributes (if present), or end of the name or prototype (whatever is
2847 the last)."
2848   (concat                               ; Assume n groups before this...
2849    "\\("                                ; n+1=name-group
2850      cperl-white-and-comment-rex        ; n+2=pre-name
2851      "\\(::[a-zA-Z_0-9:']+\\|[a-zA-Z_'][a-zA-Z_0-9:']*\\)" ; n+3=name
2852    "\\)"                                ; END n+1=name-group
2853    (if named "" "?")
2854    "\\("                                ; n+4=proto-group
2855      cperl-maybe-white-and-comment-rex  ; n+5=pre-proto
2856      "\\(([^()]*)\\)"                   ; n+6=prototype
2857    "\\)?"                               ; END n+4=proto-group
2858    "\\("                                ; n+7=attr-group
2859      cperl-maybe-white-and-comment-rex  ; n+8=pre-attr
2860      "\\("                              ; n+9=start-attr
2861         ":"
2862         (if attr (concat
2863                   "\\("
2864                      cperl-maybe-white-and-comment-rex ; whitespace-comments
2865                      "\\(\\sw\\|_\\)+"  ; attr-name
2866                      ;; attr-arg (1 level of internal parens allowed!)
2867                      "\\((\\(\\\\.\\|[^\\\\()]\\|([^\\\\()]*)\\)*)\\)?"
2868                      "\\("              ; optional : (XXX allows trailing???)
2869                         cperl-maybe-white-and-comment-rex ; whitespace-comments
2870                      ":\\)?"
2871                   "\\)+")
2872           "[^:]")
2873      "\\)"
2874    "\\)?"                               ; END n+6=proto-group
2875    ))
2876
2877 ;;; Details of groups in this are used in `cperl-imenu--create-perl-index'
2878 ;;;  and `cperl-outline-level'.
2879 ;;;; Was: 2=sub|package; now 2=package-group, 5=package-name 8=sub-name (+3)
2880 (defvar cperl-imenu--function-name-regexp-perl
2881   (concat
2882    "^\\("                               ; 1 = all
2883        "\\([ \t]*package"               ; 2 = package-group
2884           "\\("                         ; 3 = package-name-group
2885             cperl-white-and-comment-rex ; 4 = pre-package-name
2886                "\\([a-zA-Z_0-9:']+\\)\\)?\\)" ; 5 = package-name
2887        "\\|"
2888           "[ \t]*sub"
2889           (cperl-after-sub-regexp 'named nil) ; 8=name 11=proto 14=attr-start
2890           cperl-maybe-white-and-comment-rex     ; 15=pre-block
2891    "\\|"
2892      "=head\\([1-4]\\)[ \t]+"           ; 16=level
2893      "\\([^\n]+\\)$"                    ; 17=text
2894    "\\)"))
2895
2896 (defvar cperl-outline-regexp
2897   (concat cperl-imenu--function-name-regexp-perl "\\|" "\\`"))
2898
2899 (defvar cperl-mode-syntax-table nil
2900   "Syntax table in use in CPerl mode buffers.")
2901
2902 (defvar cperl-string-syntax-table nil
2903   "Syntax table in use in CPerl mode string-like chunks.")
2904
2905 (defsubst cperl-1- (p)
2906   (max (point-min) (1- p)))
2907
2908 (defsubst cperl-1+ (p)
2909   (min (point-max) (1+ p)))
2910
2911 (if cperl-mode-syntax-table
2912     ()
2913   (setq cperl-mode-syntax-table (make-syntax-table))
2914   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
2915   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
2916   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
2917   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
2918   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
2919   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
2920   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
2921   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
2922   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
2923   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
2924   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
2925   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
2926   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
2927   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
2928   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
2929   (if cperl-under-as-char
2930       (modify-syntax-entry ?_ "w" cperl-mode-syntax-table))
2931   (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
2932   (modify-syntax-entry ?| "." cperl-mode-syntax-table)
2933   (setq cperl-string-syntax-table (copy-syntax-table cperl-mode-syntax-table))
2934   (modify-syntax-entry ?$ "." cperl-string-syntax-table)
2935   (modify-syntax-entry ?\{ "." cperl-string-syntax-table)
2936   (modify-syntax-entry ?\} "." cperl-string-syntax-table)
2937   (modify-syntax-entry ?# "." cperl-string-syntax-table)) ; (?# comment )
2938
2939
2940 \f
2941 ;; provide an alias for working with emacs 19.  the perl-mode that comes
2942 ;; with it is really bad, and this lets us seamlessly replace it.
2943 ;;;###autoload
2944 (fset 'perl-mode 'cperl-mode)
2945 (defvar cperl-faces-init nil)
2946 ;; Fix for msb.el
2947 (defvar cperl-msb-fixed nil)
2948 (defvar font-lock-syntactic-keywords)
2949 (defvar perl-font-lock-keywords)
2950 (defvar perl-font-lock-keywords-1)
2951 (defvar perl-font-lock-keywords-2)
2952 (defvar outline-level)
2953 (if (fboundp 'defvaralias)
2954     (let ((f 'defvaralias)) ; Some functions deduce stuff from the mode name...
2955       (funcall f 'cperl-font-lock-keywords   'perl-font-lock-keywords)
2956       (funcall f 'cperl-font-lock-keywords-1 'perl-font-lock-keywords-1)
2957       (funcall f 'cperl-font-lock-keywords-2 'perl-font-lock-keywords-2)))
2958
2959 (defvar cperl-use-major-mode 'perl-mode)
2960 (defvar cperl-font-lock-multiline-start nil)
2961 (defvar cperl-font-lock-multiline nil)
2962 (defvar cperl-compilation-error-regexp-alist nil)
2963 (defvar cperl-font-locking nil)
2964
2965 ;;;###autoload
2966 (defun cperl-mode ()
2967   "Major mode for editing Perl code.
2968 Expression and list commands understand all C brackets.
2969 Tab indents for Perl code.
2970 Paragraphs are separated by blank lines only.
2971 Delete converts tabs to spaces as it moves back.
2972
2973 Various characters in Perl almost always come in pairs: {}, (), [],
2974 sometimes <>.  When the user types the first, she gets the second as
2975 well, with optional special formatting done on {}.  (Disabled by
2976 default.)  You can always quote (with \\[quoted-insert]) the left
2977 \"paren\" to avoid the expansion.  The processing of < is special,
2978 since most the time you mean \"less\".  CPerl mode tries to guess
2979 whether you want to type pair <>, and inserts is if it
2980 appropriate.  You can set `cperl-electric-parens-string' to the string that
2981 contains the parenths from the above list you want to be electrical.
2982 Electricity of parenths is controlled by `cperl-electric-parens'.
2983 You may also set `cperl-electric-parens-mark' to have electric parens
2984 look for active mark and \"embrace\" a region if possible.'
2985
2986 CPerl mode provides expansion of the Perl control constructs:
2987
2988    if, else, elsif, unless, while, until, continue, do,
2989    for, foreach, formy and foreachmy.
2990
2991 and POD directives (Disabled by default, see `cperl-electric-keywords'.)
2992
2993 The user types the keyword immediately followed by a space, which
2994 causes the construct to be expanded, and the point is positioned where
2995 she is most likely to want to be.  eg. when the user types a space
2996 following \"if\" the following appears in the buffer: if () { or if ()
2997 } { } and the cursor is between the parentheses.  The user can then
2998 type some boolean expression within the parens.  Having done that,
2999 typing \\[cperl-linefeed] places you - appropriately indented - on a
3000 new line between the braces (if you typed \\[cperl-linefeed] in a POD
3001 directive line, then appropriate number of new lines is inserted).
3002
3003 If CPerl decides that you want to insert \"English\" style construct like
3004
3005             bite if angry;
3006
3007 it will not do any expansion.  See also help on variable
3008 `cperl-extra-newline-before-brace'.  (Note that one can switch the
3009 help message on expansion by setting `cperl-message-electric-keyword'
3010 to nil.)
3011
3012 \\[cperl-linefeed] is a convenience replacement for typing carriage
3013 return.  It places you in the next line with proper indentation, or if
3014 you type it inside the inline block of control construct, like
3015
3016             foreach (@lines) {print; print}
3017
3018 and you are on a boundary of a statement inside braces, it will
3019 transform the construct into a multiline and will place you into an
3020 appropriately indented blank line.  If you need a usual
3021 `newline-and-indent' behaviour, it is on \\[newline-and-indent],
3022 see documentation on `cperl-electric-linefeed'.
3023
3024 Use \\[cperl-invert-if-unless] to change a construction of the form
3025
3026             if (A) { B }
3027
3028 into
3029
3030             B if A;
3031
3032 \\{cperl-mode-map}
3033
3034 Setting the variable `cperl-font-lock' to t switches on font-lock-mode
3035 \(even with older Emacsen), `cperl-electric-lbrace-space' to t switches
3036 on electric space between $ and {, `cperl-electric-parens-string' is
3037 the string that contains parentheses that should be electric in CPerl
3038 \(see also `cperl-electric-parens-mark' and `cperl-electric-parens'),
3039 setting `cperl-electric-keywords' enables electric expansion of
3040 control structures in CPerl.  `cperl-electric-linefeed' governs which
3041 one of two linefeed behavior is preferable.  You can enable all these
3042 options simultaneously (recommended mode of use) by setting
3043 `cperl-hairy' to t.  In this case you can switch separate options off
3044 by setting them to `null'.  Note that one may undo the extra
3045 whitespace inserted by semis and braces in `auto-newline'-mode by
3046 consequent \\[cperl-electric-backspace].
3047
3048 If your site has perl5 documentation in info format, you can use commands
3049 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
3050 These keys run commands `cperl-info-on-current-command' and
3051 `cperl-info-on-command', which one is which is controlled by variable
3052 `cperl-info-on-command-no-prompt' and `cperl-clobber-lisp-bindings'
3053 \(in turn affected by `cperl-hairy').
3054
3055 Even if you have no info-format documentation, short one-liner-style
3056 help is available on \\[cperl-get-help], and one can run perldoc or
3057 man via menu.
3058
3059 It is possible to show this help automatically after some idle time.
3060 This is regulated by variable `cperl-lazy-help-time'.  Default with
3061 `cperl-hairy' (if the value of `cperl-lazy-help-time' is nil) is 5
3062 secs idle time .  It is also possible to switch this on/off from the
3063 menu, or via \\[cperl-toggle-autohelp].  Requires `run-with-idle-timer'.
3064
3065 Use \\[cperl-lineup] to vertically lineup some construction - put the
3066 beginning of the region at the start of construction, and make region
3067 span the needed amount of lines.
3068
3069 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
3070 `cperl-pod-face', `cperl-pod-head-face' control processing of POD and
3071 here-docs sections.  With capable Emaxen results of scan are used
3072 for indentation too, otherwise they are used for highlighting only.
3073
3074 Variables controlling indentation style:
3075  `cperl-tab-always-indent'
3076     Non-nil means TAB in CPerl mode should always reindent the current line,
3077     regardless of where in the line point is when the TAB command is used.
3078  `cperl-indent-left-aligned-comments'
3079     Non-nil means that the comment starting in leftmost column should indent.
3080  `cperl-auto-newline'
3081     Non-nil means automatically newline before and after braces,
3082     and after colons and semicolons, inserted in Perl code.  The following
3083     \\[cperl-electric-backspace] will remove the inserted whitespace.
3084     Insertion after colons requires both this variable and
3085     `cperl-auto-newline-after-colon' set.
3086  `cperl-auto-newline-after-colon'
3087     Non-nil means automatically newline even after colons.
3088     Subject to `cperl-auto-newline' setting.
3089  `cperl-indent-level'
3090     Indentation of Perl statements within surrounding block.
3091     The surrounding block's indentation is the indentation
3092     of the line on which the open-brace appears.
3093  `cperl-continued-statement-offset'
3094     Extra indentation given to a substatement, such as the
3095     then-clause of an if, or body of a while, or just a statement continuation.
3096  `cperl-continued-brace-offset'
3097     Extra indentation given to a brace that starts a substatement.
3098     This is in addition to `cperl-continued-statement-offset'.
3099  `cperl-brace-offset'
3100     Extra indentation for line if it starts with an open brace.
3101  `cperl-brace-imaginary-offset'
3102     An open brace following other text is treated as if it the line started
3103     this far to the right of the actual line indentation.
3104  `cperl-label-offset'
3105     Extra indentation for line that is a label.
3106  `cperl-min-label-indent'
3107     Minimal indentation for line that is a label.
3108
3109 Settings for K&R and BSD indentation styles are
3110   `cperl-indent-level'                5    8
3111   `cperl-continued-statement-offset'  5    8
3112   `cperl-brace-offset'               -5   -8
3113   `cperl-label-offset'               -5   -8
3114
3115 CPerl knows several indentation styles, and may bulk set the
3116 corresponding variables.  Use \\[cperl-set-style] to do this.  Use
3117 \\[cperl-set-style-back] to restore the memorized preexisting values
3118 \(both available from menu).
3119
3120 If `cperl-indent-level' is 0, the statement after opening brace in
3121 column 0 is indented on
3122 `cperl-brace-offset'+`cperl-continued-statement-offset'.
3123
3124 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
3125 with no args.
3126
3127 DO NOT FORGET to read micro-docs (available from `Perl' menu)
3128 or as help on variables `cperl-tips', `cperl-problems',
3129 `cperl-non-problems', `cperl-praise', `cperl-speed'."
3130   (interactive)
3131   (kill-all-local-variables)
3132   (use-local-map cperl-mode-map)
3133   (if (cperl-val 'cperl-electric-linefeed)
3134       (progn
3135         (local-set-key "\C-J" 'cperl-linefeed)
3136         (local-set-key "\C-C\C-J" 'newline-and-indent)))
3137   (if (and
3138        (cperl-val 'cperl-clobber-lisp-bindings)
3139        (cperl-val 'cperl-info-on-command-no-prompt))
3140       (progn
3141         ;; don't clobber the backspace binding:
3142         (cperl-define-key "\C-hf" 'cperl-info-on-current-command [(control h) f])
3143         (cperl-define-key "\C-c\C-hf" 'cperl-info-on-command
3144                           [(control c) (control h) f])))
3145   (setq major-mode cperl-use-major-mode)
3146   (setq mode-name "CPerl")
3147   (if (not cperl-mode-abbrev-table)
3148       (let ((prev-a-c abbrevs-changed))
3149         (define-abbrev-table 'cperl-mode-abbrev-table '(
3150                 ("if" "if" cperl-electric-keyword 0)
3151                 ("elsif" "elsif" cperl-electric-keyword 0)
3152                 ("while" "while" cperl-electric-keyword 0)
3153                 ("until" "until" cperl-electric-keyword 0)
3154                 ("unless" "unless" cperl-electric-keyword 0)
3155                 ("else" "else" cperl-electric-else 0)
3156                 ("continue" "continue" cperl-electric-else 0)
3157                 ("for" "for" cperl-electric-keyword 0)
3158                 ("foreach" "foreach" cperl-electric-keyword 0)
3159                 ("formy" "formy" cperl-electric-keyword 0)
3160                 ("foreachmy" "foreachmy" cperl-electric-keyword 0)
3161                 ("do" "do" cperl-electric-keyword 0)
3162                 ("=pod" "=pod" cperl-electric-pod 0)
3163                 ("=over" "=over" cperl-electric-pod 0)
3164                 ("=head1" "=head1" cperl-electric-pod 0)
3165                 ("=head2" "=head2" cperl-electric-pod 0)
3166                 ("pod" "pod" cperl-electric-pod 0)
3167                 ("over" "over" cperl-electric-pod 0)
3168                 ("head1" "head1" cperl-electric-pod 0)
3169                 ("head2" "head2" cperl-electric-pod 0)))
3170         (setq abbrevs-changed prev-a-c)))
3171   (setq local-abbrev-table cperl-mode-abbrev-table)
3172   (if (cperl-val 'cperl-electric-keywords)
3173       (abbrev-mode 1))
3174   (set-syntax-table cperl-mode-syntax-table)
3175   ;; Until Emacs is multi-threaded, we do not actually need it local:
3176   (make-local-variable 'cperl-font-lock-multiline-start)
3177   (make-local-variable 'cperl-font-locking)
3178   (make-local-variable 'outline-regexp)
3179   ;; (setq outline-regexp imenu-example--function-name-regexp-perl)
3180   (setq outline-regexp cperl-outline-regexp)
3181   (make-local-variable 'outline-level)
3182   (setq outline-level 'cperl-outline-level)
3183   (make-local-variable 'paragraph-start)
3184   (setq paragraph-start (concat "^$\\|" page-delimiter))
3185   (make-local-variable 'paragraph-separate)
3186   (setq paragraph-separate paragraph-start)
3187   (make-local-variable 'paragraph-ignore-fill-prefix)
3188   (setq paragraph-ignore-fill-prefix t)
3189   (if cperl-xemacs-p
3190     (progn
3191       (make-local-variable 'paren-backwards-message)
3192       (set 'paren-backwards-message t)))
3193   (make-local-variable 'indent-line-function)
3194   (setq indent-line-function 'cperl-indent-line)
3195   (make-local-variable 'require-final-newline)
3196   (setq require-final-newline t)
3197   (make-local-variable 'comment-start)
3198   (setq comment-start "# ")
3199   (make-local-variable 'comment-end)
3200   (setq comment-end "")
3201   (make-local-variable 'comment-column)
3202   (setq comment-column cperl-comment-column)
3203   (make-local-variable 'comment-start-skip)
3204   (setq comment-start-skip "#+ *")
3205   (make-local-variable 'defun-prompt-regexp)
3206 ;;;       "[ \t]*sub"
3207 ;;;       (cperl-after-sub-regexp 'named nil) ; 8=name 11=proto 14=attr-start
3208 ;;;       cperl-maybe-white-and-comment-rex     ; 15=pre-block
3209   (setq defun-prompt-regexp
3210         (concat "[ \t]*sub"
3211                 (cperl-after-sub-regexp 'named 'attr-groups)
3212                 cperl-maybe-white-and-comment-rex))
3213   (make-local-variable 'comment-indent-function)
3214   (setq comment-indent-function 'cperl-comment-indent)
3215   (and (boundp 'fill-paragraph-function)
3216       (progn
3217         (make-local-variable 'fill-paragraph-function)
3218         (set 'fill-paragraph-function 'cperl-fill-paragraph)))
3219   (make-local-variable 'parse-sexp-ignore-comments)
3220   (setq parse-sexp-ignore-comments t)
3221   (make-local-variable 'indent-region-function)
3222   (setq indent-region-function 'cperl-indent-region)
3223   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
3224   (make-local-variable 'imenu-create-index-function)
3225   (setq imenu-create-index-function
3226         (function cperl-imenu--create-perl-index))
3227   (make-local-variable 'imenu-sort-function)
3228   (setq imenu-sort-function nil)
3229   (make-local-variable 'vc-rcs-header)
3230   (set 'vc-rcs-header cperl-vc-rcs-header)
3231   (make-local-variable 'vc-sccs-header)
3232   (set 'vc-sccs-header cperl-vc-sccs-header)
3233   ;; This one is obsolete...
3234   (make-local-variable 'vc-header-alist)
3235   (set 'vc-header-alist (or cperl-vc-header-alist ; Avoid warning
3236                             (` ((SCCS (, (car cperl-vc-sccs-header)))
3237                                      (RCS (, (car cperl-vc-rcs-header)))))))
3238   (cond ((boundp 'compilation-error-regexp-alist-alist);; xemacs 20.x
3239          (make-local-variable 'compilation-error-regexp-alist-alist)
3240          (set 'compilation-error-regexp-alist-alist
3241               (cons (cons 'cperl cperl-compilation-error-regexp-alist)
3242                     (symbol-value 'compilation-error-regexp-alist-alist)))
3243          (let ((f 'compilation-build-compilation-error-regexp-alist))
3244            (funcall f)))
3245         ((boundp 'compilation-error-regexp-alist);; xmeacs 19.x
3246          (make-local-variable 'compilation-error-regexp-alist)
3247          (set 'compilation-error-regexp-alist
3248                (cons cperl-compilation-error-regexp-alist
3249                      (symbol-value 'compilation-error-regexp-alist)))))
3250   (make-local-variable 'font-lock-defaults)
3251   (setq font-lock-defaults
3252         (cond
3253          ((string< emacs-version "19.30")
3254           '(perl-font-lock-keywords-2 nil nil ((?_ . "w"))))
3255          ((string< emacs-version "19.33") ; Which one to use?
3256           '((perl-font-lock-keywords
3257              perl-font-lock-keywords-1
3258              perl-font-lock-keywords-2) nil nil ((?_ . "w"))))
3259          (t
3260           '((cperl-load-font-lock-keywords
3261              cperl-load-font-lock-keywords-1
3262              cperl-load-font-lock-keywords-2) nil nil ((?_ . "w"))))))
3263   (make-local-variable 'cperl-syntax-state)
3264   (setq cperl-syntax-state nil)         ; reset syntaxification cache
3265   (if cperl-use-syntax-table-text-property
3266       (progn
3267         (make-local-variable 'parse-sexp-lookup-properties)
3268         ;; Do not introduce variable if not needed, we check it!
3269         (set 'parse-sexp-lookup-properties t)
3270         ;; Fix broken font-lock:
3271         (or (boundp 'font-lock-unfontify-region-function)
3272             (set 'font-lock-unfontify-region-function
3273                  'font-lock-default-unfontify-region))
3274         (unless cperl-xemacs-p          ; Our: just a plug for wrong font-lock
3275           (make-local-variable 'font-lock-unfontify-region-function)
3276           (set 'font-lock-unfontify-region-function ; not present with old Emacs
3277                'cperl-font-lock-unfontify-region-function))
3278         (make-local-variable 'cperl-syntax-done-to)
3279         (setq cperl-syntax-done-to nil) ; reset syntaxification cache
3280         ;; Another bug: unless font-lock-syntactic-keywords, font-lock
3281         ;;  ignores syntax-table text-property.  (t) is a hack
3282         ;;  to make font-lock think that font-lock-syntactic-keywords
3283         ;;  are defined
3284         (make-local-variable 'font-lock-syntactic-keywords)
3285         (setq font-lock-syntactic-keywords
3286               (if cperl-syntaxify-by-font-lock
3287                   '(t (cperl-fontify-syntaxically))
3288                 '(t)))))
3289   (if (boundp 'font-lock-multiline)     ; Newer font-lock; use its facilities
3290       (progn
3291         (setq cperl-font-lock-multiline t) ; Not localized...
3292         (set 'font-lock-multiline t)) ; not present with old Emacs; auto-local
3293     (make-local-variable 'font-lock-fontify-region-function)
3294     (set 'font-lock-fontify-region-function ; not present with old Emacs
3295          'cperl-font-lock-fontify-region-function))
3296   (make-local-variable 'font-lock-fontify-region-function)
3297   (set 'font-lock-fontify-region-function ; not present with old Emacs
3298        'cperl-font-lock-fontify-region-function)
3299   (make-local-variable 'cperl-old-style)
3300   (if (boundp 'normal-auto-fill-function) ; 19.33 and later
3301       (set (make-local-variable 'normal-auto-fill-function)
3302            'cperl-do-auto-fill)       ; RMS has it as #'cperl-do-auto-fill ???
3303     (or (fboundp 'cperl-old-auto-fill-mode)
3304         (progn
3305           (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
3306           (defun auto-fill-mode (&optional arg)
3307             (interactive "P")
3308             (eval '(cperl-old-auto-fill-mode arg)) ; Avoid a warning
3309             (and auto-fill-function (memq major-mode '(perl-mode cperl-mode))
3310                  (setq auto-fill-function 'cperl-do-auto-fill))))))
3311   (if (cperl-enable-font-lock)
3312       (if (cperl-val 'cperl-font-lock)
3313           (progn (or cperl-faces-init (cperl-init-faces))
3314                  (font-lock-mode 1))))
3315   (set (make-local-variable 'facemenu-add-face-function)
3316        'cperl-facemenu-add-face-function) ; XXXX What this guy is for???
3317   (and (boundp 'msb-menu-cond)
3318        (not cperl-msb-fixed)
3319        (cperl-msb-fix))
3320   (if (featurep 'easymenu)
3321       (easy-menu-add cperl-menu))       ; A NOP in RMS Emacs.
3322   (run-hooks 'cperl-mode-hook)
3323   (if cperl-hook-after-change
3324       (progn
3325         (make-local-hook 'after-change-functions)
3326         (add-hook 'after-change-functions 'cperl-after-change-function nil t)))
3327   ;; After hooks since fontification will break this
3328   (if cperl-pod-here-scan
3329       (or cperl-syntaxify-by-font-lock
3330        (progn (or cperl-faces-init (cperl-init-faces-weak))
3331               (cperl-find-pods-heres)))))
3332 \f
3333 ;; Fix for perldb - make default reasonable
3334 (defun cperl-db ()
3335   (interactive)
3336   (require 'gud)
3337   (perldb (read-from-minibuffer "Run perldb (like this): "
3338                                 (if (consp gud-perldb-history)
3339                                     (car gud-perldb-history)
3340                                   (concat "perl " ;;(file-name-nondirectory
3341                                           ;; I have problems
3342                                           ;; in OS/2
3343                                           ;; otherwise
3344                                           (buffer-file-name)))
3345                                 nil nil
3346                                 '(gud-perldb-history . 1))))
3347 \f
3348 (defun cperl-msb-fix ()
3349   ;; Adds perl files to msb menu, supposes that msb is already loaded
3350   (setq cperl-msb-fixed t)
3351   (let* ((l (length msb-menu-cond))
3352          (last (nth (1- l) msb-menu-cond))
3353          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
3354          (handle (1- (nth 1 last))))
3355     (setcdr precdr (list
3356                     (list
3357                      '(memq major-mode '(cperl-mode perl-mode))
3358                      handle
3359                      "Perl Files (%d)")
3360                     last))))
3361 \f
3362 ;; This is used by indent-for-comment
3363 ;; to decide how much to indent a comment in CPerl code
3364 ;; based on its context.  Do fallback if comment is found wrong.
3365
3366 (defvar cperl-wrong-comment)
3367 (defvar cperl-st-cfence '(14))          ; Comment-fence
3368 (defvar cperl-st-sfence '(15))          ; String-fence
3369 (defvar cperl-st-punct '(1))
3370 (defvar cperl-st-word '(2))
3371 (defvar cperl-st-bra '(4 . ?\>))
3372 (defvar cperl-st-ket '(5 . ?\<))
3373
3374
3375 (defun cperl-comment-indent ()
3376   (let ((p (point)) (c (current-column)) was phony)
3377     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
3378       ;; Wrong comment found
3379       (save-excursion
3380         (setq was (cperl-to-comment-or-eol)
3381               phony (eq (get-text-property (point) 'syntax-table)
3382                         cperl-st-cfence))
3383         (if phony
3384             (progn
3385               (re-search-forward "#\\|$") ; Hmm, what about embedded #?
3386               (if (eq (preceding-char) ?\#)
3387                   (forward-char -1))
3388               (setq was nil)))
3389         (if (= (point) p)
3390             (progn
3391               (skip-chars-backward " \t")
3392               (max (1+ (current-column)) ; Else indent at comment column
3393                    comment-column))
3394           (if was nil
3395             (insert comment-start)
3396             (backward-char (length comment-start)))
3397           (setq cperl-wrong-comment t)
3398           (cperl-make-indent comment-column 1 'keep)    ; Indent minimum 1
3399           c)))))                        ; except leave at least one space.
3400
3401 ;;;(defun cperl-comment-indent-fallback ()
3402 ;;;  "Is called if the standard comment-search procedure fails.
3403 ;;;Point is at start of real comment."
3404 ;;;  (let ((c (current-column)) target cnt prevc)
3405 ;;;    (if (= c comment-column) nil
3406 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
3407 ;;;      (setq target (max (1+ (setq prevc
3408 ;;;                          (current-column))) ; Else indent at comment column
3409 ;;;                comment-column))
3410 ;;;      (if (= c comment-column) nil
3411 ;;;     (delete-backward-char cnt)
3412 ;;;     (while (< prevc target)
3413 ;;;       (insert "\t")
3414 ;;;       (setq prevc (current-column)))
3415 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
3416 ;;;     (while (< prevc target)
3417 ;;;       (insert " ")
3418 ;;;       (setq prevc (current-column)))))))
3419
3420 (defun cperl-indent-for-comment ()
3421   "Substitute for `indent-for-comment' in CPerl."
3422   (interactive)
3423   (let (cperl-wrong-comment)
3424     (indent-for-comment)
3425     (if cperl-wrong-comment             ; set by `cperl-comment-indent'
3426         (progn (cperl-to-comment-or-eol)
3427                (forward-char (length comment-start))))))
3428
3429 (defun cperl-comment-region (b e arg)
3430   "Comment or uncomment each line in the region in CPerl mode.
3431 See `comment-region'."
3432   (interactive "r\np")
3433   (let ((comment-start "#"))
3434     (comment-region b e arg)))
3435
3436 (defun cperl-uncomment-region (b e arg)
3437   "Uncomment or comment each line in the region in CPerl mode.
3438 See `comment-region'."
3439   (interactive "r\np")
3440   (let ((comment-start "#"))
3441     (comment-region b e (- arg))))
3442
3443 (defvar cperl-brace-recursing nil)
3444
3445 (defun cperl-electric-brace (arg &optional only-before)
3446   "Insert character and correct line's indentation.
3447 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
3448 place (even in empty line), but not after.  If after \")\" and the inserted
3449 char is \"{\", insert extra newline before only if
3450 `cperl-extra-newline-before-brace'."
3451   (interactive "P")
3452   (let (insertpos
3453         (other-end (if (and cperl-electric-parens-mark
3454                             (cperl-mark-active)
3455                             (< (mark) (point)))
3456                        (mark)
3457                      nil)))
3458     (if (and other-end
3459              (not cperl-brace-recursing)
3460              (cperl-val 'cperl-electric-parens)
3461              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point)))
3462         ;; Need to insert a matching pair
3463         (progn
3464           (save-excursion
3465             (setq insertpos (point-marker))
3466             (goto-char other-end)
3467             (setq last-command-char ?\{)
3468             (cperl-electric-lbrace arg insertpos))
3469           (forward-char 1))
3470       ;; Check whether we close something "usual" with `}'
3471       (if (and (eq last-command-char ?\})
3472                (not
3473                 (condition-case nil
3474                     (save-excursion
3475                       (up-list (- (prefix-numeric-value arg)))
3476                       ;;(cperl-after-block-p (point-min))
3477                       (or (cperl-after-expr-p nil "{;)")
3478                           ;; after sub, else, continue
3479                           (cperl-after-block-p nil 'pre)))
3480                   (error nil))))
3481           ;; Just insert the guy
3482           (self-insert-command (prefix-numeric-value arg))
3483         (if (and (not arg)              ; No args, end (of empty line or auto)
3484                  (eolp)
3485                  (or (and (null only-before)
3486                           (save-excursion
3487                             (skip-chars-backward " \t")
3488                             (bolp)))
3489                      (and (eq last-command-char ?\{) ; Do not insert newline
3490                           ;; if after ")" and `cperl-extra-newline-before-brace'
3491                           ;; is nil, do not insert extra newline.
3492                           (not cperl-extra-newline-before-brace)
3493                           (save-excursion
3494                             (skip-chars-backward " \t")
3495                             (eq (preceding-char) ?\))))
3496                      (if cperl-auto-newline
3497                          (progn (cperl-indent-line) (newline) t) nil)))
3498             (progn
3499               (self-insert-command (prefix-numeric-value arg))
3500               (cperl-indent-line)
3501               (if cperl-auto-newline
3502                   (setq insertpos (1- (point))))
3503               (if (and cperl-auto-newline (null only-before))
3504                   (progn
3505                     (newline)
3506                     (cperl-indent-line)))
3507               (save-excursion
3508                 (if insertpos (progn (goto-char insertpos)
3509                                      (search-forward (make-string
3510                                                       1 last-command-char))
3511                                      (setq insertpos (1- (point)))))
3512                 (delete-char -1))))
3513         (if insertpos
3514             (save-excursion
3515               (goto-char insertpos)
3516               (self-insert-command (prefix-numeric-value arg)))
3517           (self-insert-command (prefix-numeric-value arg)))))))
3518
3519 (defun cperl-electric-lbrace (arg &optional end)
3520   "Insert character, correct line's indentation, correct quoting by space."
3521   (interactive "P")
3522   (let ((cperl-brace-recursing t)
3523         (cperl-auto-newline cperl-auto-newline)
3524         (other-end (or end
3525                        (if (and cperl-electric-parens-mark
3526                                 (cperl-mark-active)
3527                                 (> (mark) (point)))
3528                            (save-excursion
3529                              (goto-char (mark))
3530                              (point-marker))
3531                          nil)))
3532         pos after)
3533     (and (cperl-val 'cperl-electric-lbrace-space)
3534          (eq (preceding-char) ?$)
3535          (save-excursion
3536            (skip-chars-backward "$")
3537            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
3538          (insert ?\ ))
3539     ;; Check whether we are in comment
3540     (if (and
3541          (save-excursion
3542            (beginning-of-line)
3543            (not (looking-at "[ \t]*#")))
3544          (cperl-after-expr-p nil "{;)"))
3545         nil
3546       (setq cperl-auto-newline nil))
3547     (cperl-electric-brace arg)
3548     (and (cperl-val 'cperl-electric-parens)
3549          (eq last-command-char ?{)
3550          (memq last-command-char
3551                (append cperl-electric-parens-string nil))
3552          (or (if other-end (goto-char (marker-position other-end)))
3553              t)
3554          (setq last-command-char ?} pos (point))
3555          (progn (cperl-electric-brace arg t)
3556                 (goto-char pos)))))
3557
3558 (defun cperl-electric-paren (arg)
3559   "Insert an opening parenthesis or a matching pair of parentheses.
3560 See `cperl-electric-parens'."
3561   (interactive "P")
3562   (let ((beg (save-excursion (beginning-of-line) (point)))
3563         (other-end (if (and cperl-electric-parens-mark
3564                             (cperl-mark-active)
3565                             (> (mark) (point)))
3566                        (save-excursion
3567                          (goto-char (mark))
3568                          (point-marker))
3569                      nil)))
3570     (if (and (cperl-val 'cperl-electric-parens)
3571              (memq last-command-char
3572                    (append cperl-electric-parens-string nil))
3573              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
3574              ;;(not (save-excursion (search-backward "#" beg t)))
3575              (if (eq last-command-char ?<)
3576                  (progn
3577                    (and abbrev-mode ; later it is too late, may be after `for'
3578                         (expand-abbrev))
3579                    (cperl-after-expr-p nil "{;(,:="))
3580                1))
3581         (progn
3582           (self-insert-command (prefix-numeric-value arg))
3583           (if other-end (goto-char (marker-position other-end)))
3584           (insert (make-string
3585                    (prefix-numeric-value arg)
3586                    (cdr (assoc last-command-char '((?{ .?})
3587                                                    (?[ . ?])
3588                                                    (?( . ?))
3589                                                    (?< . ?>))))))
3590           (forward-char (- (prefix-numeric-value arg))))
3591       (self-insert-command (prefix-numeric-value arg)))))
3592
3593 (defun cperl-electric-rparen (arg)
3594   "Insert a matching pair of parentheses if marking is active.
3595 If not, or if we are not at the end of marking range, would self-insert.
3596 Affected by `cperl-electric-parens'."
3597   (interactive "P")
3598   (let ((beg (save-excursion (beginning-of-line) (point)))
3599         (other-end (if (and cperl-electric-parens-mark
3600                             (cperl-val 'cperl-electric-parens)
3601                             (memq last-command-char
3602                                   (append cperl-electric-parens-string nil))
3603                             (cperl-mark-active)
3604                             (< (mark) (point)))
3605                        (mark)
3606                      nil))
3607         p)
3608     (if (and other-end
3609              (cperl-val 'cperl-electric-parens)
3610              (memq last-command-char '( ?\) ?\] ?\} ?\> ))
3611              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
3612              ;;(not (save-excursion (search-backward "#" beg t)))
3613              )
3614         (progn
3615           (self-insert-command (prefix-numeric-value arg))
3616           (setq p (point))
3617           (if other-end (goto-char other-end))
3618           (insert (make-string
3619                    (prefix-numeric-value arg)
3620                    (cdr (assoc last-command-char '((?\} . ?\{)
3621                                                    (?\] . ?\[)
3622                                                    (?\) . ?\()
3623                                                    (?\> . ?\<))))))
3624           (goto-char (1+ p)))
3625       (self-insert-command (prefix-numeric-value arg)))))
3626
3627 (defun cperl-electric-keyword ()
3628   "Insert a construction appropriate after a keyword.
3629 Help message may be switched off by setting `cperl-message-electric-keyword'
3630 to nil."
3631   (let ((beg (save-excursion (beginning-of-line) (point)))
3632         (dollar (and (eq last-command-char ?$)
3633                      (eq this-command 'self-insert-command)))
3634         (delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3635                      (memq this-command '(self-insert-command newline))))
3636         my do)
3637     (and (save-excursion
3638            (condition-case nil
3639                (progn
3640                  (backward-sexp 1)
3641                  (setq do (looking-at "do\\>")))
3642              (error nil))
3643            (cperl-after-expr-p nil "{;:"))
3644          (save-excursion
3645            (not
3646             (re-search-backward
3647              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3648              beg t)))
3649          (save-excursion (or (not (re-search-backward "^=" nil t))
3650                              (or
3651                               (looking-at "=cut")
3652                               (and cperl-use-syntax-table-text-property
3653                                    (not (eq (get-text-property (point)
3654                                                                'syntax-type)
3655                                             'pod))))))
3656          (save-excursion (forward-sexp -1)
3657                          (not (memq (following-char) (append "$@%&*" nil))))
3658          (progn
3659            (and (eq (preceding-char) ?y)
3660                 (progn                  ; "foreachmy"
3661                   (forward-char -2)
3662                   (insert " ")
3663                   (forward-char 2)
3664                   (setq my t dollar t
3665                         delete
3666                         (memq this-command '(self-insert-command newline)))))
3667            (and dollar (insert " $"))
3668            (cperl-indent-line)
3669            ;;(insert " () {\n}")
3670            (cond
3671             (cperl-extra-newline-before-brace
3672              (insert (if do "\n" " ()\n"))
3673              (insert "{")
3674              (cperl-indent-line)
3675              (insert "\n")
3676              (cperl-indent-line)
3677              (insert "\n}")
3678              (and do (insert " while ();")))
3679             (t
3680              (insert (if do " {\n} while ();" " () {\n}"))))
3681            (or (looking-at "[ \t]\\|$") (insert " "))
3682            (cperl-indent-line)
3683            (if dollar (progn (search-backward "$")
3684                              (if my
3685                                  (forward-char 1)
3686                                (delete-char 1)))
3687              (search-backward ")")
3688              (if (eq last-command-char ?\()
3689                  (progn                 ; Avoid "if (())"
3690                    (delete-backward-char 1)
3691                    (delete-backward-char -1))))
3692            (if delete
3693                (cperl-putback-char cperl-del-back-ch))
3694            (if cperl-message-electric-keyword
3695                (message "Precede char by C-q to avoid expansion"))))))
3696
3697 (defun cperl-ensure-newlines (n &optional pos)
3698   "Make sure there are N newlines after the point."
3699   (or pos (setq pos (point)))
3700   (if (looking-at "\n")
3701       (forward-char 1)
3702     (insert "\n"))
3703   (if (> n 1)
3704       (cperl-ensure-newlines (1- n) pos)
3705     (goto-char pos)))
3706
3707 (defun cperl-electric-pod ()
3708   "Insert a POD chunk appropriate after a =POD directive."
3709   (let ((delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3710                      (memq this-command '(self-insert-command newline))))
3711         head1 notlast name p really-delete over)
3712     (and (save-excursion
3713            (forward-word -1)
3714            (and
3715             (eq (preceding-char) ?=)
3716             (progn
3717               (setq head1 (looking-at "head1\\>[ \t]*$"))
3718               (setq over (and (looking-at "over\\>[ \t]*$")
3719                               (not (looking-at "over[ \t]*\n\n\n*=item\\>"))))
3720               (forward-char -1)
3721               (bolp))
3722             (or
3723              (get-text-property (point) 'in-pod)
3724              (cperl-after-expr-p nil "{;:")
3725              (and (re-search-backward "\\(\\`\n?\\|^\n\\)=\\sw+" (point-min) t)
3726                   (not (looking-at "\n*=cut"))
3727                   (or (not cperl-use-syntax-table-text-property)
3728                       (eq (get-text-property (point) 'syntax-type) 'pod))))))
3729          (progn
3730            (save-excursion
3731              (setq notlast (re-search-forward "^\n=" nil t)))
3732            (or notlast
3733                (progn
3734                  (insert "\n\n=cut")
3735                  (cperl-ensure-newlines 2)
3736                  (forward-word -2)
3737                  (if (and head1
3738                           (not
3739                            (save-excursion
3740                              (forward-char -1)
3741                              (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\>"
3742                                                  nil t)))) ; Only one
3743                      (progn
3744                        (forward-word 1)
3745                        (setq name (file-name-sans-extension
3746                                    (file-name-nondirectory (buffer-file-name)))
3747                              p (point))
3748                        (insert " NAME\n\n" name
3749                                " - \n\n=head1 SYNOPSIS\n\n\n\n"
3750                                "=head1 DESCRIPTION")
3751                        (cperl-ensure-newlines 4)
3752                        (goto-char p)
3753                        (forward-word 2)
3754                        (end-of-line)
3755                        (setq really-delete t))
3756                    (forward-word 1))))
3757            (if over
3758                (progn
3759                  (setq p (point))
3760                  (insert "\n\n=item \n\n\n\n"
3761                          "=back")
3762                  (cperl-ensure-newlines 2)
3763                  (goto-char p)
3764                  (forward-word 1)
3765                  (end-of-line)
3766                  (setq really-delete t)))
3767            (if (and delete really-delete)
3768                (cperl-putback-char cperl-del-back-ch))))))
3769
3770 (defun cperl-electric-else ()
3771   "Insert a construction appropriate after a keyword.
3772 Help message may be switched off by setting `cperl-message-electric-keyword'
3773 to nil."
3774   (let ((beg (save-excursion (beginning-of-line) (point))))
3775     (and (save-excursion
3776            (backward-sexp 1)
3777            (cperl-after-expr-p nil "{;:"))
3778          (save-excursion
3779            (not
3780             (re-search-backward
3781              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3782              beg t)))
3783          (save-excursion (or (not (re-search-backward "^=" nil t))
3784                              (looking-at "=cut")
3785                              (and cperl-use-syntax-table-text-property
3786                                   (not (eq (get-text-property (point)
3787                                                               'syntax-type)
3788                                            'pod)))))
3789          (progn
3790            (cperl-indent-line)
3791            ;;(insert " {\n\n}")
3792            (cond
3793             (cperl-extra-newline-before-brace
3794              (insert "\n")
3795              (insert "{")
3796              (cperl-indent-line)
3797              (insert "\n\n}"))
3798             (t
3799              (insert " {\n\n}")))
3800            (or (looking-at "[ \t]\\|$") (insert " "))
3801            (cperl-indent-line)
3802            (forward-line -1)
3803            (cperl-indent-line)
3804            (cperl-putback-char cperl-del-back-ch)
3805            (setq this-command 'cperl-electric-else)
3806            (if cperl-message-electric-keyword
3807                (message "Precede char by C-q to avoid expansion"))))))
3808
3809 (defun cperl-linefeed ()
3810   "Go to end of line, open a new line and indent appropriately.
3811 If in POD, insert appropriate lines."
3812   (interactive)
3813   (let ((beg (save-excursion (beginning-of-line) (point)))
3814         (end (save-excursion (end-of-line) (point)))
3815         (pos (point)) start over cut res)
3816     (if (and                            ; Check if we need to split:
3817                                         ; i.e., on a boundary and inside "{...}"
3818          (save-excursion (cperl-to-comment-or-eol)
3819                          (>= (point) pos)) ; Not in a comment
3820          (or (save-excursion
3821                (skip-chars-backward " \t" beg)
3822                (forward-char -1)
3823                (looking-at "[;{]"))     ; After { or ; + spaces
3824              (looking-at "[ \t]*}")     ; Before }
3825              (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
3826          (save-excursion
3827            (and
3828             (eq (car (parse-partial-sexp pos end -1)) -1)
3829                                         ; Leave the level of parens
3830             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
3831                                         ; Are at end
3832             (cperl-after-block-p (point-min))
3833             (progn
3834               (backward-sexp 1)
3835               (setq start (point-marker))
3836               (<= start pos)))))        ; Redundant?  Are after the
3837                                         ; start of parens group.
3838         (progn
3839           (skip-chars-backward " \t")
3840           (or (memq (preceding-char) (append ";{" nil))
3841               (insert ";"))
3842           (insert "\n")
3843           (forward-line -1)
3844           (cperl-indent-line)
3845           (goto-char start)
3846           (or (looking-at "{[ \t]*$")   ; If there is a statement
3847                                         ; before, move it to separate line
3848               (progn
3849                 (forward-char 1)
3850                 (insert "\n")
3851                 (cperl-indent-line)))
3852           (forward-line 1)              ; We are on the target line
3853           (cperl-indent-line)
3854           (beginning-of-line)
3855           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
3856                                         ; after, move it to separate line
3857               (progn
3858                 (end-of-line)
3859                 (search-backward "}" beg)
3860                 (skip-chars-backward " \t")
3861                 (or (memq (preceding-char) (append ";{" nil))
3862                     (insert ";"))
3863                 (insert "\n")
3864                 (cperl-indent-line)
3865                 (forward-line -1)))
3866           (forward-line -1)             ; We are on the line before target
3867           (end-of-line)
3868           (newline-and-indent))
3869       (end-of-line)                     ; else - no splitting
3870       (cond
3871        ((and (looking-at "\n[ \t]*{$")
3872              (save-excursion
3873                (skip-chars-backward " \t")
3874                (eq (preceding-char) ?\)))) ; Probably if () {} group
3875                                         ; with an extra newline.
3876         (forward-line 2)
3877         (cperl-indent-line))
3878        ((save-excursion                 ; In POD header
3879           (forward-paragraph -1)
3880           ;; (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\b")
3881           ;; We are after \n now, so look for the rest
3882           (if (looking-at "\\(\\`\n?\\|\n\\)=\\sw+")
3883               (progn
3884                 (setq cut (looking-at "\\(\\`\n?\\|\n\\)=cut\\>"))
3885                 (setq over (looking-at "\\(\\`\n?\\|\n\\)=over\\>"))
3886                 t)))
3887         (if (and over
3888                  (progn
3889                    (forward-paragraph -1)
3890                    (forward-word 1)
3891                    (setq pos (point))
3892                    (setq cut (buffer-substring (point)
3893                                                (save-excursion
3894                                                  (end-of-line)
3895                                                  (point))))
3896                    (delete-char (- (save-excursion (end-of-line) (point))
3897                                    (point)))
3898                    (setq res (expand-abbrev))
3899                    (save-excursion
3900                      (goto-char pos)
3901                      (insert cut))
3902                    res))
3903             nil
3904           (cperl-ensure-newlines (if cut 2 4))
3905           (forward-line 2)))
3906        ((get-text-property (point) 'in-pod) ; In POD section
3907         (cperl-ensure-newlines 4)
3908         (forward-line 2))
3909        ((looking-at "\n[ \t]*$")        ; Next line is empty - use it.
3910         (forward-line 1)
3911         (cperl-indent-line))
3912        (t
3913         (newline-and-indent))))))
3914
3915 (defun cperl-electric-semi (arg)
3916   "Insert character and correct line's indentation."
3917   (interactive "P")
3918   (if cperl-auto-newline
3919       (cperl-electric-terminator arg)
3920     (self-insert-command (prefix-numeric-value arg))
3921     (if cperl-autoindent-on-semi
3922         (cperl-indent-line))))
3923
3924 (defun cperl-electric-terminator (arg)
3925   "Insert character and correct line's indentation."
3926   (interactive "P")
3927   (let ((end (point))
3928         (auto (and cperl-auto-newline
3929                    (or (not (eq last-command-char ?:))
3930                        cperl-auto-newline-after-colon)))
3931         insertpos)
3932     (if (and ;;(not arg)
3933              (eolp)
3934              (not (save-excursion
3935                     (beginning-of-line)
3936                     (skip-chars-forward " \t")
3937                     (or
3938                      ;; Ignore in comment lines
3939                      (= (following-char) ?#)
3940                      ;; Colon is special only after a label
3941                      ;; So quickly rule out most other uses of colon
3942                      ;; and do no indentation for them.
3943                      (and (eq last-command-char ?:)
3944                           (save-excursion
3945                             (forward-word 1)
3946                             (skip-chars-forward " \t")
3947                             (and (< (point) end)
3948                                  (progn (goto-char (- end 1))
3949                                         (not (looking-at ":"))))))
3950                      (progn
3951                        (beginning-of-defun)
3952                        (let ((pps (parse-partial-sexp (point) end)))
3953                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
3954         (progn
3955           (self-insert-command (prefix-numeric-value arg))
3956           ;;(forward-char -1)
3957           (if auto (setq insertpos (point-marker)))
3958           ;;(forward-char 1)
3959           (cperl-indent-line)
3960           (if auto
3961               (progn
3962                 (newline)
3963                 (cperl-indent-line)))
3964           (save-excursion
3965             (if insertpos (goto-char (1- (marker-position insertpos)))
3966               (forward-char -1))
3967             (delete-char 1))))
3968     (if insertpos
3969         (save-excursion
3970           (goto-char insertpos)
3971           (self-insert-command (prefix-numeric-value arg)))
3972       (self-insert-command (prefix-numeric-value arg)))))
3973
3974 (defun cperl-electric-backspace (arg)
3975   "Backspace, or remove the whitespace around the point inserted by an electric
3976 key.  Will untabivy if `cperl-electric-backspace-untabify' is non-nil."
3977   (interactive "p")
3978   (if (and cperl-auto-newline
3979            (memq last-command '(cperl-electric-semi
3980                                 cperl-electric-terminator
3981                                 cperl-electric-lbrace))
3982            (memq (preceding-char) '(?\  ?\t ?\n)))
3983       (let (p)
3984         (if (eq last-command 'cperl-electric-lbrace)
3985             (skip-chars-forward " \t\n"))
3986         (setq p (point))
3987         (skip-chars-backward " \t\n")
3988         (delete-region (point) p))
3989     (and (eq last-command 'cperl-electric-else)
3990          ;; We are removing the whitespace *inside* cperl-electric-else
3991          (setq this-command 'cperl-electric-else-really))
3992     (if (and cperl-auto-newline
3993              (eq last-command 'cperl-electric-else-really)
3994              (memq (preceding-char) '(?\  ?\t ?\n)))
3995         (let (p)
3996           (skip-chars-forward " \t\n")
3997           (setq p (point))
3998           (skip-chars-backward " \t\n")
3999           (delete-region (point) p))
4000       (if cperl-electric-backspace-untabify
4001           (backward-delete-char-untabify arg)
4002         (delete-backward-char arg)))))
4003
4004 (defun cperl-inside-parens-p ()         ;; NOT USED????
4005   (condition-case ()
4006       (save-excursion
4007         (save-restriction
4008           (narrow-to-region (point)
4009                             (progn (beginning-of-defun) (point)))
4010           (goto-char (point-max))
4011           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
4012     (error nil)))
4013 \f
4014 (defun cperl-indent-command (&optional whole-exp)
4015   "Indent current line as Perl code, or in some cases insert a tab character.
4016 If `cperl-tab-always-indent' is non-nil (the default), always indent current
4017 line.  Otherwise, indent the current line only if point is at the left margin
4018 or in the line's indentation; otherwise insert a tab.
4019
4020 A numeric argument, regardless of its value,
4021 means indent rigidly all the lines of the expression starting after point
4022 so that this line becomes properly indented.
4023 The relative indentation among the lines of the expression are preserved."
4024   (interactive "P")
4025   (cperl-update-syntaxification (point) (point))
4026   (if whole-exp
4027       ;; If arg, always indent this line as Perl
4028       ;; and shift remaining lines of expression the same amount.
4029       (let ((shift-amt (cperl-indent-line))
4030             beg end)
4031         (save-excursion
4032           (if cperl-tab-always-indent
4033               (beginning-of-line))
4034           (setq beg (point))
4035           (forward-sexp 1)
4036           (setq end (point))
4037           (goto-char beg)
4038           (forward-line 1)
4039           (setq beg (point)))
4040         (if (and shift-amt (> end beg))
4041             (indent-code-rigidly beg end shift-amt "#")))
4042     (if (and (not cperl-tab-always-indent)
4043              (save-excursion
4044                (skip-chars-backward " \t")
4045                (not (bolp))))
4046         (insert-tab)
4047       (cperl-indent-line))))
4048
4049 (defun cperl-indent-line (&optional parse-data)
4050   "Indent current line as Perl code.
4051 Return the amount the indentation changed by."
4052   (let ((case-fold-search nil)
4053         (pos (- (point-max) (point)))
4054         indent i beg shift-amt)
4055     (setq indent (cperl-calculate-indent parse-data)
4056           i indent)
4057     (beginning-of-line)
4058     (setq beg (point))
4059     (cond ((or (eq indent nil) (eq indent t))
4060            (setq indent (current-indentation) i nil))
4061           ;;((eq indent t)    ; Never?
4062           ;; (setq indent (cperl-calculate-indent-within-comment)))
4063           ;;((looking-at "[ \t]*#")
4064           ;; (setq indent 0))
4065           (t
4066            (skip-chars-forward " \t")
4067            (if (listp indent) (setq indent (car indent)))
4068            (cond ((looking-at "[A-Za-z_][A-Za-z_0-9]*:[^:]")
4069                   (and (> indent 0)
4070                        (setq indent (max cperl-min-label-indent
4071                                          (+ indent cperl-label-offset)))))
4072                  ((= (following-char) ?})
4073                   (setq indent (- indent cperl-indent-level)))
4074                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
4075                   (setq indent (+ indent cperl-close-paren-offset)))
4076                  ((= (following-char) ?{)
4077                   (setq indent (+ indent cperl-brace-offset))))))
4078     (skip-chars-forward " \t")
4079     (setq shift-amt (and i (- indent (current-column))))
4080     (if (or (not shift-amt)
4081             (zerop shift-amt))
4082         (if (> (- (point-max) pos) (point))
4083             (goto-char (- (point-max) pos)))
4084       ;;;(delete-region beg (point))
4085       ;;;(indent-to indent)
4086       (cperl-make-indent indent)
4087       ;; If initial point was within line's indentation,
4088       ;; position after the indentation.  Else stay at same point in text.
4089       (if (> (- (point-max) pos) (point))
4090           (goto-char (- (point-max) pos))))
4091     shift-amt))
4092
4093 (defun cperl-after-label ()
4094   ;; Returns true if the point is after label.  Does not do save-excursion.
4095   (and (eq (preceding-char) ?:)
4096        (memq (char-syntax (char-after (- (point) 2)))
4097              '(?w ?_))
4098        (progn
4099          (backward-sexp)
4100          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))
4101
4102 (defun cperl-get-state (&optional parse-start start-state)
4103   ;; returns list (START STATE DEPTH PRESTART),
4104   ;; START is a good place to start parsing, or equal to
4105   ;; PARSE-START if preset,
4106   ;; STATE is what is returned by `parse-partial-sexp'.
4107   ;; DEPTH is true is we are immediately after end of block
4108   ;; which contains START.
4109   ;; PRESTART is the position basing on which START was found.
4110   (save-excursion
4111     (let ((start-point (point)) depth state start prestart)
4112       (if (and parse-start
4113                (<= parse-start start-point))
4114           (goto-char parse-start)
4115         (beginning-of-defun)
4116         (setq start-state nil))
4117       (setq prestart (point))
4118       (if start-state nil
4119         ;; Try to go out, if sub is not on the outermost level
4120         (while (< (point) start-point)
4121           (setq start (point) parse-start start depth nil
4122                 state (parse-partial-sexp start start-point -1))
4123           (if (> (car state) -1) nil
4124             ;; The current line could start like }}}, so the indentation
4125             ;; corresponds to a different level than what we reached
4126             (setq depth t)
4127             (beginning-of-line 2)))     ; Go to the next line.
4128         (if start (goto-char start)))   ; Not at the start of file
4129       (setq start (point))
4130       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
4131       (list start state depth prestart))))
4132
4133 (defvar cperl-look-for-prop '((pod in-pod) (here-doc-delim here-doc-group)))
4134
4135 (defun cperl-beginning-of-property (p prop &optional lim)
4136   "Given that P has a property PROP, find where the property starts.
4137 Will not look before LIM."
4138   ;;; XXXX What to do at point-max???
4139   (or (previous-single-property-change (cperl-1+ p) prop lim)
4140       (point-min))
4141 ;;;  (cond ((eq p (point-min))
4142 ;;;      p)
4143 ;;;     ((and lim (<= p lim))
4144 ;;;      p)
4145 ;;;     ((not (get-text-property (1- p) prop))
4146 ;;;      p)
4147 ;;;     (t (or (previous-single-property-change p look-prop lim)
4148 ;;;            (point-min))))
4149   )
4150
4151 (defun cperl-calculate-indent (&optional parse-data) ; was parse-start
4152   "Return appropriate indentation for current line as Perl code.
4153 In usual case returns an integer: the column to indent to.
4154 Returns nil if line starts inside a string, t if in a comment.
4155
4156 Will not correct the indentation for labels, but will correct it for braces
4157 and closing parentheses and brackets."
4158   (cperl-update-syntaxification (point) (point))
4159   (save-excursion
4160     (if (or
4161          (and (memq (get-text-property (point) 'syntax-type)
4162                     '(pod here-doc here-doc-delim format))
4163               (not (get-text-property (point) 'indentable)))
4164          ;; before start of POD - whitespace found since do not have 'pod!
4165          (and (looking-at "[ \t]*\n=")
4166               (error "Spaces before POD section!"))
4167          (and (not cperl-indent-left-aligned-comments)
4168               (looking-at "^#")))
4169         nil
4170       (beginning-of-line)
4171       (let* ((indent-point (point))
4172              (char-after-pos (save-excursion
4173                                (skip-chars-forward " \t")
4174                                (point)))
4175              (char-after (char-after char-after-pos))
4176              (in-pod (get-text-property (point) 'in-pod))
4177              (pre-indent-point (point))
4178              p prop look-prop is-block delim)
4179         (cond
4180          (in-pod
4181           ;; In the verbatim part, probably code example.  What to do???
4182           )
4183          (t
4184           (save-excursion
4185             ;; Not in POD
4186             (cperl-backward-to-noncomment nil)
4187             (setq p (max (point-min) (1- (point)))
4188                   prop (get-text-property p 'syntax-type)
4189                   look-prop (or (nth 1 (assoc prop cperl-look-for-prop))
4190                                 'syntax-type))
4191             (if (memq prop '(pod here-doc format here-doc-delim))
4192                 (progn
4193                   (goto-char (cperl-beginning-of-property p look-prop))
4194                   (beginning-of-line)
4195                   (setq pre-indent-point (point)))))))
4196         (goto-char pre-indent-point)
4197         (let* ((case-fold-search nil)
4198                (s-s (cperl-get-state (car parse-data) (nth 1 parse-data)))
4199                (start (or (nth 2 parse-data)
4200                           (nth 0 s-s)))
4201                (state (nth 1 s-s))
4202                (containing-sexp (car (cdr state)))
4203                old-indent)
4204           (if (and
4205                ;;containing-sexp                ;; We are buggy at toplevel :-(
4206                parse-data)
4207               (progn
4208                 (setcar parse-data pre-indent-point)
4209                 (setcar (cdr parse-data) state)
4210                 (or (nth 2 parse-data)
4211                     (setcar (cddr parse-data) start))
4212                 ;; Before this point: end of statement
4213                 (setq old-indent (nth 3 parse-data))))
4214           (cond ((get-text-property (point) 'indentable)
4215                  ;; indent to "after" the surrounding open
4216                  ;; (same offset as `cperl-beautify-regexp-piece'),
4217                  ;; skip blanks if we do not close the expression.
4218                  (setq delim            ; We do not close the expression
4219                        (get-text-property
4220                         (cperl-1+ char-after-pos) 'indentable)
4221                        p (1+ (cperl-beginning-of-property
4222                               (point) 'indentable))
4223                        is-block         ; misused for: preceeding line in REx
4224                        (save-excursion  ; Find preceeding line
4225                          (cperl-backward-to-noncomment p)
4226                          (beginning-of-line)
4227                          (if (<= (point) p)
4228                              (progn     ; get indent from the first line
4229                                (goto-char p)
4230                                (skip-chars-forward " \t")
4231                                (if (memq (char-after (point))
4232                                          (append "#\n" nil))
4233                                    nil  ; Can't use intentation of this line...
4234                                  (point)))
4235                            (skip-chars-forward " \t")
4236                            (point)))
4237                        prop (parse-partial-sexp p char-after-pos))
4238                  (cond ((not delim)
4239                         (goto-char p)   ; beginning of REx etc
4240                         (1- (current-column))) ; End the REx, ignore is-block
4241                        (is-block
4242                         ;; Indent as the level after closing parens
4243                         (goto-char char-after-pos)
4244                         (skip-chars-forward " \t)")
4245                         (setq char-after-pos (point))
4246                         (goto-char is-block)
4247                         (skip-chars-forward " \t)")
4248                         (setq p (parse-partial-sexp (point) char-after-pos))
4249                         (goto-char is-block)
4250                         (+ (* (nth 0 p)
4251                               (or cperl-regexp-indent-step cperl-indent-level))
4252                            (cond ((eq char-after ?\) )
4253                                   (- cperl-close-paren-offset)) ; compensate
4254                                  ((eq char-after ?\| )
4255                                   (- (or cperl-regexp-indent-step cperl-indent-level)))
4256                                  (t 0))
4257                            (if (eq (following-char) ?\| )
4258                                (or cperl-regexp-indent-step cperl-indent-level)
4259                              0)
4260                            (current-column)))
4261                        ;; Now we have no preceeding line...
4262                        (t
4263                         (goto-char p)
4264                         (+ (or cperl-regexp-indent-step cperl-indent-level)
4265                            -1
4266                            (current-column)))))
4267                 ((get-text-property char-after-pos 'REx-part2)
4268                  (condition-case nil    ; Use indentation of the 1st part
4269                      (forward-sexp -1))
4270                  (current-column))
4271                 ((or (nth 3 state) (nth 4 state))
4272                  ;; return nil or t if should not change this line
4273                  (nth 4 state))
4274                 ;; XXXX Do we need to special-case this?
4275                 ((null containing-sexp)
4276                  ;; Line is at top level.  May be data or function definition,
4277                  ;; or may be function argument declaration.
4278                  ;; Indent like the previous top level line
4279                  ;; unless that ends in a closeparen without semicolon,
4280                  ;; in which case this line is the first argument decl.
4281                  (skip-chars-forward " \t")
4282                  (+ (save-excursion
4283                       (goto-char start)
4284                       (- (current-indentation)
4285                          (if (nth 2 s-s) cperl-indent-level 0)))
4286                     (if (eq char-after ?{) cperl-continued-brace-offset 0)
4287                     (progn
4288                       (cperl-backward-to-noncomment (or old-indent (point-min)))
4289                       ;; Look at previous line that's at column 0
4290                       ;; to determine whether we are in top-level decls
4291                       ;; or function's arg decls.  Set basic-indent accordingly.
4292                       ;; Now add a little if this is a continuation line.
4293                       (if (or (bobp)
4294                               (eq (point) old-indent) ; old-indent was at comment
4295                               (eq (preceding-char) ?\;)
4296                               ;;  Had ?\) too
4297                               (and (eq (preceding-char) ?\})
4298                                    (cperl-after-block-and-statement-beg
4299                                     (point-min))) ; Was start - too close
4300                               (memq char-after (append ")]}" nil))
4301                               (and (eq (preceding-char) ?\:) ; label
4302                                    (progn
4303                                      (forward-sexp -1)
4304                                      (skip-chars-backward " \t")
4305                                      (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*[ \t]*:")))
4306                               (get-text-property (point) 'first-format-line))
4307                           (progn
4308                             (if (and parse-data
4309                                      (not (eq char-after ?\C-j)))
4310                                 (setcdr (cddr parse-data)
4311                                         (list pre-indent-point)))
4312                             0)
4313                         cperl-continued-statement-offset))))
4314                 ((not
4315                   (or (setq is-block
4316                             (and (setq delim (= (char-after containing-sexp) ?{))
4317                                  (save-excursion ; Is it a hash?
4318                                    (goto-char containing-sexp)
4319                                    (cperl-block-p))))
4320                       cperl-indent-parens-as-block))
4321                  ;; group is an expression, not a block:
4322                  ;; indent to just after the surrounding open parens,
4323                  ;; skip blanks if we do not close the expression.
4324                  (goto-char (1+ containing-sexp))
4325                  (or (memq char-after
4326                            (append (if delim "}" ")]}") nil))
4327                      (looking-at "[ \t]*\\(#\\|$\\)")
4328                      (skip-chars-forward " \t"))
4329                  (+ (current-column)
4330                     (if (and delim
4331                              (eq char-after ?\}))
4332                         ;; Correct indentation of trailing ?\}
4333                         (+ cperl-indent-level cperl-close-paren-offset)
4334                       0)))
4335 ;;;           ((and (/= (char-after containing-sexp) ?{)
4336 ;;;                 (not cperl-indent-parens-as-block))
4337 ;;;            ;; line is expression, not statement:
4338 ;;;            ;; indent to just after the surrounding open,
4339 ;;;            ;; skip blanks if we do not close the expression.
4340 ;;;            (goto-char (1+ containing-sexp))
4341 ;;;            (or (memq char-after (append ")]}" nil))
4342 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
4343 ;;;                (skip-chars-forward " \t"))
4344 ;;;            (current-column))
4345 ;;;           ((progn
4346 ;;;              ;; Containing-expr starts with \{.  Check whether it is a hash.
4347 ;;;              (goto-char containing-sexp)
4348 ;;;              (and (not (cperl-block-p))
4349 ;;;                   (not cperl-indent-parens-as-block)))
4350 ;;;            (goto-char (1+ containing-sexp))
4351 ;;;            (or (eq char-after ?\})
4352 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
4353 ;;;                (skip-chars-forward " \t"))
4354 ;;;            (+ (current-column)      ; Correct indentation of trailing ?\}
4355 ;;;               (if (eq char-after ?\}) (+ cperl-indent-level
4356 ;;;                                          cperl-close-paren-offset)
4357 ;;;                 0)))
4358                 (t
4359                  ;; Statement level.  Is it a continuation or a new statement?
4360                  ;; Find previous non-comment character.
4361                  (goto-char pre-indent-point)
4362                  (cperl-backward-to-noncomment containing-sexp)
4363                  ;; Back up over label lines, since they don't
4364                  ;; affect whether our line is a continuation.
4365                  ;; (Had \, too)
4366                  (while;;(or (eq (preceding-char) ?\,)
4367                      (and (eq (preceding-char) ?:)
4368                           (or;;(eq (char-after (- (point) 2)) ?\') ; ????
4369                            (memq (char-syntax (char-after (- (point) 2)))
4370                                  '(?w ?_))))
4371                    ;;)
4372                    (if (eq (preceding-char) ?\,)
4373                        ;; Will go to beginning of line, essentially.
4374                        ;; Will ignore embedded sexpr XXXX.
4375                        (cperl-backward-to-start-of-continued-exp containing-sexp))
4376                    (beginning-of-line)
4377                    (cperl-backward-to-noncomment containing-sexp))
4378                  ;; Now we get the answer.
4379                  (if (not (or (eq (1- (point)) containing-sexp)
4380                               (memq (preceding-char)
4381                                     (append (if is-block " ;{" " ,;{") '(nil)))
4382                               (and (eq (preceding-char) ?\})
4383                                    (cperl-after-block-and-statement-beg
4384                                     containing-sexp))
4385                               (get-text-property (point) 'first-format-line)))
4386                      ;; This line is continuation of preceding line's statement;
4387                      ;; indent  `cperl-continued-statement-offset'  more than the
4388                      ;; previous line of the statement.
4389                      ;;
4390                      ;; There might be a label on this line, just
4391                      ;; consider it bad style and ignore it.
4392                      (progn
4393                        (cperl-backward-to-start-of-continued-exp containing-sexp)
4394                        (+ (if (memq char-after (append "}])" nil))
4395                               0         ; Closing parenth
4396                             cperl-continued-statement-offset)
4397                           (if (or is-block
4398                                   (not delim)
4399                                   (not (eq char-after ?\})))
4400                               0
4401                             ;; Now it is a hash reference
4402                             (+ cperl-indent-level cperl-close-paren-offset))
4403                           ;; Labels do not take :: ...
4404                           (if (looking-at "\\(\\w\\|_\\)+[ \t]*:")
4405                               (if (> (current-indentation) cperl-min-label-indent)
4406                                   (- (current-indentation) cperl-label-offset)
4407                                 ;; Do not move `parse-data', this should
4408                                 ;; be quick anyway (this comment comes
4409                                 ;; from different location):
4410                                 (cperl-calculate-indent))
4411                             (current-column))
4412                           (if (eq char-after ?\{)
4413                               cperl-continued-brace-offset 0)))
4414                    ;; This line starts a new statement.
4415                    ;; Position following last unclosed open.
4416                    (goto-char containing-sexp)
4417                    ;; Is line first statement after an open-brace?
4418                    (or
4419                     ;; If no, find that first statement and indent like
4420                     ;; it.  If the first statement begins with label, do
4421                     ;; not believe when the indentation of the label is too
4422                     ;; small.
4423                     (save-excursion
4424                       (forward-char 1)
4425                       (setq old-indent (current-indentation))
4426                       (let ((colon-line-end 0))
4427                         (while
4428                             (progn (skip-chars-forward " \t\n")
4429                                    (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]\\|=[a-zA-Z]"))
4430                           ;; Skip over comments and labels following openbrace.
4431                           (cond ((= (following-char) ?\#)
4432                                  (forward-line 1))
4433                                 ((= (following-char) ?\=)
4434                                  (goto-char
4435                                   (or (next-single-property-change (point) 'in-pod)
4436                                       (point-max)))) ; do not loop if no syntaxification
4437                                 ;; label:
4438                                 (t
4439                                  (save-excursion (end-of-line)
4440                                                  (setq colon-line-end (point)))
4441                                  (search-forward ":"))))
4442                         ;; The first following code counts
4443                         ;; if it is before the line we want to indent.
4444                         (and (< (point) indent-point)
4445                              (if (> colon-line-end (point)) ; After label
4446                                  (if (> (current-indentation)
4447                                         cperl-min-label-indent)
4448                                      (- (current-indentation) cperl-label-offset)
4449                                    ;; Do not believe: `max' is involved
4450                                    (+ old-indent cperl-indent-level))
4451                                (current-column)))))
4452                     ;; If no previous statement,
4453                     ;; indent it relative to line brace is on.
4454                     ;; For open brace in column zero, don't let statement
4455                     ;; start there too.  If cperl-indent-level is zero,
4456                     ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
4457                     ;; For open-braces not the first thing in a line,
4458                     ;; add in cperl-brace-imaginary-offset.
4459
4460                     ;; If first thing on a line:  ?????
4461                     (+ (if (and (bolp) (zerop cperl-indent-level))
4462                            (+ cperl-brace-offset cperl-continued-statement-offset)
4463                          cperl-indent-level)
4464                        (if (or is-block
4465                                (not delim)
4466                                (not (eq char-after ?\})))
4467                            0
4468                          ;; Now it is a hash reference
4469                          (+ cperl-indent-level cperl-close-paren-offset))
4470                        ;; Move back over whitespace before the openbrace.
4471                        ;; If openbrace is not first nonwhite thing on the line,
4472                        ;; add the cperl-brace-imaginary-offset.
4473                        (progn (skip-chars-backward " \t")
4474                               (if (bolp) 0 cperl-brace-imaginary-offset))
4475                        ;; If the openbrace is preceded by a parenthesized exp,
4476                        ;; move to the beginning of that;
4477                        ;; possibly a different line
4478                        (progn
4479                          (cperl-backward-to-noncomment (point-min))
4480                          (if (eq (preceding-char) ?\))
4481                              (forward-sexp -1))
4482                          ;; In the case it starts a subroutine, indent with
4483                          ;; respect to `sub', not with respect to the
4484                          ;; first thing on the line, say in the case of
4485                          ;; anonymous sub in a hash.
4486                          ;;
4487                          ;;(skip-chars-backward " \t")
4488                          (cperl-backward-to-noncomment (point-min))
4489                          (if (and
4490                               (or
4491                                (and (get-text-property (point) 'attrib-group)
4492                                     (goto-char
4493                                      (cperl-beginning-of-property
4494                                       (point) 'attrib-group)))
4495                                (and (eq (preceding-char) ?b)
4496                                     (progn
4497                                       (forward-sexp -1)
4498                                       (looking-at "sub\\>"))))
4499                               (setq old-indent
4500                                     (nth 1
4501                                          (parse-partial-sexp
4502                                           (save-excursion (beginning-of-line) (point))
4503                                           (point)))))
4504                              (progn (goto-char (1+ old-indent))
4505                                     (skip-chars-forward " \t")
4506                                     (current-column))
4507                            ;; Get initial indentation of the line we are on.
4508                            ;; If line starts with label, calculate label indentation
4509                            (if (save-excursion
4510                                  (beginning-of-line)
4511                                  (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
4512                                (if (> (current-indentation) cperl-min-label-indent)
4513                                    (- (current-indentation) cperl-label-offset)
4514                                  ;; Do not move `parse-data', this should
4515                                  ;; be quick anyway:
4516                                  (cperl-calculate-indent))
4517                              (current-indentation))))))))))))))
4518
4519 (defvar cperl-indent-alist
4520   '((string nil)
4521     (comment nil)
4522     (toplevel 0)
4523     (toplevel-after-parenth 2)
4524     (toplevel-continued 2)
4525     (expression 1))
4526   "Alist of indentation rules for CPerl mode.
4527 The values mean:
4528   nil: do not indent;
4529   number: add this amount of indentation.
4530
4531 Not finished, not used.")
4532
4533 (defun cperl-where-am-i (&optional parse-start start-state)
4534   ;; Unfinished
4535   "Return a list of lists ((TYPE POS)...) of good points before the point.
4536 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'.
4537
4538 Not finished, not used."
4539   (save-excursion
4540     (let* ((start-point (point)) unused
4541            (s-s (cperl-get-state))
4542            (start (nth 0 s-s))
4543            (state (nth 1 s-s))
4544            (prestart (nth 3 s-s))
4545            (containing-sexp (car (cdr state)))
4546            (case-fold-search nil)
4547            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
4548       (cond ((nth 3 state)              ; In string
4549              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
4550             ((nth 4 state)              ; In comment
4551              (setq res (cons '(comment) res)))
4552             ((null containing-sexp)
4553              ;; Line is at top level.
4554              ;; Indent like the previous top level line
4555              ;; unless that ends in a closeparen without semicolon,
4556              ;; in which case this line is the first argument decl.
4557              (cperl-backward-to-noncomment (or parse-start (point-min)))
4558              ;;(skip-chars-backward " \t\f\n")
4559              (cond
4560               ((or (bobp)
4561                    (memq (preceding-char) (append ";}" nil)))
4562                (setq res (cons (list 'toplevel start) res)))
4563               ((eq (preceding-char) ?\) )
4564                (setq res (cons (list 'toplevel-after-parenth start) res)))
4565               (t
4566                (setq res (cons (list 'toplevel-continued start) res)))))
4567             ((/= (char-after containing-sexp) ?{)
4568              ;; line is expression, not statement:
4569              ;; indent to just after the surrounding open.
4570              ;; skip blanks if we do not close the expression.
4571              (setq res (cons (list 'expression-blanks
4572                                    (progn
4573                                      (goto-char (1+ containing-sexp))
4574                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
4575                                          (skip-chars-forward " \t"))
4576                                      (point)))
4577                              (cons (list 'expression containing-sexp) res))))
4578             ((progn
4579                ;; Containing-expr starts with \{.  Check whether it is a hash.
4580                (goto-char containing-sexp)
4581                (not (cperl-block-p)))
4582              (setq res (cons (list 'expression-blanks
4583                                    (progn
4584                                      (goto-char (1+ containing-sexp))
4585                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
4586                                          (skip-chars-forward " \t"))
4587                                      (point)))
4588                              (cons (list 'expression containing-sexp) res))))
4589             (t
4590              ;; Statement level.
4591              (setq res (cons (list 'in-block containing-sexp) res))
4592              ;; Is it a continuation or a new statement?
4593              ;; Find previous non-comment character.
4594              (cperl-backward-to-noncomment containing-sexp)
4595              ;; Back up over label lines, since they don't
4596              ;; affect whether our line is a continuation.
4597              ;; Back up comma-delimited lines too ?????
4598              (while (or (eq (preceding-char) ?\,)
4599                         (save-excursion (cperl-after-label)))
4600                (if (eq (preceding-char) ?\,)
4601                    ;; Will go to beginning of line, essentially
4602                    ;; Will ignore embedded sexpr XXXX.
4603                    (cperl-backward-to-start-of-continued-exp containing-sexp))
4604                (beginning-of-line)
4605                (cperl-backward-to-noncomment containing-sexp))
4606              ;; Now we get the answer.
4607              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
4608                  ;; This line is continuation of preceding line's statement.
4609                  (list (list 'statement-continued containing-sexp))
4610                ;; This line starts a new statement.
4611                ;; Position following last unclosed open.
4612                (goto-char containing-sexp)
4613                ;; Is line first statement after an open-brace?
4614                (or
4615                 ;; If no, find that first statement and indent like
4616                 ;; it.  If the first statement begins with label, do
4617                 ;; not believe when the indentation of the label is too
4618                 ;; small.
4619                 (save-excursion
4620                   (forward-char 1)
4621                   (let ((colon-line-end 0))
4622                     (while (progn (skip-chars-forward " \t\n" start-point)
4623                                   (and (< (point) start-point)
4624                                        (looking-at
4625                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
4626                       ;; Skip over comments and labels following openbrace.
4627                       (cond ((= (following-char) ?\#)
4628                              ;;(forward-line 1)
4629                              (end-of-line))
4630                             ;; label:
4631                             (t
4632                              (save-excursion (end-of-line)
4633                                              (setq colon-line-end (point)))
4634                              (search-forward ":"))))
4635                     ;; Now at the point, after label, or at start
4636                     ;; of first statement in the block.
4637                     (and (< (point) start-point)
4638                          (if (> colon-line-end (point))
4639                              ;; Before statement after label
4640                              (if (> (current-indentation)
4641                                     cperl-min-label-indent)
4642                                  (list (list 'label-in-block (point)))
4643                                ;; Do not believe: `max' is involved
4644                                (list
4645                                 (list 'label-in-block-min-indent (point))))
4646                            ;; Before statement
4647                            (list 'statement-in-block (point))))))
4648                 ;; If no previous statement,
4649                 ;; indent it relative to line brace is on.
4650                 ;; For open brace in column zero, don't let statement
4651                 ;; start there too.  If cperl-indent-level is zero,
4652                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
4653                 ;; For open-braces not the first thing in a line,
4654                 ;; add in cperl-brace-imaginary-offset.
4655
4656                 ;; If first thing on a line:  ?????
4657                 (setq unused            ; This is not finished...
4658                 (+ (if (and (bolp) (zerop cperl-indent-level))
4659                        (+ cperl-brace-offset cperl-continued-statement-offset)
4660                      cperl-indent-level)
4661                    ;; Move back over whitespace before the openbrace.
4662                    ;; If openbrace is not first nonwhite thing on the line,
4663                    ;; add the cperl-brace-imaginary-offset.
4664                    (progn (skip-chars-backward " \t")
4665                           (if (bolp) 0 cperl-brace-imaginary-offset))
4666                    ;; If the openbrace is preceded by a parenthesized exp,
4667                    ;; move to the beginning of that;
4668                    ;; possibly a different line
4669                    (progn
4670                      (if (eq (preceding-char) ?\))
4671                          (forward-sexp -1))
4672                      ;; Get initial indentation of the line we are on.
4673                      ;; If line starts with label, calculate label indentation
4674                      (if (save-excursion
4675                            (beginning-of-line)
4676                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
4677                          (if (> (current-indentation) cperl-min-label-indent)
4678                              (- (current-indentation) cperl-label-offset)
4679                            (cperl-calculate-indent))
4680                        (current-indentation)))))))))
4681       res)))
4682
4683 (defun cperl-calculate-indent-within-comment ()
4684   "Return the indentation amount for line, assuming that
4685 the current line is to be regarded as part of a block comment."
4686   (let (end star-start)
4687     (save-excursion
4688       (beginning-of-line)
4689       (skip-chars-forward " \t")
4690       (setq end (point))
4691       (and (= (following-char) ?#)
4692            (forward-line -1)
4693            (cperl-to-comment-or-eol)
4694            (setq end (point)))
4695       (goto-char end)
4696       (current-column))))
4697
4698
4699 (defun cperl-to-comment-or-eol ()
4700   "Go to position before comment on the current line, or to end of line.
4701 Returns true if comment is found.  In POD will not move the point."
4702   ;; If the line is inside other syntax groups (qq-style strings, HERE-docs)
4703   ;; then looks for literal # or end-of-line.
4704   (let (state stop-in cpoint (lim (progn (end-of-line) (point))) pr e)
4705     (or cperl-font-locking
4706         (cperl-update-syntaxification lim lim))
4707     (beginning-of-line)
4708     (if (setq pr (get-text-property (point) 'syntax-type))
4709         (setq e (next-single-property-change (point) 'syntax-type nil (point-max))))
4710     (if (or (eq pr 'pod)
4711             (if (or (not e) (> e lim))  ; deep inside a group
4712                 (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t)))
4713         (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
4714       ;; Else - need to do it the hard way
4715       (and (and e (<= e lim))
4716            (goto-char e))
4717       (while (not stop-in)
4718         (setq state (parse-partial-sexp (point) lim nil nil nil t))
4719                                         ; stop at comment
4720         ;; If fails (beginning-of-line inside sexp), then contains not-comment
4721         (if (nth 4 state)               ; After `#';
4722                                         ; (nth 2 state) can be
4723                                         ; beginning of m,s,qq and so
4724                                         ; on
4725             (if (nth 2 state)
4726                 (progn
4727                   (setq cpoint (point))
4728                   (goto-char (nth 2 state))
4729                   (cond
4730                    ((looking-at "\\(s\\|tr\\)\\>")
4731                     (or (re-search-forward
4732                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
4733                          lim 'move)
4734                         (setq stop-in t)))
4735                    ((looking-at "\\(m\\|q\\([qxwr]\\)?\\)\\>")
4736                     (or (re-search-forward
4737                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
4738                          lim 'move)
4739                         (setq stop-in t)))
4740                    (t                   ; It was fair comment
4741                     (setq stop-in t)    ; Finish
4742                     (goto-char (1- cpoint)))))
4743               (setq stop-in t)          ; Finish
4744               (forward-char -1))
4745           (setq stop-in t)))            ; Finish
4746       (nth 4 state))))
4747
4748 (defsubst cperl-modify-syntax-type (at how)
4749   (if (< at (point-max))
4750       (progn
4751         (put-text-property at (1+ at) 'syntax-table how)
4752         (put-text-property at (1+ at) 'rear-nonsticky '(syntax-table)))))
4753
4754 (defun cperl-protect-defun-start (s e)
4755   ;; C code looks for "^\\s(" to skip comment backward in "hard" situations
4756   (save-excursion
4757     (goto-char s)
4758     (while (re-search-forward "^\\s(" e 'to-end)
4759       (put-text-property (1- (point)) (point) 'syntax-table cperl-st-punct))))
4760
4761 (defun cperl-commentify (bb e string &optional noface)
4762   (if cperl-use-syntax-table-text-property
4763       (if (eq noface 'n)                ; Only immediate
4764           nil
4765         ;; We suppose that e is _after_ the end of construction, as after eol.
4766         (setq string (if string cperl-st-sfence cperl-st-cfence))
4767         (if (> bb (- e 2))
4768             ;; one-char string/comment?!
4769             (cperl-modify-syntax-type bb cperl-st-punct)
4770           (cperl-modify-syntax-type bb string)
4771           (cperl-modify-syntax-type (1- e) string))
4772         (if (and (eq string cperl-st-sfence) (> (- e 2) bb))
4773             (put-text-property (1+ bb) (1- e)
4774                                'syntax-table cperl-string-syntax-table))
4775         (cperl-protect-defun-start bb e))
4776     ;; Fontify
4777     (or noface
4778         (not cperl-pod-here-fontify)
4779         (put-text-property bb e 'face (if string 'font-lock-string-face
4780                                         'font-lock-comment-face)))))
4781
4782 (defvar cperl-starters '(( ?\( . ?\) )
4783                          ( ?\[ . ?\] )
4784                          ( ?\{ . ?\} )
4785                          ( ?\< . ?\> )))
4786
4787 (defun cperl-cached-syntax-table (st)
4788   "Get a syntax table cached in ST, or create and cache into ST a syntax table.
4789 All the entries of the syntax table are \".\", except for a backslash, which
4790 is quoting."
4791   (if (car-safe st)
4792       (car st)
4793     (setcar st (make-syntax-table))
4794     (setq st (car st))
4795     (let ((i 0))
4796       (while (< i 256)
4797         (modify-syntax-entry i "." st)
4798         (setq i (1+ i))))
4799     (modify-syntax-entry ?\\ "\\" st)
4800     st))
4801
4802 (defun cperl-forward-re (lim end is-2arg st-l err-l argument
4803                              &optional ostart oend)
4804 "Find the end of a regular expression or a stringish construct (q[] etc).
4805 The point should be before the starting delimiter.
4806
4807 Goes to LIM if none is found.  If IS-2ARG is non-nil, assumes that it
4808 is s/// or tr/// like expression.  If END is nil, generates an error
4809 message if needed.  If SET-ST is non-nil, will use (or generate) a
4810 cached syntax table in ST-L.  If ERR-L is non-nil, will store the
4811 error message in its CAR (unless it already contains some error
4812 message).  ARGUMENT should be the name of the construct (used in error
4813 messages).  OSTART, OEND may be set in recursive calls when processing
4814 the second argument of 2ARG construct.
4815
4816 Works *before* syntax recognition is done.  In IS-2ARG situation may
4817 modify syntax-type text property if the situation is too hard."
4818   (let (b starter ender st i i2 go-forward reset-st set-st)
4819     (skip-chars-forward " \t")
4820     ;; ender means matching-char matcher.
4821     (setq b (point)
4822           starter (if (eobp) 0 (char-after b))
4823           ender (cdr (assoc starter cperl-starters)))
4824     ;; What if starter == ?\\  ????
4825     (setq st (cperl-cached-syntax-table st-l))
4826     (setq set-st t)
4827     ;; Whether we have an intermediate point
4828     (setq i nil)
4829     ;; Prepare the syntax table:
4830     (if (not ender)             ; m/blah/, s/x//, s/x/y/
4831         (modify-syntax-entry starter "$" st)
4832       (modify-syntax-entry starter (concat "(" (list ender)) st)
4833       (modify-syntax-entry ender  (concat ")" (list starter)) st))
4834     (condition-case bb
4835         (progn
4836           ;; We use `$' syntax class to find matching stuff, but $$
4837           ;; is recognized the same as $, so we need to check this manually.
4838           (if (and (eq starter (char-after (cperl-1+ b)))
4839                    (not ender))
4840               ;; $ has TeXish matching rules, so $$ equiv $...
4841               (forward-char 2)
4842             (setq reset-st (syntax-table))
4843             (set-syntax-table st)
4844             (forward-sexp 1)
4845             (if (<= (point) (1+ b))
4846                 (error "Unfinished regular expression"))
4847             (set-syntax-table reset-st)
4848             (setq reset-st nil)
4849             ;; Now the problem is with m;blah;;
4850             (and (not ender)
4851                  (eq (preceding-char)
4852                      (char-after (- (point) 2)))
4853                  (save-excursion
4854                    (forward-char -2)
4855                    (= 0 (% (skip-chars-backward "\\\\") 2)))
4856                  (forward-char -1)))
4857           ;; Now we are after the first part.
4858           (and is-2arg                  ; Have trailing part
4859                (not ender)
4860                (eq (following-char) starter) ; Empty trailing part
4861                (progn
4862                  (or (eq (char-syntax (following-char)) ?.)
4863                      ;; Make trailing letter into punctuation
4864                      (cperl-modify-syntax-type (point) cperl-st-punct))
4865                  (setq is-2arg nil go-forward t))) ; Ignore the tail
4866           (if is-2arg                   ; Not number => have second part
4867               (progn
4868                 (setq i (point) i2 i)
4869                 (if ender
4870                     (if (memq (following-char) '(?\  ?\t ?\n ?\f))
4871                         (progn
4872                           (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4873                               (goto-char (match-end 0))
4874                             (skip-chars-forward " \t\n\f"))
4875                           (setq i2 (point))))
4876                   (forward-char -1))
4877                 (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4878                 (if ender (modify-syntax-entry ender "." st))
4879                 (setq set-st nil)
4880                 (setq ender (cperl-forward-re lim end nil st-l err-l
4881                                               argument starter ender)
4882                       ender (nth 2 ender)))))
4883       (error (goto-char lim)
4884              (setq set-st nil)
4885              (if reset-st
4886                  (set-syntax-table reset-st))
4887              (or end
4888                  (message
4889                   "End of `%s%s%c ... %c' string/RE not found: %s"
4890                   argument
4891                   (if ostart (format "%c ... %c" ostart (or oend ostart)) "")
4892                   starter (or ender starter) bb)
4893                  (or (car err-l) (setcar err-l b)))))
4894     (if set-st
4895         (progn
4896           (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4897           (if ender (modify-syntax-entry ender "." st))))
4898     ;; i: have 2 args, after end of the first arg
4899     ;; i2: start of the second arg, if any (before delim iff `ender').
4900     ;; ender: the last arg bounded by parens-like chars, the second one of them
4901     ;; starter: the starting delimiter of the first arg
4902     ;; go-forward: has 2 args, and the second part is empty
4903     (list i i2 ender starter go-forward)))
4904
4905 (defun cperl-forward-group-in-re (&optional st-l)
4906   "Find the end of a group in a REx.
4907 Return the error message (if any).  Does not work if delimiter is `)'.
4908 Works before syntax recognition is done."
4909   ;; Works *before* syntax recognition is done
4910   (or st-l (setq st-l (list nil)))      ; Avoid overwriting '()
4911   (let (st b reset-st)
4912     (condition-case b
4913         (progn
4914           (setq st (cperl-cached-syntax-table st-l))
4915           (modify-syntax-entry ?\( "()" st)
4916           (modify-syntax-entry ?\) ")(" st)
4917           (setq reset-st (syntax-table))
4918           (set-syntax-table st)
4919           (forward-sexp 1))
4920       (error (message
4921               "cperl-forward-group-in-re: error %s" b)))
4922     ;; now restore the initial state
4923     (if st
4924         (progn
4925           (modify-syntax-entry ?\( "." st)
4926           (modify-syntax-entry ?\) "." st)))
4927     (if reset-st
4928         (set-syntax-table reset-st))
4929     b))
4930
4931
4932 (defvar font-lock-string-face)
4933 ;;(defvar font-lock-reference-face)
4934 (defvar font-lock-constant-face)
4935 (defsubst cperl-postpone-fontification (b e type val &optional now)
4936   ;; Do after syntactic fontification?
4937   (if cperl-syntaxify-by-font-lock
4938       (or now (put-text-property b e 'cperl-postpone (cons type val)))
4939     (put-text-property b e type val)))
4940
4941 ;;; Here is how the global structures (those which cannot be
4942 ;;; recognized locally) are marked:
4943 ;;      a) PODs:
4944 ;;              Start-to-end is marked `in-pod' ==> t
4945 ;;              Each non-literal part is marked `syntax-type' ==> `pod'
4946 ;;              Each literal part is marked `syntax-type' ==> `in-pod'
4947 ;;      b) HEREs:
4948 ;;              Start-to-end is marked `here-doc-group' ==> t
4949 ;;              The body is marked `syntax-type' ==> `here-doc'
4950 ;;              The delimiter is marked `syntax-type' ==> `here-doc-delim'
4951 ;;      c) FORMATs:
4952 ;;              First line (to =) marked `first-format-line' ==> t
4953 ;;              After-this--to-end is marked `syntax-type' ==> `format'
4954 ;;      d) 'Q'uoted string:
4955 ;;              part between markers inclusive is marked `syntax-type' ==> `string'
4956 ;;              part between `q' and the first marker is marked `syntax-type' ==> `prestring'
4957 ;;      e) Attributes of subroutines: `attrib-group' ==> t
4958 ;;              (or 0 if declaration); up to `{' or ';': `syntax-type' => `sub-decl'.
4959 ;;      f) Multiline my/our declaration lists etc: `syntax-type' => `multiline'
4960
4961 ;;; In addition, some parts of RExes may be marked as `REx-interpolated'
4962 ;;; (value: 0 in //o, 1 if "interpolated variable" is whole-REx, t otherwise).
4963
4964 (defun cperl-unwind-to-safe (before &optional end)
4965   ;; if BEFORE, go to the previous start-of-line on each step of unwinding
4966   (let ((pos (point)) opos)
4967     (while (and pos (progn
4968                       (beginning-of-line)
4969                       (get-text-property (setq pos (point)) 'syntax-type)))
4970       (setq opos pos
4971             pos (cperl-beginning-of-property pos 'syntax-type))
4972       (if (eq pos (point-min))
4973           (setq pos nil))
4974       (if pos
4975           (if before
4976               (progn
4977                 (goto-char (cperl-1- pos))
4978                 (beginning-of-line)
4979                 (setq pos (point)))
4980             (goto-char (setq pos (cperl-1- pos))))
4981         ;; Up to the start
4982         (goto-char (point-min))))
4983     ;; Skip empty lines
4984     (and (looking-at "\n*=")
4985          (/= 0 (skip-chars-backward "\n"))
4986          (forward-char))
4987     (setq pos (point))
4988     (if end
4989         ;; Do the same for end, going small steps
4990         (save-excursion
4991           (while (and end (get-text-property end 'syntax-type))
4992             (setq pos end
4993                   end (next-single-property-change end 'syntax-type nil (point-max)))
4994             (if end (progn (goto-char end)
4995                            (or (bolp) (forward-line 1))
4996                            (setq end (point)))))
4997           (or end pos)))))
4998
4999 ;;; These are needed for byte-compile (at least with v19)
5000 (defvar cperl-nonoverridable-face)
5001 (defvar font-lock-variable-name-face)
5002 (defvar font-lock-function-name-face)
5003 (defvar font-lock-keyword-face)
5004 (defvar font-lock-builtin-face)
5005 (defvar font-lock-type-face)
5006 (defvar font-lock-comment-face)
5007 (defvar font-lock-warning-face)
5008
5009 (defun cperl-find-sub-attrs (&optional st-l b-fname e-fname pos)
5010   "Syntaxically mark (and fontify) attributes of a subroutine.
5011 Should be called with the point before leading colon of an attribute."
5012   ;; Works *before* syntax recognition is done
5013   (or st-l (setq st-l (list nil)))      ; Avoid overwriting '()
5014   (let (st b p reset-st after-first (start (point)) start1 end1)
5015     (condition-case b
5016         (while (looking-at
5017                 (concat
5018                  "\\("                  ; 1=optional? colon
5019                    ":" cperl-maybe-white-and-comment-rex ; 2=whitespace/comment?
5020                  "\\)"
5021                  (if after-first "?" "")
5022                  ;; No space between name and paren allowed...
5023                  "\\(\\sw+\\)"          ; 3=name
5024                  "\\((\\)?"))           ; 4=optional paren
5025           (and (match-beginning 1)
5026                (cperl-postpone-fontification
5027                 (match-beginning 0) (cperl-1+ (match-beginning 0))
5028                 'face font-lock-constant-face))
5029           (setq start1 (match-beginning 3) end1 (match-end 3))
5030           (cperl-postpone-fontification start1 end1
5031                                         'face font-lock-constant-face)
5032           (goto-char end1)              ; end or before `('
5033           (if (match-end 4)             ; Have attribute arguments...
5034               (progn
5035                 (if st nil
5036                   (setq st (cperl-cached-syntax-table st-l))
5037                   (modify-syntax-entry ?\( "()" st)
5038                   (modify-syntax-entry ?\) ")(" st))
5039                 (setq reset-st (syntax-table) p (point))
5040                 (set-syntax-table st)
5041                 (forward-sexp 1)
5042                 (set-syntax-table reset-st)
5043                 (setq reset-st nil)
5044                 (cperl-commentify p (point) t))) ; mark as string
5045           (forward-comment (buffer-size))
5046           (setq after-first t))
5047       (error (message
5048               "L%d: attribute `%s': %s"
5049               (count-lines (point-min) (point))
5050               (and start1 end1 (buffer-substring start1 end1)) b)
5051              (setq start nil)))
5052     (and start
5053          (progn
5054            (put-text-property start (point)
5055                               'attrib-group (if (looking-at "{") t 0))
5056            (and pos
5057                 (< 1 (count-lines (+ 3 pos) (point))) ; end of `sub'
5058                 ;; Apparently, we do not need `multiline': faces added now
5059                 (put-text-property (+ 3 pos) (cperl-1+ (point))
5060                                    'syntax-type 'sub-decl))
5061            (and b-fname                 ; Fontify here: the following condition
5062                 (cperl-postpone-fontification ; is too hard to determine by
5063                  b-fname e-fname 'face ; a REx, so do it here
5064                 (if (looking-at "{")
5065                     font-lock-function-name-face
5066                   font-lock-variable-name-face)))))
5067     ;; now restore the initial state
5068     (if st
5069         (progn
5070           (modify-syntax-entry ?\( "." st)
5071           (modify-syntax-entry ?\) "." st)))
5072     (if reset-st
5073         (set-syntax-table reset-st))))
5074
5075 (defsubst cperl-look-at-leading-count (is-x-REx e)
5076   (if (re-search-forward (concat "\\=" (if is-x-REx "[ \t\n]*" "") "[{?+*]")
5077                          (1- e) t)      ; return nil on failure, no moving
5078       (if (eq ?\{ (preceding-char)) nil
5079         (cperl-postpone-fontification
5080          (1- (point)) (point)
5081          'face font-lock-warning-face))))
5082
5083 ;;; Debugging this may require (setq max-specpdl-size 2000)...
5084 (defun cperl-find-pods-heres (&optional min max non-inter end ignore-max end-of-here-doc)
5085   "Scans the buffer for hard-to-parse Perl constructions.
5086 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify
5087 the sections using `cperl-pod-head-face', `cperl-pod-face',
5088 `cperl-here-face'."
5089   (interactive)
5090  (or min (setq min (point-min)
5091                 cperl-syntax-state nil
5092                 cperl-syntax-done-to min))
5093   (or max (setq max (point-max)))
5094   (let* ((cperl-pod-here-fontify (eval cperl-pod-here-fontify)) go tmpend
5095          face head-face here-face b e bb tag qtag b1 e1 argument i c tail tb
5096          is-REx is-x-REx REx-subgr-start REx-subgr-end was-subgr i2 hairy-RE
5097          (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
5098          (modified (buffer-modified-p)) overshoot is-o-REx
5099          (after-change-functions nil)
5100          (cperl-font-locking t)
5101          (use-syntax-state (and cperl-syntax-state
5102                                 (>= min (car cperl-syntax-state))))
5103          (state-point (if use-syntax-state
5104                           (car cperl-syntax-state)
5105                         (point-min)))
5106          (state (if use-syntax-state
5107                     (cdr cperl-syntax-state)))
5108          ;; (st-l '(nil)) (err-l '(nil)) ; Would overwrite - propagates from a function call to a function call!
5109          (st-l (list nil)) (err-l (list nil))
5110          ;; Somehow font-lock may be not loaded yet...
5111          ;; (e.g., when building TAGS via command-line call)
5112          (font-lock-string-face (if (boundp 'font-lock-string-face)
5113                                     font-lock-string-face
5114                                   'font-lock-string-face))
5115          (my-cperl-delimiters-face (if (boundp 'font-lock-constant-face)
5116                                       font-lock-constant-face
5117                                     'font-lock-constant-face))
5118          (my-cperl-REx-spec-char-face   ; [] ^.$ and wrapper-of ({})
5119           (if (boundp 'font-lock-function-name-face)
5120               font-lock-function-name-face
5121             'font-lock-function-name-face))
5122          (font-lock-variable-name-face  ; interpolated vars and ({})-code
5123           (if (boundp 'font-lock-variable-name-face)
5124               font-lock-variable-name-face
5125             'font-lock-variable-name-face))
5126          (font-lock-function-name-face  ; used in `cperl-find-sub-attrs'
5127           (if (boundp 'font-lock-function-name-face)
5128               font-lock-function-name-face
5129             'font-lock-function-name-face))
5130          (font-lock-constant-face       ; used in `cperl-find-sub-attrs'
5131           (if (boundp 'font-lock-constant-face)
5132               font-lock-constant-face
5133             'font-lock-constant-face))
5134          (my-cperl-REx-0length-face ; 0-length, (?:)etc, non-literal \
5135           (if (boundp 'font-lock-builtin-face)
5136               font-lock-builtin-face
5137             'font-lock-builtin-face))
5138          (font-lock-comment-face
5139           (if (boundp 'font-lock-comment-face)
5140               font-lock-comment-face
5141             'font-lock-comment-face))
5142          (font-lock-warning-face
5143           (if (boundp 'font-lock-warning-face)
5144               font-lock-warning-face
5145             'font-lock-warning-face))
5146          (my-cperl-REx-ctl-face         ; (|)
5147           (if (boundp 'font-lock-keyword-face)
5148               font-lock-keyword-face
5149             'font-lock-keyword-face))
5150          (my-cperl-REx-modifiers-face   ; //gims
5151           (if (boundp 'cperl-nonoverridable-face)
5152               cperl-nonoverridable-face
5153             'cperl-nonoverridable-face))
5154          (my-cperl-REx-length1-face     ; length=1 escaped chars, POSIX classes
5155           (if (boundp 'font-lock-type-face)
5156               font-lock-type-face
5157             'font-lock-type-face))
5158          (stop-point (if ignore-max
5159                          (point-max)
5160                        max))
5161          (search
5162           (concat
5163            "\\(\\`\n?\\|^\n\\)="        ; POD
5164            "\\|"
5165            ;; One extra () before this:
5166            "<<"                         ; HERE-DOC
5167            "\\("                        ; 1 + 1
5168            ;; First variant "BLAH" or just ``.
5169            "[ \t]*"                     ; Yes, whitespace is allowed!
5170            "\\([\"'`]\\)"               ; 2 + 1 = 3
5171            "\\([^\"'`\n]*\\)"           ; 3 + 1
5172            "\\3"
5173            "\\|"
5174            ;; Second variant: Identifier or \ID (same as 'ID') or empty
5175            "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
5176            ;; Do not have <<= or << 30 or <<30 or << $blah.
5177            ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
5178            "\\(\\)"             ; To preserve count of pars :-( 6 + 1
5179            "\\)"
5180            "\\|"
5181            ;; 1+6 extra () before this:
5182            "^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$" ;FRMAT
5183            (if cperl-use-syntax-table-text-property
5184                (concat
5185                 "\\|"
5186                 ;; 1+6+2=9 extra () before this:
5187                 "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>" ; QUOTED CONSTRUCT
5188                 "\\|"
5189                 ;; 1+6+2+1=10 extra () before this:
5190                 "\\([?/<]\\)"   ; /blah/ or ?blah? or <file*glob>
5191                 "\\|"
5192                 ;; 1+6+2+1+1=11 extra () before this
5193                 "\\<sub\\>"             ;  sub with proto/attr
5194                 "\\("
5195                    cperl-white-and-comment-rex
5196                    "\\(::[a-zA-Z_:'0-9]*\\|[a-zA-Z_'][a-zA-Z_:'0-9]*\\)\\)?" ; name
5197                 "\\("
5198                    cperl-maybe-white-and-comment-rex
5199                    "\\(([^()]*)\\|:[^:]\\)\\)" ; prototype or attribute start
5200                 "\\|"
5201                 ;; 1+6+2+1+1+6=17 extra () before this:
5202                 "\\$\\(['{]\\)"         ; $' or ${foo}
5203                 "\\|"
5204                 ;; 1+6+2+1+1+6+1=18 extra () before this (old pack'var syntax;
5205                 ;; we do not support intervening comments...):
5206                 "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'"
5207                 ;; 1+6+2+1+1+6+1+1=19 extra () before this:
5208                 "\\|"
5209                 "__\\(END\\|DATA\\)__"  ; __END__ or __DATA__
5210                 ;; 1+6+2+1+1+6+1+1+1=20 extra () before this:
5211                 "\\|"
5212                 "\\\\\\(['`\"($]\\)")   ; BACKWACKED something-hairy
5213              ""))))
5214     (unwind-protect
5215         (progn
5216           (save-excursion
5217             (or non-inter
5218                 (message "Scanning for \"hard\" Perl constructions..."))
5219             ;;(message "find: %s --> %s" min max)
5220             (and cperl-pod-here-fontify
5221                  ;; We had evals here, do not know why...
5222                  (setq face cperl-pod-face
5223                        head-face cperl-pod-head-face
5224                        here-face cperl-here-face))
5225             (remove-text-properties min max
5226                                     '(syntax-type t in-pod t syntax-table t
5227                                                   attrib-group t
5228                                                   REx-interpolated t
5229                                                   cperl-postpone t
5230                                                   syntax-subtype t
5231                                                   rear-nonsticky t
5232                                                   front-sticky t
5233                                                   here-doc-group t
5234                                                   first-format-line t
5235                                                   REx-part2 t
5236                                                   indentable t))
5237             ;; Need to remove face as well...
5238             (goto-char min)
5239             (and (eq system-type 'emx)
5240                  (eq (point) 1)
5241                  (let ((case-fold-search t))
5242                    (looking-at "extproc[ \t]")) ; Analogue of #!
5243                  (cperl-commentify min
5244                                    (save-excursion (end-of-line) (point))
5245                                    nil))
5246             (while (and
5247                     (< (point) max)
5248                     (re-search-forward search max t))
5249               (setq tmpend nil)         ; Valid for most cases
5250               (setq b (match-beginning 0)
5251                     state (save-excursion (parse-partial-sexp
5252                                            state-point b nil nil state))
5253                     state-point b)
5254               (cond
5255                ;; 1+6+2+1+1+6=17 extra () before this:
5256                ;;    "\\$\\(['{]\\)"
5257                ((match-beginning 18) ; $' or ${foo}
5258                 (if (eq (preceding-char) ?\') ; $'
5259                     (progn
5260                       (setq b (1- (point))
5261                             state (parse-partial-sexp
5262                                    state-point (1- b) nil nil state)
5263                             state-point (1- b))
5264                       (if (nth 3 state) ; in string
5265                           (cperl-modify-syntax-type (1- b) cperl-st-punct))
5266                       (goto-char (1+ b)))
5267                   ;; else: ${
5268                   (setq bb (match-beginning 0))
5269                   (cperl-modify-syntax-type bb cperl-st-punct)))
5270                ;; No processing in strings/comments beyond this point:
5271                ((or (nth 3 state) (nth 4 state))
5272                 t)                      ; Do nothing in comment/string
5273                ((match-beginning 1)     ; POD section
5274                 ;;  "\\(\\`\n?\\|^\n\\)="
5275                 (setq b (match-beginning 0)
5276                       state (parse-partial-sexp
5277                              state-point b nil nil state)
5278                       state-point b)
5279                 (if (or (nth 3 state) (nth 4 state)
5280                         (looking-at "cut\\>"))
5281                     (if (or (nth 3 state) (nth 4 state) ignore-max)
5282                         nil             ; Doing a chunk only
5283                       (message "=cut is not preceded by a POD section")
5284                       (or (car err-l) (setcar err-l (point))))
5285                   (beginning-of-line)
5286
5287                   (setq b (point)
5288                         bb b
5289                         tb (match-beginning 0)
5290                         b1 nil)         ; error condition
5291                   ;; We do not search to max, since we may be called from
5292                   ;; some hook of fontification, and max is random
5293                   (or (re-search-forward "^\n=cut\\>" stop-point 'toend)
5294                       (progn
5295                         (goto-char b)
5296                         (if (re-search-forward "\n=cut\\>" stop-point 'toend)
5297                             (progn
5298                               (message "=cut is not preceded by an empty line")
5299                               (setq b1 t)
5300                               (or (car err-l) (setcar err-l b))))))
5301                   (beginning-of-line 2) ; An empty line after =cut is not POD!
5302                   (setq e (point))
5303                   (and (> e max)
5304                        (progn
5305                          (remove-text-properties
5306                           max e '(syntax-type t in-pod t syntax-table t
5307                                               attrib-group t
5308                                               REx-interpolated t
5309                                               cperl-postpone t
5310                                               syntax-subtype t
5311                                               here-doc-group t
5312                                               rear-nonsticky t
5313                                               front-sticky t
5314                                               first-format-line t
5315                                               REx-part2 t
5316                                               indentable t))
5317                          (setq tmpend tb)))
5318                   (put-text-property b e 'in-pod t)
5319                   (put-text-property b e 'syntax-type 'in-pod)
5320                   (goto-char b)
5321                   (while (re-search-forward "\n\n[ \t]" e t)
5322                     ;; We start 'pod 1 char earlier to include the preceding line
5323                     (beginning-of-line)
5324                     (put-text-property (cperl-1- b) (point) 'syntax-type 'pod)
5325                     (cperl-put-do-not-fontify b (point) t)
5326                     ;; mark the non-literal parts as PODs
5327                     (if cperl-pod-here-fontify
5328                         (cperl-postpone-fontification b (point) 'face face t))
5329                     (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
5330                     (beginning-of-line)
5331                     (setq b (point)))
5332                   (put-text-property (cperl-1- (point)) e 'syntax-type 'pod)
5333                   (cperl-put-do-not-fontify (point) e t)
5334                   (if cperl-pod-here-fontify
5335                       (progn
5336                         ;; mark the non-literal parts as PODs
5337                         (cperl-postpone-fontification (point) e 'face face t)
5338                         (goto-char bb)
5339                         (if (looking-at
5340                              "=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
5341                             ;; mark the headers
5342                             (cperl-postpone-fontification
5343                              (match-beginning 1) (match-end 1)
5344                              'face head-face))
5345                         (while (re-search-forward
5346                                 ;; One paragraph
5347                                 "^\n=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
5348                                 e 'toend)
5349                           ;; mark the headers
5350                           (cperl-postpone-fontification
5351                            (match-beginning 1) (match-end 1)
5352                            'face head-face))))
5353                   (cperl-commentify bb e nil)
5354                   (goto-char e)
5355                   (or (eq e (point-max))
5356                       (forward-char -1)))) ; Prepare for immediate POD start.
5357                ;; Here document
5358                ;; We can do many here-per-line;
5359                ;; but multiline quote on the same line as <<HERE confuses us...
5360                ;; ;; One extra () before this:
5361                ;;"<<"
5362                ;;  "\\("                        ; 1 + 1
5363                ;;  ;; First variant "BLAH" or just ``.
5364                ;;     "[ \t]*"                  ; Yes, whitespace is allowed!
5365                ;;     "\\([\"'`]\\)"    ; 2 + 1
5366                ;;     "\\([^\"'`\n]*\\)"        ; 3 + 1
5367                ;;     "\\3"
5368                ;;  "\\|"
5369                ;;  ;; Second variant: Identifier or \ID or empty
5370                ;;    "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
5371                ;;    ;; Do not have <<= or << 30 or <<30 or << $blah.
5372                ;;    ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
5373                ;;    "\\(\\)"           ; To preserve count of pars :-( 6 + 1
5374                ;;  "\\)"
5375                ((match-beginning 2)     ; 1 + 1
5376                 (setq b (point)
5377                       tb (match-beginning 0)
5378                       c (and            ; not HERE-DOC
5379                          (match-beginning 5)
5380                          (save-match-data
5381                            (or (looking-at "[ \t]*(") ; << function_call()
5382                                (save-excursion ; 1 << func_name, or $foo << 10
5383                                  (condition-case nil
5384                                      (progn
5385                                        (goto-char tb)
5386                ;;; XXX What to do: foo <<bar ???
5387                ;;; XXX Need to support print {a} <<B ???
5388                                        (forward-sexp -1)
5389                                        (save-match-data 
5390                                         ; $foo << b; $f .= <<B;
5391                                         ; ($f+1) << b; a($f) . <<B;
5392                                         ; foo 1, <<B; $x{a} <<b;
5393                                          (cond
5394                                           ((looking-at "[0-9$({]")
5395                                            (forward-sexp 1)
5396                                            (and
5397                                             (looking-at "[ \t]*<<")
5398                                             (condition-case nil
5399                                                 ;; print $foo <<EOF
5400                                                 (progn
5401                                                   (forward-sexp -2)
5402                                                   (not
5403                                                    (looking-at "print\\>")))
5404                                                 (error t)))))))
5405                                    (error nil))) ; func(<<EOF)
5406                                (and (not (match-beginning 6)) ; Empty
5407                                     (looking-at
5408                                      "[ \t]*[=0-9$@%&(]"))))))
5409                 (if c                   ; Not here-doc
5410                     nil                 ; Skip it.
5411                   (setq c (match-end 2)) ; 1 + 1
5412                   (if (match-beginning 5) ;4 + 1
5413                       (setq b1 (match-beginning 5) ; 4 + 1
5414                             e1 (match-end 5)) ; 4 + 1
5415                     (setq b1 (match-beginning 4) ; 3 + 1
5416                           e1 (match-end 4))) ; 3 + 1
5417                   (setq tag (buffer-substring b1 e1)
5418                         qtag (regexp-quote tag))
5419                   (cond (cperl-pod-here-fontify
5420                          ;; Highlight the starting delimiter
5421                          (cperl-postpone-fontification 
5422                           b1 e1 'face my-cperl-delimiters-face)
5423                          (cperl-put-do-not-fontify b1 e1 t)))
5424                   (forward-line)
5425                   (setq i (point))
5426                   (if end-of-here-doc
5427                       (goto-char end-of-here-doc))
5428                   (setq b (point))
5429                   ;; We do not search to max, since we may be called from
5430                   ;; some hook of fontification, and max is random
5431                   (or (and (re-search-forward (concat "^" qtag "$")
5432                                               stop-point 'toend)
5433                            (eq (following-char) ?\n))
5434                     (progn              ; Pretend we matched at the end
5435                       (goto-char (point-max))
5436                       (re-search-forward "\\'")
5437                       (message "End of here-document `%s' not found." tag)
5438                       (or (car err-l) (setcar err-l b))))
5439                   (if cperl-pod-here-fontify
5440                       (progn
5441                         ;; Highlight the ending delimiter
5442                         (cperl-postpone-fontification
5443                          (match-beginning 0) (match-end 0)
5444                          'face my-cperl-delimiters-face)
5445                         (cperl-put-do-not-fontify b (match-end 0) t)
5446                         ;; Highlight the HERE-DOC
5447                         (cperl-postpone-fontification b (match-beginning 0)
5448                                                       'face here-face)))
5449                   (setq e1 (cperl-1+ (match-end 0)))
5450                   (put-text-property b (match-beginning 0)
5451                                      'syntax-type 'here-doc)
5452                   (put-text-property (match-beginning 0) e1
5453                                      'syntax-type 'here-doc-delim)
5454                   (put-text-property b e1 'here-doc-group t)
5455                   ;; This makes insertion at the start of HERE-DOC update
5456                   ;; the whole construct:
5457                   (put-text-property b (cperl-1+ b) 'front-sticky '(syntax-type))
5458                   (cperl-commentify b e1 nil)
5459                   (cperl-put-do-not-fontify b (match-end 0) t)
5460                   ;; Cache the syntax info...
5461                   (setq cperl-syntax-state (cons state-point state))
5462                   ;; ... and process the rest of the line...
5463                   (setq overshoot
5464                         (elt            ; non-inter ignore-max
5465                          (cperl-find-pods-heres c i t end t e1) 1))
5466                   (if (and overshoot (> overshoot (point)))
5467                       (goto-char overshoot)
5468                     (setq overshoot e1))
5469                   (if (> e1 max)
5470                       (setq tmpend tb))))
5471                ;; format
5472                ((match-beginning 8)
5473                 ;; 1+6=7 extra () before this:
5474                 ;;"^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
5475                 (setq b (point)
5476                       name (if (match-beginning 8) ; 7 + 1
5477                                (buffer-substring (match-beginning 8) ; 7 + 1
5478                                                  (match-end 8)) ; 7 + 1
5479                              "")
5480                       tb (match-beginning 0))
5481                 (setq argument nil)
5482                 (put-text-property (save-excursion
5483                                      (beginning-of-line)
5484                                      (point))
5485                                    b 'first-format-line 't)
5486                 (if cperl-pod-here-fontify
5487                     (while (and (eq (forward-line) 0)
5488                                 (not (looking-at "^[.;]$")))
5489                       (cond
5490                        ((looking-at "^#")) ; Skip comments
5491                        ((and argument   ; Skip argument multi-lines
5492                              (looking-at "^[ \t]*{"))
5493                         (forward-sexp 1)
5494                         (setq argument nil))
5495                        (argument        ; Skip argument lines
5496                         (setq argument nil))
5497                        (t               ; Format line
5498                         (setq b1 (point))
5499                         (setq argument (looking-at "^[^\n]*[@^]"))
5500                         (end-of-line)
5501                         ;; Highlight the format line
5502                         (cperl-postpone-fontification b1 (point)
5503                                                       'face font-lock-string-face)
5504                         (cperl-commentify b1 (point) nil)
5505                         (cperl-put-do-not-fontify b1 (point) t))))
5506                   ;; We do not search to max, since we may be called from
5507                   ;; some hook of fontification, and max is random
5508                   (re-search-forward "^[.;]$" stop-point 'toend))
5509                 (beginning-of-line)
5510                 (if (looking-at "^\\.$") ; ";" is not supported yet
5511                     (progn
5512                       ;; Highlight the ending delimiter
5513                       (cperl-postpone-fontification (point) (+ (point) 2)
5514                                                     'face font-lock-string-face)
5515                       (cperl-commentify (point) (+ (point) 2) nil)
5516                       (cperl-put-do-not-fontify (point) (+ (point) 2) t))
5517                   (message "End of format `%s' not found." name)
5518                   (or (car err-l) (setcar err-l b)))
5519                 (forward-line)
5520                 (if (> (point) max)
5521                     (setq tmpend tb))
5522                 (put-text-property b (point) 'syntax-type 'format))
5523                ;; qq-like String or Regexp:
5524                ((or (match-beginning 10) (match-beginning 11))
5525                 ;; 1+6+2=9 extra () before this:
5526                 ;; "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>"
5527                 ;; "\\|"
5528                 ;; "\\([?/<]\\)"        ; /blah/ or ?blah? or <file*glob>
5529                 (setq b1 (if (match-beginning 10) 10 11)
5530                       argument (buffer-substring
5531                                 (match-beginning b1) (match-end b1))
5532                       b (point)         ; end of qq etc
5533                       i b
5534                       c (char-after (match-beginning b1))
5535                       bb (char-after (1- (match-beginning b1))) ; tmp holder
5536                       ;; bb == "Not a stringy"
5537                       bb (if (eq b1 10) ; user variables/whatever
5538                              (and (memq bb (append "$@%*#_:-&>" nil)) ; $#y)
5539                                   (cond ((eq bb ?-) (eq c ?s)) ; -s file test
5540                                         ((eq bb ?\:) ; $opt::s
5541                                          (eq (char-after
5542                                               (- (match-beginning b1) 2))
5543                                              ?\:))
5544                                         ((eq bb ?\>) ; $foo->s
5545                                          (eq (char-after
5546                                               (- (match-beginning b1) 2))
5547                                              ?\-))
5548                                         ((eq bb ?\&)
5549                                          (not (eq (char-after ; &&m/blah/
5550                                                    (- (match-beginning b1) 2))
5551                                                   ?\&)))
5552                                         (t t)))
5553                            ;; <file> or <$file>
5554                            (and (eq c ?\<)
5555                                 ;; Do not stringify <FH>, <$fh> :
5556                                 (save-match-data
5557                                   (looking-at
5558                                    "\\$?\\([_a-zA-Z:][_a-zA-Z0-9:]*\\)?>"))))
5559                       tb (match-beginning 0))
5560                 (goto-char (match-beginning b1))
5561                 (cperl-backward-to-noncomment (point-min))
5562                 (or bb
5563                     (if (eq b1 11)      ; bare /blah/ or ?blah? or <foo>
5564                         (setq argument ""
5565                               b1 nil
5566                               bb        ; Not a regexp?
5567                               (not
5568                                ;; What is below: regexp-p?
5569                                (and
5570                                 (or (memq (preceding-char)
5571                                           (append (if (memq c '(?\? ?\<))
5572                                                       ;; $a++ ? 1 : 2
5573                                                       "~{(=|&*!,;:["
5574                                                     "~{(=|&+-*!,;:[") nil))
5575                                     (and (eq (preceding-char) ?\})
5576                                          (cperl-after-block-p (point-min)))
5577                                     (and (eq (char-syntax (preceding-char)) ?w)
5578                                          (progn
5579                                            (forward-sexp -1)
5580 ;;; After these keywords `/' starts a RE.  One should add all the
5581 ;;; functions/builtins which expect an argument, but ...
5582                                            (if (eq (preceding-char) ?-)
5583                                                ;; -d ?foo? is a RE
5584                                                (looking-at "[a-zA-Z]\\>")
5585                                              (and
5586                                               (not (memq (preceding-char)
5587                                                          '(?$ ?@ ?& ?%)))
5588                                               (looking-at
5589                                                "\\(while\\|if\\|unless\\|until\\|and\\|or\\|not\\|xor\\|split\\|grep\\|map\\|print\\)\\>")))))
5590                                     (and (eq (preceding-char) ?.)
5591                                          (eq (char-after (- (point) 2)) ?.))
5592                                     (bobp))
5593                                 ;;  m|blah| ? foo : bar;
5594                                 (not
5595                                  (and (eq c ?\?)
5596                                       cperl-use-syntax-table-text-property
5597                                       (not (bobp))
5598                                       (progn
5599                                         (forward-char -1)
5600                                         (looking-at "\\s|"))))))
5601                               b (1- b))
5602                       ;; s y tr m
5603                       ;; Check for $a -> y
5604                       (setq b1 (preceding-char)
5605                             go (point))
5606                       (if (and (eq b1 ?>)
5607                                (eq (char-after (- go 2)) ?-))
5608                           ;; Not a regexp
5609                           (setq bb t))))
5610                 (or bb
5611                     (progn
5612                       (goto-char b)
5613                       (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
5614                           (goto-char (match-end 0))
5615                         (skip-chars-forward " \t\n\f"))
5616                       (cond ((and (eq (following-char) ?\})
5617                                   (eq b1 ?\{))
5618                              ;; Check for $a[23]->{ s }, @{s} and *{s::foo}
5619                              (goto-char (1- go))
5620                              (skip-chars-backward " \t\n\f")
5621                              (if (memq (preceding-char) (append "$@%&*" nil))
5622                                  (setq bb t) ; @{y}
5623                                (condition-case nil
5624                                    (forward-sexp -1)
5625                                  (error nil)))
5626                              (if (or bb
5627                                      (looking-at ; $foo -> {s}
5628                                       "[$@]\\$*\\([a-zA-Z0-9_:]+\\|[^{]\\)\\([ \t\n]*->\\)?[ \t\n]*{")
5629                                      (and ; $foo[12] -> {s}
5630                                       (memq (following-char) '(?\{ ?\[))
5631                                       (progn
5632                                         (forward-sexp 1)
5633                                         (looking-at "\\([ \t\n]*->\\)?[ \t\n]*{"))))
5634                                  (setq bb t)
5635                                (goto-char b)))
5636                             ((and (eq (following-char) ?=)
5637                                   (eq (char-after (1+ (point))) ?\>))
5638                              ;; Check for { foo => 1, s => 2 }
5639                              ;; Apparently s=> is never a substitution...
5640                              (setq bb t))
5641                             ((and (eq (following-char) ?:)
5642                                   (eq b1 ?\{) ; Check for $ { s::bar }
5643                                   (looking-at "::[a-zA-Z0-9_:]*[ \t\n\f]*}")
5644                                   (progn
5645                                     (goto-char (1- go))
5646                                     (skip-chars-backward " \t\n\f")
5647                                     (memq (preceding-char)
5648                                           (append "$@%&*" nil))))
5649                              (setq bb t))
5650                             ((eobp)
5651                              (setq bb t)))))
5652                 (if bb
5653                     (goto-char i)
5654                   ;; Skip whitespace and comments...
5655                   (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
5656                       (goto-char (match-end 0))
5657                     (skip-chars-forward " \t\n\f"))
5658                   (if (> (point) b)
5659                       (put-text-property b (point) 'syntax-type 'prestring))
5660                   ;; qtag means two-arg matcher, may be reset to
5661                   ;;   2 or 3 later if some special quoting is needed.
5662                   ;; e1 means matching-char matcher.
5663                   (setq b (point)       ; before the first delimiter
5664                         ;; has 2 args
5665                         i2 (string-match "^\\([sy]\\|tr\\)$" argument)
5666                         ;; We do not search to max, since we may be called from
5667                         ;; some hook of fontification, and max is random
5668                         i (cperl-forward-re stop-point end
5669                                             i2
5670                                             st-l err-l argument)
5671                         ;; If `go', then it is considered as 1-arg, `b1' is nil
5672                         ;; as in s/foo//x; the point is before final "slash"
5673                         b1 (nth 1 i)    ; start of the second part
5674                         tag (nth 2 i)   ; ender-char, true if second part
5675                                         ; is with matching chars []
5676                         go (nth 4 i)    ; There is a 1-char part after the end
5677                         i (car i)       ; intermediate point
5678                         e1 (point)      ; end
5679                         ;; Before end of the second part if non-matching: ///
5680                         tail (if (and i (not tag))
5681                                  (1- e1))
5682                         e (if i i e1)   ; end of the first part
5683                         qtag nil        ; need to preserve backslashitis
5684                         is-x-REx nil is-o-REx nil); REx has //x //o modifiers
5685                   ;; If s{} (), then b/b1 are at "{", "(", e1/i after ")", "}"
5686                   ;; Commenting \\ is dangerous, what about ( ?
5687                   (and i tail
5688                        (eq (char-after i) ?\\)
5689                        (setq qtag t))
5690                   (and (if go (looking-at ".\\sw*x")
5691                          (looking-at "\\sw*x")) ; qr//x
5692                        (setq is-x-REx t))
5693                   (and (if go (looking-at ".\\sw*o")
5694                          (looking-at "\\sw*o")) ; //o
5695                        (setq is-o-REx t))
5696                   (if (null i)
5697                       ;; Considered as 1arg form
5698                       (progn
5699                         (cperl-commentify b (point) t)
5700                         (put-text-property b (point) 'syntax-type 'string)
5701                         (if (or is-x-REx
5702                                 ;; ignore other text properties:
5703                                 (string-match "^qw$" argument))
5704                             (put-text-property b (point) 'indentable t))
5705                         (and go
5706                              (setq e1 (cperl-1+ e1))
5707                              (or (eobp)
5708                                  (forward-char 1))))
5709                     (cperl-commentify b i t)
5710                     (if (looking-at "\\sw*e") ; s///e
5711                         (progn
5712                           ;; Cache the syntax info...
5713                           (setq cperl-syntax-state (cons state-point state))
5714                           (and
5715                            ;; silent:
5716                            (car (cperl-find-pods-heres b1 (1- (point)) t end))
5717                            ;; Error
5718                            (goto-char (1+ max)))
5719                           (if (and tag (eq (preceding-char) ?\>))
5720                               (progn
5721                                 (cperl-modify-syntax-type (1- (point)) cperl-st-ket)
5722                                 (cperl-modify-syntax-type i cperl-st-bra)))
5723                           (put-text-property b i 'syntax-type 'string)
5724                           (if is-x-REx
5725                               (put-text-property b i 'indentable t)))
5726                       (cperl-commentify b1 (point) t)
5727                       (put-text-property b (point) 'syntax-type 'string)
5728                       (if is-x-REx
5729                           (put-text-property b i 'indentable t))
5730                       (if qtag
5731                           (cperl-modify-syntax-type (1+ i) cperl-st-punct))
5732                       (setq tail nil)))
5733                   ;; Now: tail: if the second part is non-matching without ///e
5734                   (if (eq (char-syntax (following-char)) ?w)
5735                       (progn
5736                         (forward-word 1) ; skip modifiers s///s
5737                         (if tail (cperl-commentify tail (point) t))
5738                         (cperl-postpone-fontification
5739                          e1 (point) 'face my-cperl-REx-modifiers-face)))
5740                   ;; Check whether it is m// which means "previous match"
5741                   ;; and highlight differently
5742                   (setq is-REx
5743                         (and (string-match "^\\([sm]?\\|qr\\)$" argument)
5744                              (or (not (= (length argument) 0))
5745                                  (not (eq c ?\<)))))
5746                   (if (and is-REx
5747                            (eq e (+ 2 b))
5748                            ;; split // *is* using zero-pattern
5749                            (save-excursion
5750                              (condition-case nil
5751                                  (progn
5752                                    (goto-char tb)
5753                                    (forward-sexp -1)
5754                                    (not (looking-at "split\\>")))
5755                                (error t))))
5756                       (cperl-postpone-fontification
5757                        b e 'face font-lock-warning-face)
5758                     (if (or i2          ; Has 2 args
5759                             (and cperl-fontify-m-as-s
5760                                  (or
5761                                   (string-match "^\\(m\\|qr\\)$" argument)
5762                                   (and (eq 0 (length argument))
5763                                        (not (eq ?\< (char-after b)))))))
5764                         (progn
5765                           (cperl-postpone-fontification
5766                            b (cperl-1+ b) 'face my-cperl-delimiters-face)
5767                           (cperl-postpone-fontification
5768                            (1- e) e 'face my-cperl-delimiters-face)))
5769                     (if (and is-REx cperl-regexp-scan)
5770                         ;; Process RExen: embedded comments, charclasses and ]
5771 ;;;/\3333\xFg\x{FFF}a\ppp\PPP\qqq\C\99f(?{  foo  })(??{  foo  })/;
5772 ;;;/a\.b[^a[:ff:]b]x$ab->$[|$,$ab->[cd]->[ef]|$ab[xy].|^${a,b}{c,d}/;
5773 ;;;/(?<=foo)(?<!bar)(x)(?:$ab|\$\/)$|\\\b\x888\776\[\:$/xxx;
5774 ;;;m?(\?\?{b,a})? + m/(??{aa})(?(?=xx)aa|bb)(?#aac)/;
5775 ;;;m$(^ab[c]\$)$ + m+(^ab[c]\$\+)+ + m](^ab[c\]$|.+)] + m)(^ab[c]$|.+\));
5776 ;;;m^a[\^b]c^ + m.a[^b]\.c.;
5777                         (save-excursion
5778                           (goto-char (1+ b))
5779                           ;; First 
5780                           (cperl-look-at-leading-count is-x-REx e)
5781                           (setq hairy-RE
5782                                 (concat
5783                                  (if is-x-REx
5784                                      (if (eq (char-after b) ?\#)
5785                                          "\\((\\?\\\\#\\)\\|\\(\\\\#\\)"
5786                                        "\\((\\?#\\)\\|\\(#\\)")
5787                                    ;; keep the same count: add a fake group
5788                                    (if (eq (char-after b) ?\#)
5789                                        "\\((\\?\\\\#\\)\\(\\)"
5790                                      "\\((\\?#\\)\\(\\)"))
5791                                  "\\|"
5792                                     "\\(\\[\\)" ; 3=[
5793                                  "\\|"
5794                                     "\\(]\\)" ; 4=]
5795                                  "\\|"
5796                                  ;; XXXX Will not be able to use it in s)))
5797                                  (if (eq (char-after b) ?\) )
5798                                      "\\())))\\)" ; Will never match
5799                                    (if (eq (char-after b) ?? )
5800                                        ;;"\\((\\\\\\?\\(\\\\\\?\\)?{\\)"
5801                                        "\\((\\\\\\?\\\\\\?{\\|()\\\\\\?{\\)"
5802                                      "\\((\\?\\??{\\)")) ; 5= (??{ (?{
5803                                  "\\|"  ; 6= 0-length, 7: name, 8,9:code, 10:group
5804                                     "\\(" ;; XXXX 1-char variables, exc. |()\s
5805                                        "[$@]"
5806                                        "\\("
5807                                           "[_a-zA-Z:][_a-zA-Z0-9:]*"
5808                                        "\\|"
5809                                           "{[^{}]*}" ; only one-level allowed
5810                                        "\\|"
5811                                           "[^{(|) \t\r\n\f]"
5812                                        "\\)"
5813                                        "\\(" ;;8,9:code part of array/hash elt
5814                                           "\\(" "->" "\\)?"
5815                                           "\\[[^][]*\\]"
5816                                           "\\|"
5817                                           "{[^{}]*}"
5818                                        "\\)*"
5819                                     ;; XXXX: what if u is delim?
5820                                     "\\|"
5821                                        "[)^|$.*?+]"
5822                                     "\\|"
5823                                        "{[0-9]+}"
5824                                     "\\|"
5825                                        "{[0-9]+,[0-9]*}"
5826                                     "\\|"
5827                                        "\\\\[luLUEQbBAzZG]"
5828                                     "\\|"
5829                                        "(" ; Group opener
5830                                        "\\(" ; 10 group opener follower
5831                                           "\\?\\((\\?\\)" ; 11: in (?(?=C)A|B)
5832                                        "\\|"
5833                                           "\\?[:=!>?{]" ; "?" something
5834                                        "\\|"
5835                                           "\\?[-imsx]+[:)]" ; (?i) (?-s:.)
5836                                        "\\|"
5837                                           "\\?([0-9]+)" ; (?(1)foo|bar)
5838                                        "\\|"
5839                                           "\\?<[=!]"
5840                                        ;;;"\\|"
5841                                        ;;;   "\\?"
5842                                        "\\)?"
5843                                     "\\)"
5844                                  "\\|"
5845                                     "\\\\\\(.\\)" ; 12=\SYMBOL
5846                                  ))
5847                           (while
5848                               (and (< (point) (1- e))
5849                                    (re-search-forward hairy-RE (1- e) 'to-end))
5850                             (goto-char (match-beginning 0))
5851                             (setq REx-subgr-start (point)
5852                                   was-subgr (following-char))
5853                             (cond
5854                              ((match-beginning 6) ; 0-length builtins, groups
5855                               (goto-char (match-end 0))
5856                               (if (match-beginning 11)
5857                                   (goto-char (match-beginning 11)))
5858                               (if (>= (point) e)
5859                                   (goto-char (1- e)))
5860                               (cperl-postpone-fontification
5861                                (match-beginning 0) (point)
5862                                'face
5863                                (cond
5864                                 ((eq was-subgr ?\) )
5865                                  (condition-case nil
5866                                      (save-excursion
5867                                        (forward-sexp -1)
5868                                        (if (> (point) b)
5869                                            (if (if (eq (char-after b) ?? )
5870                                                    (looking-at "(\\\\\\?")
5871                                                  (eq (char-after (1+ (point))) ?\?))
5872                                                my-cperl-REx-0length-face
5873                                              my-cperl-REx-ctl-face)
5874                                          font-lock-warning-face))
5875                                    (error font-lock-warning-face)))
5876                                 ((eq was-subgr ?\| )
5877                                  my-cperl-REx-ctl-face)
5878                                 ((eq was-subgr ?\$ )
5879                                  (if (> (point) (1+ REx-subgr-start))
5880                                      (progn
5881                                        (put-text-property
5882                                         (match-beginning 0) (point)
5883                                         'REx-interpolated
5884                                         (if is-o-REx 0
5885                                             (if (and (eq (match-beginning 0)
5886                                                          (1+ b))
5887                                                      (eq (point)
5888                                                          (1- e))) 1 t)))
5889                                        font-lock-variable-name-face)
5890                                    my-cperl-REx-spec-char-face))
5891                                 ((memq was-subgr (append "^." nil) )
5892                                  my-cperl-REx-spec-char-face)
5893                                 ((eq was-subgr ?\( )
5894                                  (if (not (match-beginning 10))
5895                                      my-cperl-REx-ctl-face
5896                                    my-cperl-REx-0length-face))
5897                                 (t my-cperl-REx-0length-face)))
5898                               (if (and (memq was-subgr (append "(|" nil))
5899                                        (not (string-match "(\\?[-imsx]+)"
5900                                                           (match-string 0))))
5901                                   (cperl-look-at-leading-count is-x-REx e))
5902                               (setq was-subgr nil)) ; We do stuff here
5903                              ((match-beginning 12) ; \SYMBOL
5904                               (forward-char 2)
5905                               (if (>= (point) e)
5906                                   (goto-char (1- e))
5907                                 ;; How many chars to not highlight:
5908                                 ;; 0-len special-alnums in other branch =>
5909                                 ;; Generic:  \non-alnum (1), \alnum (1+face)
5910                                 ;; Is-delim: \non-alnum (1/spec-2) alnum-1 (=what hai)
5911                                 (setq REx-subgr-start (point)
5912                                       qtag (preceding-char))
5913                                 (cperl-postpone-fontification
5914                                  (- (point) 2) (- (point) 1) 'face
5915                                  (if (memq qtag
5916                                            (append "ghijkmoqvFHIJKMORTVY" nil))
5917                                      font-lock-warning-face
5918                                    my-cperl-REx-0length-face))
5919                                 (if (and (eq (char-after b) qtag)
5920                                          (memq qtag (append ".])^$|*?+" nil)))
5921                                     (progn
5922                                       (if (and cperl-use-syntax-table-text-property
5923                                                (eq qtag ?\) ))
5924                                           (put-text-property
5925                                            REx-subgr-start (1- (point))
5926                                            'syntax-table cperl-st-punct))
5927                                       (cperl-postpone-fontification
5928                                        (1- (point)) (point) 'face
5929                                         ; \] can't appear below
5930                                        (if (memq qtag (append ".]^$" nil))
5931                                            'my-cperl-REx-spec-char-face
5932                                          (if (memq qtag (append "*?+" nil))
5933                                              'my-cperl-REx-0length-face
5934                                            'my-cperl-REx-ctl-face))))) ; )|
5935                                 ;; Test for arguments:
5936                                 (cond
5937                                  ;; This is not pretty: the 5.8.7 logic:
5938                                  ;; \0numx  -> octal (up to total 3 dig)
5939                                  ;; \DIGIT  -> backref unless \0
5940                                  ;; \DIGITs -> backref if legal
5941                                  ;;          otherwise up to 3 -> octal
5942                                  ;; Do not try to distinguish, we guess
5943                                  ((or (and (memq qtag (append "01234567" nil))
5944                                            (re-search-forward
5945                                             "\\=[01234567]?[01234567]?"
5946                                             (1- e) 'to-end))
5947                                       (and (memq qtag (append "89" nil))
5948                                            (re-search-forward 
5949                                             "\\=[0123456789]*" (1- e) 'to-end))
5950                                       (and (eq qtag ?x)
5951                                            (re-search-forward
5952                                             "\\=[0-9a-fA-F][0-9a-fA-F]?\\|\\={[0-9a-fA-F]+}"
5953                                             (1- e) 'to-end))
5954                                       (and (memq qtag (append "pPN" nil))
5955                                            (re-search-forward "\\={[^{}]+}\\|."
5956                                             (1- e) 'to-end))
5957                                       (eq (char-syntax qtag) ?w))
5958                                   (cperl-postpone-fontification
5959                                    (1- REx-subgr-start) (point)
5960                                    'face my-cperl-REx-length1-face))))
5961                               (setq was-subgr nil)) ; We do stuff here
5962                              ((match-beginning 3) ; [charclass]
5963                               (forward-char 1)
5964                               (if (eq (char-after b) ?^ )
5965                                   (and (eq (following-char) ?\\ )
5966                                        (eq (char-after (cperl-1+ (point)))
5967                                            ?^ )
5968                                        (forward-char 2))
5969                                 (and (eq (following-char) ?^ )
5970                                      (forward-char 1)))
5971                               (setq argument b ; continue?
5972                                     tag nil ; list of POSIX classes
5973                                     qtag (point))
5974                               (if (eq (char-after b) ?\] )
5975                                   (and (eq (following-char) ?\\ )
5976                                        (eq (char-after (cperl-1+ (point)))
5977                                            ?\] )
5978                                        (setq qtag (1+ qtag))
5979                                        (forward-char 2))
5980                                 (and (eq (following-char) ?\] )
5981                                      (forward-char 1)))
5982                               ;; Apparently, I can't put \] into a charclass
5983                               ;; in m]]: m][\\\]\]] produces [\\]]
5984 ;;; POSIX?  [:word:] [:^word:] only inside []
5985 ;;;                                    "\\=\\(\\\\.\\|[^][\\\\]\\|\\[:\\^?\sw+:]\\|\\[[^:]\\)*]")
5986                               (while 
5987                                   (and argument
5988                                        (re-search-forward
5989                                         (if (eq (char-after b) ?\] )
5990                                             "\\=\\(\\\\[^]]\\|[^]\\\\]\\)*\\\\]"
5991                                           "\\=\\(\\\\.\\|[^]\\\\]\\)*]")
5992                                         (1- e) 'toend))
5993                                 ;; Is this ] an end of POSIX class?
5994                                 (if (save-excursion
5995                                       (and
5996                                        (search-backward "[" argument t)
5997                                        (< REx-subgr-start (point))
5998                                        (not
5999                                         (and ; Should work with delim = \
6000                                          (eq (preceding-char) ?\\ )
6001                                          (= (% (skip-chars-backward
6002                                                 "\\\\") 2) 0)))
6003                                        (looking-at
6004                                         (cond
6005                                          ((eq (char-after b) ?\] )
6006                                           "\\\\*\\[:\\^?\\sw+:\\\\\\]")
6007                                          ((eq (char-after b) ?\: )
6008                                           "\\\\*\\[\\\\:\\^?\\sw+\\\\:]")
6009                                          ((eq (char-after b) ?^ )
6010                                           "\\\\*\\[:\\(\\\\\\^\\)?\\sw+:\]")
6011                                          ((eq (char-syntax (char-after b))
6012                                               ?w)
6013                                           (concat
6014                                            "\\\\*\\[:\\(\\\\\\^\\)?\\(\\\\"
6015                                            (char-to-string (char-after b))
6016                                            "\\|\\sw\\)+:\]"))
6017                                          (t "\\\\*\\[:\\^?\\sw*:]")))
6018                                        (setq argument (point))))
6019                                     (setq tag (cons (cons argument (point))
6020                                                     tag)
6021                                           argument (point)) ; continue
6022                                   (setq argument nil)))
6023                               (and argument
6024                                    (message "Couldn't find end of charclass in a REx, pos=%s"
6025                                             REx-subgr-start))
6026                               (if (and cperl-use-syntax-table-text-property
6027                                        (> (- (point) 2) REx-subgr-start))
6028                                   (put-text-property
6029                                    (1+ REx-subgr-start) (1- (point))
6030                                    'syntax-table cperl-st-punct))
6031                               (cperl-postpone-fontification
6032                                REx-subgr-start qtag
6033                                'face my-cperl-REx-spec-char-face)
6034                               (cperl-postpone-fontification
6035                                (1- (point)) (point) 'face
6036                                my-cperl-REx-spec-char-face)
6037                               (if (eq (char-after b) ?\] )
6038                                   (cperl-postpone-fontification
6039                                    (- (point) 2) (1- (point))
6040                                    'face my-cperl-REx-0length-face))
6041                               (while tag
6042                                 (cperl-postpone-fontification
6043                                  (car (car tag)) (cdr (car tag))
6044                                  'face my-cperl-REx-length1-face)
6045                                 (setq tag (cdr tag)))
6046                               (setq was-subgr nil)) ; did facing already
6047                              ;; Now rare stuff:
6048                              ((and (match-beginning 2) ; #-comment
6049                                    (/= (match-beginning 2) (match-end 2)))
6050                               (beginning-of-line 2)
6051                               (if (> (point) e)
6052                                   (goto-char (1- e))))
6053                              ((match-beginning 4) ; character "]"
6054                               (setq was-subgr nil) ; We do stuff here
6055                               (goto-char (match-end 0))
6056                               (if cperl-use-syntax-table-text-property
6057                                   (put-text-property
6058                                    (1- (point)) (point)
6059                                    'syntax-table cperl-st-punct))
6060                               (cperl-postpone-fontification
6061                                (1- (point)) (point)
6062                                'face font-lock-warning-face))
6063                              ((match-beginning 5) ; before (?{}) (??{})
6064                               (setq tag (match-end 0))
6065                               (if (or (setq qtag
6066                                             (cperl-forward-group-in-re st-l))
6067                                       (and (>= (point) e)
6068                                            (setq qtag "no matching `)' found"))
6069                                       (and (not (eq (char-after (- (point) 2))
6070                                                     ?\} ))
6071                                            (setq qtag "Can't find })")))
6072                                   (progn
6073                                     (goto-char (1- e))
6074                                     (message qtag))
6075                                 (cperl-postpone-fontification
6076                                  (1- tag) (1- (point))
6077                                  'face font-lock-variable-name-face)
6078                                 (cperl-postpone-fontification
6079                                  REx-subgr-start (1- tag)
6080                                  'face my-cperl-REx-spec-char-face)
6081                                 (cperl-postpone-fontification
6082                                  (1- (point)) (point)
6083                                  'face my-cperl-REx-spec-char-face)
6084                                 (if cperl-use-syntax-table-text-property
6085                                     (progn
6086                                       (put-text-property
6087                                        (- (point) 2) (1- (point))
6088                                        'syntax-table cperl-st-cfence)
6089                                       (put-text-property
6090                                        (+ REx-subgr-start 2)
6091                                        (+ REx-subgr-start 3)
6092                                        'syntax-table cperl-st-cfence))))
6093                               (setq was-subgr nil))
6094                              (t         ; (?#)-comment
6095                               ;; Inside "(" and "\" arn't special in any way
6096                               ;; Works also if the outside delimiters are ().
6097                               (or;;(if (eq (char-after b) ?\) )
6098                                ;;(re-search-forward
6099                                ;; "[^\\\\]\\(\\\\\\\\\\)*\\\\)"
6100                                ;; (1- e) 'toend)
6101                                (search-forward ")" (1- e) 'toend)
6102                                ;;)
6103                                (message
6104                                 "Couldn't find end of (?#...)-comment in a REx, pos=%s"
6105                                 REx-subgr-start))))
6106                             (if (>= (point) e)
6107                                 (goto-char (1- e)))
6108                             (cond
6109                              (was-subgr
6110                               (setq REx-subgr-end (point))
6111                               (cperl-commentify
6112                                REx-subgr-start REx-subgr-end nil)
6113                               (cperl-postpone-fontification
6114                                REx-subgr-start REx-subgr-end
6115                                'face font-lock-comment-face))))))
6116                     (if (and is-REx is-x-REx)
6117                         (put-text-property (1+ b) (1- e)
6118                                            'syntax-subtype 'x-REx)))
6119                   (if i2
6120                       (progn
6121                         (cperl-postpone-fontification
6122                          (1- e1) e1 'face my-cperl-delimiters-face)
6123                         (if (assoc (char-after b) cperl-starters)
6124                             (progn
6125                               (cperl-postpone-fontification
6126                                b1 (1+ b1) 'face my-cperl-delimiters-face)
6127                               (put-text-property b1 (1+ b1)
6128                                            'REx-part2 t)))))
6129                   (if (> (point) max)
6130                       (setq tmpend tb))))
6131                ((match-beginning 17)    ; sub with prototype or attribute
6132                 ;; 1+6+2+1+1=11 extra () before this (sub with proto/attr):
6133                 ;;"\\<sub\\>\\("                        ;12
6134                 ;;   cperl-white-and-comment-rex        ;13
6135                 ;;   "\\([a-zA-Z_:'0-9]+\\)\\)?" ; name ;14
6136                 ;;"\\(" cperl-maybe-white-and-comment-rex       ;15,16
6137                 ;;   "\\(([^()]*)\\|:[^:]\\)\\)" ; 17:proto or attribute start
6138                 (setq b1 (match-beginning 14) e1 (match-end 14))
6139                 (if (memq (char-after (1- b))
6140                           '(?\$ ?\@ ?\% ?\& ?\*))
6141                     nil
6142                   (goto-char b)
6143                   (if (eq (char-after (match-beginning 17)) ?\( )
6144                       (progn
6145                         (cperl-commentify ; Prototypes; mark as string
6146                          (match-beginning 17) (match-end 17) t)
6147                         (goto-char (match-end 0))
6148                         ;; Now look for attributes after prototype:
6149                         (forward-comment (buffer-size))
6150                         (and (looking-at ":[^:]")
6151                              (cperl-find-sub-attrs st-l b1 e1 b)))
6152                     ;; treat attributes without prototype
6153                     (goto-char (match-beginning 17))
6154                     (cperl-find-sub-attrs st-l b1 e1 b))))
6155                ;; 1+6+2+1+1+6+1=18 extra () before this:
6156                ;;    "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'")
6157                ((match-beginning 19)    ; old $abc'efg syntax
6158                 (setq bb (match-end 0))
6159                 ;;;(if (nth 3 state) nil        ; in string
6160                 (put-text-property (1- bb) bb 'syntax-table cperl-st-word)
6161                 (goto-char bb))
6162                ;; 1+6+2+1+1+6+1+1=19 extra () before this:
6163                ;; "__\\(END\\|DATA\\)__"
6164                ((match-beginning 20)    ; __END__, __DATA__
6165                 (setq bb (match-end 0))
6166                 ;; (put-text-property b (1+ bb) 'syntax-type 'pod) ; Cheat
6167                 (cperl-commentify b bb nil)
6168                 (setq end t))
6169                ;; "\\\\\\(['`\"($]\\)"
6170                ((match-beginning 21)
6171                 ;; Trailing backslash; make non-quoting outside string/comment
6172                 (setq bb (match-end 0))
6173                 (goto-char b)
6174                 (skip-chars-backward "\\\\")
6175                 ;;;(setq i2 (= (% (skip-chars-backward "\\\\") 2) -1))
6176                 (cperl-modify-syntax-type b cperl-st-punct)
6177                 (goto-char bb))
6178                (t (error "Error in regexp of the sniffer")))
6179               (if (> (point) stop-point)
6180                   (progn
6181                     (if end
6182                         (message "Garbage after __END__/__DATA__ ignored")
6183                       (message "Unbalanced syntax found while scanning")
6184                       (or (car err-l) (setcar err-l b)))
6185                     (goto-char stop-point))))
6186             (setq cperl-syntax-state (cons state-point state)
6187                   ;; Do not mark syntax as done past tmpend???
6188                   cperl-syntax-done-to (or tmpend (max (point) max)))
6189             ;;(message "state-at=%s, done-to=%s" state-point cperl-syntax-done-to)
6190             )
6191           (if (car err-l) (goto-char (car err-l))
6192             (or non-inter
6193                 (message "Scanning for \"hard\" Perl constructions... done"))))
6194       (and (buffer-modified-p)
6195            (not modified)
6196            (set-buffer-modified-p nil))
6197       (set-syntax-table cperl-mode-syntax-table))
6198     (list (car err-l) overshoot)))
6199
6200 (defun cperl-find-pods-heres-region (min max)
6201   (interactive "r")
6202   (cperl-find-pods-heres min max))
6203
6204 (defun cperl-backward-to-noncomment (lim)
6205   ;; Stops at lim or after non-whitespace that is not in comment
6206   ;; XXXX Wrongly understands end-of-multiline strings with # as comment
6207   (let (stop p pr)
6208     (while (and (not stop) (> (point) (or lim (point-min))))
6209       (skip-chars-backward " \t\n\f" lim)
6210       (setq p (point))
6211       (beginning-of-line)
6212       (if (memq (setq pr (get-text-property (point) 'syntax-type))
6213                 '(pod here-doc here-doc-delim))
6214           (cperl-unwind-to-safe nil)
6215         (or (and (looking-at "^[ \t]*\\(#\\|$\\)")
6216                  (not (memq pr '(string prestring))))
6217             (progn (cperl-to-comment-or-eol) (bolp))
6218             (progn
6219               (skip-chars-backward " \t")
6220               (if (< p (point)) (goto-char p))
6221               (setq stop t)))))))
6222
6223 ;; Used only in `cperl-calculate-indent'...
6224 (defun cperl-block-p ()            ; Do not C-M-q !  One string contains ";" !
6225   ;; Positions is before ?\{.  Checks whether it starts a block.
6226   ;; No save-excursion!  This is more a distinguisher of a block/hash ref...
6227   (cperl-backward-to-noncomment (point-min))
6228   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label!  \C-@ at bobp
6229                                         ; Label may be mixed up with `$blah :'
6230       (save-excursion (cperl-after-label))
6231       (get-text-property (cperl-1- (point)) 'attrib-group)
6232       (and (memq (char-syntax (preceding-char)) '(?w ?_))
6233            (progn
6234              (backward-sexp)
6235              ;; sub {BLK}, print {BLK} $data, but NOT `bless', `return', `tr'
6236              (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
6237                       (not (looking-at "\\(bless\\|return\\|q[wqrx]?\\|tr\\|[smy]\\)\\>")))
6238                  ;; sub bless::foo {}
6239                  (progn
6240                    (cperl-backward-to-noncomment (point-min))
6241                    (and (eq (preceding-char) ?b)
6242                         (progn
6243                           (forward-sexp -1)
6244                           (looking-at "sub[ \t\n\f#]")))))))))
6245
6246 ;;; What is the difference of (cperl-after-block-p lim t) and (cperl-block-p)?
6247 ;;; No save-excursion; condition-case ...  In (cperl-block-p) the block
6248 ;;; may be a part of an in-statement construct, such as
6249 ;;;   ${something()}, print {FH} $data.
6250 ;;; Moreover, one takes positive approach (looks for else,grep etc)
6251 ;;; another negative (looks for bless,tr etc)
6252 (defun cperl-after-block-p (lim &optional pre-block)
6253   "Return true if the preceeding } (if PRE-BLOCK, following {) delimits a block.
6254 Would not look before LIM.  Assumes that LIM is a good place to begin a
6255 statement.  The kind of block we treat here is one after which a new
6256 statement would start; thus the block in ${func()} does not count."
6257   (save-excursion
6258     (condition-case nil
6259         (progn
6260           (or pre-block (forward-sexp -1))
6261           (cperl-backward-to-noncomment lim)
6262           (or (eq (point) lim)
6263               ;; if () {}   // sub f () {}   // sub f :a(') {}
6264               (eq (preceding-char) ?\) )
6265               ;; label: {}
6266               (save-excursion (cperl-after-label))
6267               ;; sub :attr {}
6268               (get-text-property (cperl-1- (point)) 'attrib-group)
6269               (if (memq (char-syntax (preceding-char)) '(?w ?_)) ; else {}
6270                   (save-excursion
6271                     (forward-sexp -1)
6272                     ;; else {}     but not    else::func {}
6273                     (or (and (looking-at "\\(else\\|continue\\|grep\\|map\\|BEGIN\\|END\\|CHECK\\|INIT\\)\\>")
6274                              (not (looking-at "\\(\\sw\\|_\\)+::")))
6275                         ;; sub f {}
6276                         (progn
6277                           (cperl-backward-to-noncomment lim)
6278                           (and (eq (preceding-char) ?b)
6279                                (progn
6280                                  (forward-sexp -1)
6281                                  (looking-at "sub[ \t\n\f#]"))))))
6282                 ;; What preceeds is not word...  XXXX Last statement in sub???
6283                 (cperl-after-expr-p lim))))
6284       (error nil))))
6285
6286 (defun cperl-after-expr-p (&optional lim chars test)
6287   "Return true if the position is good for start of expression.
6288 TEST is the expression to evaluate at the found position.  If absent,
6289 CHARS is a string that contains good characters to have before us (however,
6290 `}' is treated \"smartly\" if it is not in the list)."
6291   (let ((lim (or lim (point-min)))
6292         stop p pr)
6293     (cperl-update-syntaxification (point) (point))
6294     (save-excursion
6295       (while (and (not stop) (> (point) lim))
6296         (skip-chars-backward " \t\n\f" lim)
6297         (setq p (point))
6298         (beginning-of-line)
6299         ;;(memq (setq pr (get-text-property (point) 'syntax-type))
6300         ;;      '(pod here-doc here-doc-delim))
6301         (if (get-text-property (point) 'here-doc-group)
6302             (progn
6303               (goto-char
6304                (cperl-beginning-of-property (point) 'here-doc-group))
6305               (beginning-of-line 0)))
6306         (if (get-text-property (point) 'in-pod)
6307             (progn
6308               (goto-char
6309                (cperl-beginning-of-property (point) 'in-pod))
6310               (beginning-of-line 0)))
6311         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
6312           ;; Else: last iteration, or a label
6313           (cperl-to-comment-or-eol)     ; Will not move past "." after a format
6314           (skip-chars-backward " \t")
6315           (if (< p (point)) (goto-char p))
6316           (setq p (point))
6317           (if (and (eq (preceding-char) ?:)
6318                    (progn
6319                      (forward-char -1)
6320                      (skip-chars-backward " \t\n\f" lim)
6321                      (memq (char-syntax (preceding-char)) '(?w ?_))))
6322               (forward-sexp -1)         ; Possibly label.  Skip it
6323             (goto-char p)
6324             (setq stop t))))
6325       (or (bobp)                        ; ???? Needed
6326           (eq (point) lim)
6327           (looking-at "[ \t]*__\\(END\\|DATA\\)__") ; After this anything goes
6328           (progn
6329             (if test (eval test)
6330               (or (memq (preceding-char) (append (or chars "{;") nil))
6331                   (and (eq (preceding-char) ?\})
6332                        (cperl-after-block-p lim))
6333                   (and (eq (following-char) ?.) ; in format: see comment above
6334                        (eq (get-text-property (point) 'syntax-type)
6335                            'format)))))))))
6336
6337 (defun cperl-backward-to-start-of-expr (&optional lim)
6338   (condition-case nil
6339       (progn
6340         (while (and (or (not lim)
6341                         (> (point) lim))
6342                     (not (cperl-after-expr-p lim)))
6343           (forward-sexp -1)))
6344     (error nil)))
6345
6346 (defun cperl-at-end-of-expr (&optional lim)
6347   (condition-case nil
6348       (save-excursion
6349         ;; If nothing interesting after, same as (forward-sexp -1); otherwise
6350         ;; fails, or at a start of following sexp:
6351         (let ((p (point)))
6352           (forward-sexp 1)
6353           (forward-sexp -1)
6354           (or (< (point) p)
6355               (cperl-after-expr-p lim))))
6356     (error t)))
6357
6358 (defun cperl-forward-to-end-of-expr (&optional lim)
6359   (let ((p (point))))
6360   (condition-case nil
6361       (progn
6362         (while (and (< (point) (or lim (point-max)))
6363                     (not (cperl-at-end-of-expr)))
6364           (forward-sexp 1)))
6365     (error nil)))
6366
6367 (defun cperl-backward-to-start-of-continued-exp (lim)
6368   (if (memq (preceding-char) (append ")]}\"'`" nil))
6369       (forward-sexp -1))
6370   (beginning-of-line)
6371   (if (<= (point) lim)
6372       (goto-char (1+ lim)))
6373   (skip-chars-forward " \t"))
6374
6375 (defun cperl-after-block-and-statement-beg (lim)
6376   ;; We assume that we are after ?\}
6377   (and
6378    (cperl-after-block-p lim)
6379    (save-excursion
6380      (forward-sexp -1)
6381      (cperl-backward-to-noncomment (point-min))
6382      (or (bobp)
6383          (eq (point) lim)
6384          (not (= (char-syntax (preceding-char)) ?w))
6385          (progn
6386            (forward-sexp -1)
6387            (not
6388             (looking-at
6389              "\\(map\\|grep\\|printf?\\|system\\|exec\\|tr\\|s\\)\\>")))))))
6390
6391 \f
6392 (defvar innerloop-done nil)
6393 (defvar last-depth nil)
6394
6395 (defun cperl-indent-exp ()
6396   "Simple variant of indentation of continued-sexp.
6397
6398 Will not indent comment if it starts at `comment-indent' or looks like
6399 continuation of the comment on the previous line.
6400
6401 If `cperl-indent-region-fix-constructs', will improve spacing on
6402 conditional/loop constructs."
6403   (interactive)
6404   (save-excursion
6405     (let ((tmp-end (progn (end-of-line) (point))) top done)
6406       (save-excursion
6407         (beginning-of-line)
6408         (while (null done)
6409           (setq top (point))
6410           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
6411                                                -1)) -1)
6412             (setq top (point)))         ; Get the outermost parenths in line
6413           (goto-char top)
6414           (while (< (point) tmp-end)
6415             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
6416             (or (eolp) (forward-sexp 1)))
6417           (if (> (point) tmp-end)
6418               (save-excursion
6419                 (end-of-line)
6420                 (setq tmp-end (point)))
6421             (setq done t)))
6422         (goto-char tmp-end)
6423         (setq tmp-end (point-marker)))
6424       (if cperl-indent-region-fix-constructs
6425           (cperl-fix-line-spacing tmp-end))
6426       (cperl-indent-region (point) tmp-end))))
6427
6428 (defun cperl-fix-line-spacing (&optional end parse-data)
6429   "Improve whitespace in a conditional/loop construct.
6430 Returns some position at the last line."
6431   (interactive)
6432   (or end
6433       (setq end (point-max)))
6434   (let ((ee (save-excursion (end-of-line) (point)))
6435         (cperl-indent-region-fix-constructs
6436          (or cperl-indent-region-fix-constructs 1))
6437         p pp ml have-brace ret)
6438     (save-excursion
6439       (beginning-of-line)
6440       (setq ret (point))
6441       ;;  }? continue
6442       ;;  blah; }
6443       (if (not
6444            (or (looking-at "[ \t]*\\(els\\(e\\|if\\)\\|continue\\|if\\|while\\|for\\(each\\)?\\|until\\)")
6445                (setq have-brace (save-excursion (search-forward "}" ee t)))))
6446           nil                           ; Do not need to do anything
6447         ;; Looking at:
6448         ;; }
6449         ;; else
6450         (if (and cperl-merge-trailing-else
6451                  (looking-at
6452                   "[ \t]*}[ \t]*\n[ \t\n]*\\(els\\(e\\|if\\)\\|continue\\)\\>"))
6453             (progn
6454               (search-forward "}")
6455               (setq p (point))
6456               (skip-chars-forward " \t\n")
6457               (delete-region p (point))
6458               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6459               (beginning-of-line)))
6460         ;; Looking at:
6461         ;; }     else
6462         (if (looking-at "[ \t]*}\\(\t*\\|[ \t][ \t]+\\)\\<\\(els\\(e\\|if\\)\\|continue\\)\\>")
6463             (progn
6464               (search-forward "}")
6465               (delete-horizontal-space)
6466               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6467               (beginning-of-line)))
6468         ;; Looking at:
6469         ;; else   {
6470         (if (looking-at
6471              "[ \t]*}?[ \t]*\\<\\(\\els\\(e\\|if\\)\\|continue\\|unless\\|if\\|while\\|for\\(each\\)?\\|until\\)\\>\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
6472             (progn
6473               (forward-word 1)
6474               (delete-horizontal-space)
6475               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6476               (beginning-of-line)))
6477         ;; Looking at:
6478         ;; foreach my    $var
6479         (if (looking-at
6480              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)\\(\t*\\|[ \t][ \t]+\\)[^ \t\n]")
6481             (progn
6482               (forward-word 2)
6483               (delete-horizontal-space)
6484               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
6485               (beginning-of-line)))
6486         ;; Looking at:
6487         ;; foreach my $var     (
6488         (if (looking-at
6489              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)[ \t]*\\$[_a-zA-Z0-9]+\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
6490             (progn
6491               (forward-sexp 3)
6492               (delete-horizontal-space)
6493               (insert
6494                (make-string cperl-indent-region-fix-constructs ?\ ))
6495               (beginning-of-line)))
6496         ;; Looking at:
6497         ;; } foreach my $var ()    {
6498         (if (looking-at
6499              "[ \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]*{")
6500             (progn
6501               (setq ml (match-beginning 8))
6502               (re-search-forward "[({]")
6503               (forward-char -1)
6504               (setq p (point))
6505               (if (eq (following-char) ?\( )
6506                   (progn
6507                     (forward-sexp 1)
6508                     (setq pp (point)))
6509                 ;; after `else' or nothing
6510                 (if ml                  ; after `else'
6511                     (skip-chars-backward " \t\n")
6512                   (beginning-of-line))
6513                 (setq pp nil))
6514               ;; Now after the sexp before the brace
6515               ;; Multiline expr should be special
6516               (setq ml (and pp (save-excursion (goto-char p)
6517                                                (search-forward "\n" pp t))))
6518               (if (and (or (not pp) (< pp end))
6519                        (looking-at "[ \t\n]*{"))
6520                   (progn
6521                     (cond
6522                      ((bolp)            ; Were before `{', no if/else/etc
6523                       nil)
6524                      ((looking-at "\\(\t*\\| [ \t]+\\){")
6525                       (delete-horizontal-space)
6526                       (if (if ml
6527                               cperl-extra-newline-before-brace-multiline
6528                             cperl-extra-newline-before-brace)
6529                           (progn
6530                             (delete-horizontal-space)
6531                             (insert "\n")
6532                             (setq ret (point))
6533                             (if (cperl-indent-line parse-data)
6534                                 (progn
6535                                   (cperl-fix-line-spacing end parse-data)
6536                                   (setq ret (point)))))
6537                         (insert
6538                          (make-string cperl-indent-region-fix-constructs ?\ ))))
6539                      ((and (looking-at "[ \t]*\n")
6540                            (not (if ml
6541                                     cperl-extra-newline-before-brace-multiline
6542                                   cperl-extra-newline-before-brace)))
6543                       (setq pp (point))
6544                       (skip-chars-forward " \t\n")
6545                       (delete-region pp (point))
6546                       (insert
6547                        (make-string cperl-indent-region-fix-constructs ?\ ))))
6548                     ;; Now we are before `{'
6549                     (if (looking-at "[ \t\n]*{[ \t]*[^ \t\n#]")
6550                         (progn
6551                           (skip-chars-forward " \t\n")
6552                           (setq pp (point))
6553                           (forward-sexp 1)
6554                           (setq p (point))
6555                           (goto-char pp)
6556                           (setq ml (search-forward "\n" p t))
6557                           (if (or cperl-break-one-line-blocks-when-indent ml)
6558                               ;; not good: multi-line BLOCK
6559                               (progn
6560                                 (goto-char (1+ pp))
6561                                 (delete-horizontal-space)
6562                                 (insert "\n")
6563                                 (setq ret (point))
6564                                 (if (cperl-indent-line parse-data)
6565                                     (setq ret (cperl-fix-line-spacing end parse-data)))))))))))
6566         (beginning-of-line)
6567         (setq p (point) pp (save-excursion (end-of-line) (point))) ; May be different from ee.
6568         ;; Now check whether there is a hanging `}'
6569         ;; Looking at:
6570         ;; } blah
6571         (if (and
6572              cperl-fix-hanging-brace-when-indent
6573              have-brace
6574              (not (looking-at "[ \t]*}[ \t]*\\(\\<\\(els\\(if\\|e\\)\\|continue\\|while\\|until\\)\\>\\|$\\|#\\)"))
6575              (condition-case nil
6576                  (progn
6577                    (up-list 1)
6578                    (if (and (<= (point) pp)
6579                             (eq (preceding-char) ?\} )
6580                             (cperl-after-block-and-statement-beg (point-min)))
6581                        t
6582                      (goto-char p)
6583                      nil))
6584                (error nil)))
6585             (progn
6586               (forward-char -1)
6587               (skip-chars-backward " \t")
6588               (if (bolp)
6589                   ;; `}' was the first thing on the line, insert NL *after* it.
6590                   (progn
6591                     (cperl-indent-line parse-data)
6592                     (search-forward "}")
6593                     (delete-horizontal-space)
6594                     (insert "\n"))
6595                 (delete-horizontal-space)
6596                 (or (eq (preceding-char) ?\;)
6597                     (bolp)
6598                     (and (eq (preceding-char) ?\} )
6599                          (cperl-after-block-p (point-min)))
6600                     (insert ";"))
6601                 (insert "\n")
6602                 (setq ret (point)))
6603               (if (cperl-indent-line parse-data)
6604                   (setq ret (cperl-fix-line-spacing end parse-data)))
6605               (beginning-of-line)))))
6606     ret))
6607
6608 (defvar cperl-update-start)             ; Do not need to make them local
6609 (defvar cperl-update-end)
6610 (defun cperl-delay-update-hook (beg end old-len)
6611   (setq cperl-update-start (min beg (or cperl-update-start (point-max))))
6612   (setq cperl-update-end (max end (or cperl-update-end (point-min)))))
6613
6614 (defun cperl-indent-region (start end)
6615   "Simple variant of indentation of region in CPerl mode.
6616 Should be slow.  Will not indent comment if it starts at `comment-indent'
6617 or looks like continuation of the comment on the previous line.
6618 Indents all the lines whose first character is between START and END
6619 inclusive.
6620
6621 If `cperl-indent-region-fix-constructs', will improve spacing on
6622 conditional/loop constructs."
6623   (interactive "r")
6624   (cperl-update-syntaxification end end)
6625   (save-excursion
6626     (let (cperl-update-start cperl-update-end (h-a-c after-change-functions))
6627       (let ((indent-info (if cperl-emacs-can-parse
6628                              (list nil nil nil) ; Cannot use '(), since will modify
6629                            nil))
6630             (pm 0) (imenu-scanning-message "Indenting... (%3d%%)")
6631             after-change-functions      ; Speed it up!
6632             st comm old-comm-indent new-comm-indent p pp i empty)
6633         (if h-a-c (add-hook 'after-change-functions 'cperl-delay-update-hook))
6634         (goto-char start)
6635         (setq old-comm-indent (and (cperl-to-comment-or-eol)
6636                                    (current-column))
6637               new-comm-indent old-comm-indent)
6638         (goto-char start)
6639         (setq end (set-marker (make-marker) end)) ; indentation changes pos
6640         (or (bolp) (beginning-of-line 2))
6641         (or (fboundp 'imenu-progress-message)
6642             (message "Indenting... For feedback load `imenu'..."))
6643         (while (and (<= (point) end) (not (eobp))) ; bol to check start
6644           (and (fboundp 'imenu-progress-message)
6645                (imenu-progress-message
6646                 pm (/ (* 100 (- (point) start)) (- end start -1))))
6647           (setq st (point))
6648           (if (or
6649                (setq empty (looking-at "[ \t]*\n"))
6650                (and (setq comm (looking-at "[ \t]*#"))
6651                     (or (eq (current-indentation) (or old-comm-indent
6652                                                       comment-column))
6653                         (setq old-comm-indent nil))))
6654               (if (and old-comm-indent
6655                        (not empty)
6656                        (= (current-indentation) old-comm-indent)
6657                        (not (eq (get-text-property (point) 'syntax-type) 'pod))
6658                        (not (eq (get-text-property (point) 'syntax-table)
6659                                 cperl-st-cfence)))
6660                   (let ((comment-column new-comm-indent))
6661                     (indent-for-comment)))
6662             (progn
6663               (setq i (cperl-indent-line indent-info))
6664               (or comm
6665                   (not i)
6666                   (progn
6667                     (if cperl-indent-region-fix-constructs
6668                         (goto-char (cperl-fix-line-spacing end indent-info)))
6669                     (if (setq old-comm-indent
6670                               (and (cperl-to-comment-or-eol)
6671                                    (not (memq (get-text-property (point)
6672                                                                  'syntax-type)
6673                                               '(pod here-doc)))
6674                                    (not (eq (get-text-property (point)
6675                                                                'syntax-table)
6676                                             cperl-st-cfence))
6677                                    (current-column)))
6678                         (progn (indent-for-comment)
6679                                (skip-chars-backward " \t")
6680                                (skip-chars-backward "#")
6681                                (setq new-comm-indent (current-column))))))))
6682           (beginning-of-line 2))
6683         (if (fboundp 'imenu-progress-message)
6684             (imenu-progress-message pm 100)
6685           (message nil)))
6686       ;; Now run the update hooks
6687       (and after-change-functions
6688            cperl-update-end
6689            (save-excursion
6690              (goto-char cperl-update-end)
6691              (insert " ")
6692              (delete-char -1)
6693              (goto-char cperl-update-start)
6694              (insert " ")
6695              (delete-char -1))))))
6696
6697 ;; Stolen from lisp-mode with a lot of improvements
6698
6699 (defun cperl-fill-paragraph (&optional justify iteration)
6700   "Like \\[fill-paragraph], but handle CPerl comments.
6701 If any of the current line is a comment, fill the comment or the
6702 block of it that point is in, preserving the comment's initial
6703 indentation and initial hashes.  Behaves usually outside of comment."
6704   (interactive "P")
6705   (let (;; Non-nil if the current line contains a comment.
6706         has-comment
6707         fill-paragraph-function         ; do not recurse
6708         ;; If has-comment, the appropriate fill-prefix for the comment.
6709         comment-fill-prefix
6710         ;; Line that contains code and comment (or nil)
6711         start
6712         c spaces len dc (comment-column comment-column))
6713     ;; Figure out what kind of comment we are looking at.
6714     (save-excursion
6715       (beginning-of-line)
6716       (cond
6717
6718        ;; A line with nothing but a comment on it?
6719        ((looking-at "[ \t]*#[# \t]*")
6720         (setq has-comment t
6721               comment-fill-prefix (buffer-substring (match-beginning 0)
6722                                                     (match-end 0))))
6723
6724        ;; A line with some code, followed by a comment?  Remember that the
6725        ;; semi which starts the comment shouldn't be part of a string or
6726        ;; character.
6727        ((cperl-to-comment-or-eol)
6728         (setq has-comment t)
6729         (looking-at "#+[ \t]*")
6730         (setq start (point) c (current-column)
6731               comment-fill-prefix
6732               (concat (make-string (current-column) ?\ )
6733                       (buffer-substring (match-beginning 0) (match-end 0)))
6734               spaces (progn (skip-chars-backward " \t")
6735                             (buffer-substring (point) start))
6736               dc (- c (current-column)) len (- start (point))
6737               start (point-marker))
6738         (delete-char len)
6739         (insert (make-string dc ?-))))) ; Placeholder (to avoid splitting???)
6740     (if (not has-comment)
6741         (fill-paragraph justify)       ; Do the usual thing outside of comment
6742       ;; Narrow to include only the comment, and then fill the region.
6743       (save-restriction
6744         (narrow-to-region
6745          ;; Find the first line we should include in the region to fill.
6746          (if start (progn (beginning-of-line) (point))
6747            (save-excursion
6748              (while (and (zerop (forward-line -1))
6749                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
6750              ;; We may have gone to far.  Go forward again.
6751              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
6752                  (forward-line 1))
6753              (point)))
6754          ;; Find the beginning of the first line past the region to fill.
6755          (save-excursion
6756            (while (progn (forward-line 1)
6757                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
6758            (point)))
6759         ;; Remove existing hashes
6760         (goto-char (point-min))
6761         (while (progn (forward-line 1) (< (point) (point-max)))
6762           (skip-chars-forward " \t")
6763           (if (looking-at "#+")
6764               (progn
6765                 (if (and (eq (point) (match-beginning 0))
6766                          (not (eq (point) (match-end 0)))) nil
6767                     (error
6768  "Bug in Emacs: `looking-at' in `narrow-to-region': match-data is garbage"))
6769                 (delete-char (- (match-end 0) (match-beginning 0))))))
6770
6771         ;; Lines with only hashes on them can be paragraph boundaries.
6772         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
6773               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
6774               (fill-prefix comment-fill-prefix))
6775           (fill-paragraph justify)))
6776       (if (and start)
6777           (progn
6778             (goto-char start)
6779             (if (> dc 0)
6780                 (progn (delete-char dc) (insert spaces)))
6781             (if (or (= (current-column) c) iteration) nil
6782               (setq comment-column c)
6783               (indent-for-comment)
6784               ;; Repeat once more, flagging as iteration
6785               (cperl-fill-paragraph justify t))))))
6786   t)
6787
6788 (defun cperl-do-auto-fill ()
6789   ;; Break out if the line is short enough
6790   (if (> (save-excursion
6791            (end-of-line)
6792            (current-column))
6793          fill-column)
6794       (let ((c (save-excursion (beginning-of-line)
6795                                (cperl-to-comment-or-eol) (point)))
6796             (s (memq (following-char) '(?\ ?\t))) marker)
6797         (if (>= c (point)) nil
6798           (setq marker (point-marker))
6799           (cperl-fill-paragraph)
6800           (goto-char marker)
6801           ;; Is not enough, sometimes marker is a start of line
6802           (if (bolp) (progn (re-search-forward "#+[ \t]*")
6803                             (goto-char (match-end 0))))
6804           ;; Following space could have gone:
6805           (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
6806             (insert " ")
6807             (backward-char 1))
6808           ;; Previous space could have gone:
6809           (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
6810
6811 (defun cperl-imenu-addback (lst &optional isback name)
6812   ;; We suppose that the lst is a DAG, unless the first element only
6813   ;; loops back, and ISBACK is set.  Thus this function cannot be
6814   ;; applied twice without ISBACK set.
6815   (cond ((not cperl-imenu-addback) lst)
6816         (t
6817          (or name
6818              (setq name "+++BACK+++"))
6819          (mapcar (lambda (elt)
6820                    (if (and (listp elt) (listp (cdr elt)))
6821                        (progn
6822                          ;; In the other order it goes up
6823                          ;; one level only ;-(
6824                          (setcdr elt (cons (cons name lst)
6825                                            (cdr elt)))
6826                          (cperl-imenu-addback (cdr elt) t name))))
6827                  (if isback (cdr lst) lst))
6828          lst)))
6829
6830 (defun cperl-imenu--create-perl-index (&optional regexp)
6831   (require 'cl)
6832   (require 'imenu)                      ; May be called from TAGS creator
6833   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '())
6834         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
6835         (index-meth-alist '()) meth
6836         packages ends-ranges p marker is-proto
6837         (prev-pos 0) is-pack index index1 name (end-range 0) package)
6838     (goto-char (point-min))
6839     (if noninteractive
6840         (message "Scanning Perl for index")
6841       (imenu-progress-message prev-pos 0))
6842     (cperl-update-syntaxification (point-max) (point-max))
6843     ;; Search for the function
6844     (progn ;;save-match-data
6845       (while (re-search-forward
6846               (or regexp cperl-imenu--function-name-regexp-perl)
6847               nil t)
6848         (or noninteractive
6849             (imenu-progress-message prev-pos))
6850         ;; 2=package-group, 5=package-name 8=sub-name
6851         (cond
6852          ((and                          ; Skip some noise if building tags
6853            (match-beginning 5)          ; package name
6854            ;;(eq (char-after (match-beginning 2)) ?p) ; package
6855            (not (save-match-data
6856                   (looking-at "[ \t\n]*;")))) ; Plain text word 'package'
6857           nil)
6858          ((and
6859            (or (match-beginning 2)
6860                (match-beginning 8))             ; package or sub
6861            ;; Skip if quoted (will not skip multi-line ''-strings :-():
6862            (null (get-text-property (match-beginning 1) 'syntax-table))
6863            (null (get-text-property (match-beginning 1) 'syntax-type))
6864            (null (get-text-property (match-beginning 1) 'in-pod)))
6865           (setq is-pack (match-beginning 2))
6866           ;; (if (looking-at "([^()]*)[ \t\n\f]*")
6867           ;;    (goto-char (match-end 0)))      ; Messes what follows
6868           (setq meth nil
6869                 p (point))
6870           (while (and ends-ranges (>= p (car ends-ranges)))
6871             ;; delete obsolete entries
6872             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
6873           (setq package (or (car packages) "")
6874                 end-range (or (car ends-ranges) 0))
6875           (if is-pack                   ; doing "package"
6876               (progn
6877                 (if (match-beginning 5) ; named package
6878                     (setq name (buffer-substring (match-beginning 5)
6879                                                  (match-end 5))
6880                           name (progn
6881                                  (set-text-properties 0 (length name) nil name)
6882                                  name)
6883                           package (concat name "::")
6884                           name (concat "package " name))
6885                   ;; Support nameless packages
6886                   (setq name "package;" package ""))
6887                 (setq end-range
6888                       (save-excursion
6889                         (parse-partial-sexp (point) (point-max) -1) (point))
6890                       ends-ranges (cons end-range ends-ranges)
6891                       packages (cons package packages)))
6892             (setq is-proto
6893                   (or (eq (following-char) ?\;)
6894                       (eq 0 (get-text-property (point) 'attrib-group)))))
6895           ;; Skip this function name if it is a prototype declaration.
6896           (if (and is-proto (not is-pack)) nil
6897             (or is-pack
6898                 (setq name
6899                       (buffer-substring (match-beginning 8) (match-end 8)))
6900                 (set-text-properties 0 (length name) nil name))
6901             (setq marker (make-marker))
6902             (set-marker marker (match-end (if is-pack 2 8)))
6903             (cond (is-pack nil)
6904                   ((string-match "[:']" name)
6905                    (setq meth t))
6906                   ((> p end-range) nil)
6907                   (t
6908                    (setq name (concat package name) meth t)))
6909             (setq index (cons name marker))
6910             (if is-pack
6911                 (push index index-pack-alist)
6912               (push index index-alist))
6913             (if meth (push index index-meth-alist))
6914             (push index index-unsorted-alist)))
6915          ((match-beginning 16)          ; POD section
6916           (setq name (buffer-substring (match-beginning 17) (match-end 17))
6917                 marker (make-marker))
6918           (set-marker marker (match-beginning 17))
6919           (set-text-properties 0 (length name) nil name)
6920           (setq name (concat (make-string
6921                               (* 3 (- (char-after (match-beginning 16)) ?1))
6922                               ?\ )
6923                              name)
6924                 index (cons name marker))
6925           (setq index1 (cons (concat "=" name) (cdr index)))
6926           (push index index-pod-alist)
6927           (push index1 index-unsorted-alist)))))
6928     (or noninteractive
6929         (imenu-progress-message prev-pos 100))
6930     (setq index-alist
6931           (if (default-value 'imenu-sort-function)
6932               (sort index-alist (default-value 'imenu-sort-function))
6933             (nreverse index-alist)))
6934     (and index-pod-alist
6935          (push (cons "+POD headers+..."
6936                      (nreverse index-pod-alist))
6937                index-alist))
6938     (and (or index-pack-alist index-meth-alist)
6939          (let ((lst index-pack-alist) hier-list pack elt group name)
6940            ;; Remove "package ", reverse and uniquify.
6941            (while lst
6942              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
6943              (if (assoc name hier-list) nil
6944                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
6945            (setq lst index-meth-alist)
6946            (while lst
6947              (setq elt (car lst) lst (cdr lst))
6948              (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
6949                     (setq pack (substring (car elt) 0 (match-beginning 0)))
6950                     (if (setq group (assoc pack hier-list))
6951                         (if (listp (cdr group))
6952                             ;; Have some functions already
6953                             (setcdr group
6954                                     (cons (cons (substring
6955                                                  (car elt)
6956                                                  (+ 2 (match-beginning 0)))
6957                                                 (cdr elt))
6958                                           (cdr group)))
6959                           (setcdr group (list (cons (substring
6960                                                      (car elt)
6961                                                      (+ 2 (match-beginning 0)))
6962                                                     (cdr elt)))))
6963                       (setq hier-list
6964                             (cons (cons pack
6965                                         (list (cons (substring
6966                                                      (car elt)
6967                                                      (+ 2 (match-beginning 0)))
6968                                                     (cdr elt))))
6969                                   hier-list))))))
6970            (push (cons "+Hierarchy+..."
6971                        hier-list)
6972                  index-alist)))
6973     (and index-pack-alist
6974          (push (cons "+Packages+..."
6975                      (nreverse index-pack-alist))
6976                index-alist))
6977     (and (or index-pack-alist index-pod-alist
6978              (default-value 'imenu-sort-function))
6979          index-unsorted-alist
6980          (push (cons "+Unsorted List+..."
6981                      (nreverse index-unsorted-alist))
6982                index-alist))
6983     (cperl-imenu-addback index-alist)))
6984
6985 \f
6986 ;; Suggested by Mark A. Hershberger
6987 (defun cperl-outline-level ()
6988   (looking-at outline-regexp)
6989   (cond ((not (match-beginning 1)) 0)   ; beginning-of-file
6990 ;;;; 2=package-group, 5=package-name 8=sub-name 16=head-level
6991         ((match-beginning 2) 0)         ; package
6992         ((match-beginning 8) 1)         ; sub
6993         ((match-beginning 16)
6994          (- (char-after (match-beginning 16)) ?0)) ; headN ==> N
6995         (t 5)))                         ; should not happen
6996
6997 \f
6998 (defvar cperl-compilation-error-regexp-alist
6999   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORKS).
7000   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
7001      2 3))
7002   "Alist that specifies how to match errors in perl output.")
7003
7004 (if (fboundp 'eval-after-load)
7005     (eval-after-load
7006         "mode-compile"
7007       '(setq perl-compilation-error-regexp-alist
7008              cperl-compilation-error-regexp-alist)))
7009
7010
7011 (defun cperl-windowed-init ()
7012   "Initialization under windowed version."
7013   (if (or (featurep 'ps-print) cperl-faces-init)
7014       ;; Need to init anyway:
7015       (or cperl-faces-init (cperl-init-faces))
7016     (add-hook 'font-lock-mode-hook
7017               (function
7018                (lambda ()
7019                  (if (memq major-mode '(perl-mode cperl-mode))
7020                      (progn
7021                        (or cperl-faces-init (cperl-init-faces)))))))
7022     (if (fboundp 'eval-after-load)
7023         (eval-after-load
7024             "ps-print"
7025           '(or cperl-faces-init (cperl-init-faces))))))
7026
7027 (defun cperl-load-font-lock-keywords ()
7028   (or cperl-faces-init (cperl-init-faces))
7029   perl-font-lock-keywords)
7030
7031 (defun cperl-load-font-lock-keywords-1 ()
7032   (or cperl-faces-init (cperl-init-faces))
7033   perl-font-lock-keywords-1)
7034
7035 (defun cperl-load-font-lock-keywords-2 ()
7036   (or cperl-faces-init (cperl-init-faces))
7037   perl-font-lock-keywords-2)
7038
7039 (defvar perl-font-lock-keywords-1 nil
7040   "Additional expressions to highlight in Perl mode.  Minimal set.")
7041 (defvar perl-font-lock-keywords nil
7042   "Additional expressions to highlight in Perl mode.  Default set.")
7043 (defvar perl-font-lock-keywords-2 nil
7044   "Additional expressions to highlight in Perl mode.  Maximal set.")
7045
7046 (defvar font-lock-background-mode)
7047 (defvar font-lock-display-type)
7048 (defun cperl-init-faces-weak ()
7049   ;; Allow `cperl-find-pods-heres' to run.
7050   (or (boundp 'font-lock-constant-face)
7051       (cperl-force-face font-lock-constant-face
7052                         "Face for constant and label names"))
7053   (or (boundp 'font-lock-warning-face)
7054       (cperl-force-face font-lock-warning-face
7055                         "Face for things which should stand out"))
7056   ;;(setq font-lock-constant-face 'font-lock-constant-face)
7057   )
7058
7059 (defun cperl-init-faces ()
7060   (condition-case errs
7061       (progn
7062         (require 'font-lock)
7063         (and (fboundp 'font-lock-fontify-anchored-keywords)
7064              (featurep 'font-lock-extra)
7065              (message "You have an obsolete package `font-lock-extra'.  Install `choose-color'."))
7066         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
7067           (if (fboundp 'font-lock-fontify-anchored-keywords)
7068               (setq font-lock-anchored t))
7069           (setq
7070            t-font-lock-keywords
7071            (list
7072             (list "[ \t]+$" 0 cperl-invalid-face t)
7073             (cons
7074              (concat
7075               "\\(^\\|[^$@%&\\]\\)\\<\\("
7076               (mapconcat
7077                'identity
7078                '("if" "until" "while" "elsif" "else" "unless" "for"
7079                  "foreach" "continue" "exit" "die" "last" "goto" "next"
7080                  "redo" "return" "local" "exec" "sub" "do" "dump" "use" "our"
7081                  "require" "package" "eval" "my" "BEGIN" "END" "CHECK" "INIT")
7082                "\\|")                   ; Flow control
7083               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
7084                                         ; In what follows we use `type' style
7085                                         ; for overwritable builtins
7086             (list
7087              (concat
7088               "\\(^\\|[^$@%&\\]\\)\\<\\("
7089               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm"
7090               ;; "and" "atan2" "bind" "binmode" "bless" "caller"
7091               ;; "chdir" "chmod" "chown" "chr" "chroot" "close"
7092               ;; "closedir" "cmp" "connect" "continue" "cos" "crypt"
7093               ;; "dbmclose" "dbmopen" "die" "dump" "endgrent"
7094               ;; "endhostent" "endnetent" "endprotoent" "endpwent"
7095               ;; "endservent" "eof" "eq" "exec" "exit" "exp" "fcntl"
7096               ;; "fileno" "flock" "fork" "formline" "ge" "getc"
7097               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr"
7098               ;; "gethostbyname" "gethostent" "getlogin"
7099               ;; "getnetbyaddr" "getnetbyname" "getnetent"
7100               ;; "getpeername" "getpgrp" "getppid" "getpriority"
7101               ;; "getprotobyname" "getprotobynumber" "getprotoent"
7102               ;; "getpwent" "getpwnam" "getpwuid" "getservbyname"
7103               ;; "getservbyport" "getservent" "getsockname"
7104               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int"
7105               ;; "ioctl" "join" "kill" "lc" "lcfirst" "le" "length"
7106               ;; "link" "listen" "localtime" "lock" "log" "lstat" "lt"
7107               ;; "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd" "ne"
7108               ;; "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
7109               ;; "quotemeta" "rand" "read" "readdir" "readline"
7110               ;; "readlink" "readpipe" "recv" "ref" "rename" "require"
7111               ;; "reset" "reverse" "rewinddir" "rindex" "rmdir" "seek"
7112               ;; "seekdir" "select" "semctl" "semget" "semop" "send"
7113               ;; "setgrent" "sethostent" "setnetent" "setpgrp"
7114               ;; "setpriority" "setprotoent" "setpwent" "setservent"
7115               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite"
7116               ;; "shutdown" "sin" "sleep" "socket" "socketpair"
7117               ;; "sprintf" "sqrt" "srand" "stat" "substr" "symlink"
7118               ;; "syscall" "sysopen" "sysread" "system" "syswrite" "tell"
7119               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst"
7120               ;; "umask" "unlink" "unpack" "utime" "values" "vec"
7121               ;; "wait" "waitpid" "wantarray" "warn" "write" "x" "xor"
7122               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|"
7123               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
7124               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
7125               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
7126               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
7127               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
7128               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
7129               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
7130               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
7131               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
7132               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
7133               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
7134               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
7135               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
7136               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
7137               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
7138               "\\(\\|ngth\\)\\|o\\(c\\(altime\\|k\\)\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
7139               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
7140               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
7141               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
7142               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
7143               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
7144               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
7145               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
7146               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
7147               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|open\\|tem\\|write\\)\\|"
7148               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
7149               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
7150               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
7151               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
7152               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\|PACKAGE__\\)"
7153               "\\)\\>") 2 'font-lock-type-face)
7154             ;; In what follows we use `other' style
7155             ;; for nonoverwritable builtins
7156             ;; Somehow 's', 'm' are not auto-generated???
7157             (list
7158              (concat
7159               "\\(^\\|[^$@%&\\]\\)\\<\\("
7160               ;; "AUTOLOAD" "BEGIN" "CHECK" "DESTROY" "END" "INIT" "__END__" "chomp"
7161               ;; "chop" "defined" "delete" "do" "each" "else" "elsif"
7162               ;; "eval" "exists" "for" "foreach" "format" "goto"
7163               ;; "grep" "if" "keys" "last" "local" "map" "my" "next"
7164               ;; "no" "our" "package" "pop" "pos" "print" "printf" "push"
7165               ;; "q" "qq" "qw" "qx" "redo" "return" "scalar" "shift"
7166               ;; "sort" "splice" "split" "study" "sub" "tie" "tr"
7167               ;; "undef" "unless" "unshift" "untie" "until" "use"
7168               ;; "while" "y"
7169               "AUTOLOAD\\|BEGIN\\|CHECK\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
7170               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
7171               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|INIT\\|if\\|keys\\|"
7172               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|our\\|"
7173               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
7174               "q\\(\\|q\\|w\\|x\\|r\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
7175               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
7176               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
7177               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
7178               "\\|[sm]"                 ; Added manually
7179               "\\)\\>") 2 'cperl-nonoverridable-face)
7180             ;;          (mapconcat 'identity
7181             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
7182             ;;                       "#include" "#define" "#undef")
7183             ;;                     "\\|")
7184             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
7185               font-lock-function-name-face keep) ; Not very good, triggers at "[a-z]"
7186             ;; This highlights declarations and definitions differenty.
7187             ;; We do not try to highlight in the case of attributes:
7188             ;; it is already done by `cperl-find-pods-heres'
7189             (list (concat "\\<sub"
7190                           cperl-white-and-comment-rex ; whitespace/comments
7191                           "\\([^ \n\t{;()]+\\)" ; 2=name (assume non-anonymous)
7192                           "\\("
7193                             cperl-maybe-white-and-comment-rex ;whitespace/comments?
7194                             "([^()]*)\\)?" ; prototype
7195                           cperl-maybe-white-and-comment-rex ; whitespace/comments?
7196                           "[{;]")
7197                   2 (if cperl-font-lock-multiline
7198                         '(if (eq (char-after (cperl-1- (match-end 0))) ?\{ )
7199                              'font-lock-function-name-face
7200                            'font-lock-variable-name-face)
7201                       ;; need to manually set 'multiline' for older font-locks
7202                       '(progn
7203                          (if (< 1 (count-lines (match-beginning 0)
7204                                                (match-end 0)))
7205                              (put-text-property
7206                               (+ 3 (match-beginning 0)) (match-end 0)
7207                               'syntax-type 'multiline))
7208                          (if (eq (char-after (cperl-1- (match-end 0))) ?\{ )
7209                              'font-lock-function-name-face
7210                            'font-lock-variable-name-face))))
7211             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
7212               2 font-lock-function-name-face)
7213             '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
7214               1 font-lock-function-name-face)
7215             (cond ((featurep 'font-lock-extra)
7216                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
7217                      (2 font-lock-string-face t)
7218                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
7219                   (font-lock-anchored
7220                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
7221                      (2 font-lock-string-face t)
7222                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
7223                       nil nil
7224                       (1 font-lock-string-face t))))
7225                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
7226                        2 font-lock-string-face t)))
7227             '("[\[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
7228               font-lock-string-face t)
7229             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1
7230               font-lock-constant-face)  ; labels
7231             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
7232               2 font-lock-constant-face)
7233             ;; Uncomment to get perl-mode-like vars
7234             ;;; '("[$*]{?\\(\\sw+\\)" 1 font-lock-variable-name-face)
7235             ;;; '("\\([@%]\\|\\$#\\)\\(\\sw+\\)"
7236             ;;;  (2 (cons font-lock-variable-name-face '(underline))))
7237             (cond ((featurep 'font-lock-extra)
7238                    '("^[ \t]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
7239                      (3 font-lock-variable-name-face)
7240                      (4 '(another 4 nil
7241                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
7242                                    (1 font-lock-variable-name-face)
7243                                    (2 '(restart 2 nil) nil t)))
7244                         nil t)))        ; local variables, multiple
7245                   (font-lock-anchored
7246                    ;; 1=my_etc, 2=white? 3=(+white? 4=white? 5=var
7247                    (` ((, (concat "\\<\\(my\\|local\\|our\\)"
7248                                   cperl-maybe-white-and-comment-rex
7249                                   "\\(("
7250                                      cperl-maybe-white-and-comment-rex
7251                                   "\\)?\\([$@%*]\\([a-zA-Z0-9_:]+\\|[^a-zA-Z0-9_]\\)\\)"))
7252                        (5 (, (if cperl-font-lock-multiline
7253                                  'font-lock-variable-name-face
7254                                '(progn  (setq cperl-font-lock-multiline-start
7255                                               (match-beginning 0))
7256                                         'font-lock-variable-name-face))))
7257                        ((, (concat "\\="
7258                                    cperl-maybe-white-and-comment-rex
7259                                    ","
7260                                    cperl-maybe-white-and-comment-rex
7261                                    "\\([$@%*]\\([a-zA-Z0-9_:]+\\|[^a-zA-Z0-9_]\\)\\)"))
7262                         ;; Bug in font-lock: limit is used not only to limit 
7263                         ;; searches, but to set the "extend window for
7264                         ;; facification" property.  Thus we need to minimize.
7265                         (, (if cperl-font-lock-multiline
7266                              '(if (match-beginning 3)
7267                                   (save-excursion
7268                                     (goto-char (match-beginning 3))
7269                                     (condition-case nil
7270                                         (forward-sexp 1)
7271                                       (error
7272                                        (condition-case nil
7273                                            (forward-char 200)
7274                                          (error nil)))) ; typeahead
7275                                     (1- (point))) ; report limit
7276                                 (forward-char -2)) ; disable continued expr
7277                              '(if (match-beginning 3)
7278                                   (point-max) ; No limit for continuation
7279                                 (forward-char -2)))) ; disable continued expr
7280                         (, (if cperl-font-lock-multiline
7281                                nil
7282                              '(progn    ; Do at end
7283                                 ;; "my" may be already fontified (POD),
7284                                 ;; so cperl-font-lock-multiline-start is nil
7285                                 (if (or (not cperl-font-lock-multiline-start)
7286                                         (> 2 (count-lines
7287                                               cperl-font-lock-multiline-start
7288                                               (point))))
7289                                     nil
7290                                   (put-text-property
7291                                    (1+ cperl-font-lock-multiline-start) (point)
7292                                    'syntax-type 'multiline))
7293                                 (setq cperl-font-lock-multiline-start nil))))
7294                         (3 font-lock-variable-name-face)))))
7295                   (t '("^[ \t{}]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
7296                        3 font-lock-variable-name-face)))
7297             '("\\<for\\(each\\)?\\([ \t]+\\(my\\|local\\|our\\)\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
7298               4 font-lock-variable-name-face)))
7299           (setq
7300            t-font-lock-keywords-1
7301            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
7302                 ;; not yet as of XEmacs 19.12, works with 21.1.11
7303                 (or
7304                  (not cperl-xemacs-p)
7305                  (string< "21.1.9" emacs-version)
7306                  (and (string< "21.1.10" emacs-version)
7307                       (string< emacs-version "21.1.2")))
7308                 '(
7309                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
7310                    (if (eq (char-after (match-beginning 2)) ?%)
7311                        cperl-hash-face
7312                      cperl-array-face)
7313                    t)                   ; arrays and hashes
7314                   ("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
7315                    1
7316                    (if (= (- (match-end 2) (match-beginning 2)) 1)
7317                        (if (eq (char-after (match-beginning 3)) ?{)
7318                            cperl-hash-face
7319                          cperl-array-face) ; arrays and hashes
7320                      font-lock-variable-name-face) ; Just to put something
7321                    t)
7322                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
7323                        ;;; Too much noise from \s* @s[ and friends
7324                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)"
7325                   ;;(3 font-lock-function-name-face t t)
7326                   ;;(4
7327                   ;; (if (cperl-slash-is-regexp)
7328                   ;;    font-lock-function-name-face 'default) nil t))
7329                   )))
7330           (if cperl-highlight-variables-indiscriminately
7331               (setq t-font-lock-keywords-1
7332                     (append t-font-lock-keywords-1
7333                             (list '("[$*]{?\\(\\sw+\\)" 1
7334                                     font-lock-variable-name-face)))))
7335           (setq perl-font-lock-keywords-1
7336                 (if cperl-syntaxify-by-font-lock
7337                     (cons 'cperl-fontify-update
7338                           t-font-lock-keywords)
7339                   t-font-lock-keywords)
7340                 perl-font-lock-keywords perl-font-lock-keywords-1
7341                 perl-font-lock-keywords-2 (append
7342                                            perl-font-lock-keywords-1
7343                                            t-font-lock-keywords-1)))
7344         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
7345         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
7346             (eval                       ; Avoid a warning
7347              '(font-lock-require-faces
7348                (list
7349                 ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
7350                 (list 'font-lock-comment-face
7351                       ["Firebrick"      "OrangeRed"     "DimGray"       "Gray80"]
7352                       nil
7353                       [nil              nil             t               t       t]
7354                       [nil              nil             t               t       t]
7355                       nil)
7356                 (list 'font-lock-string-face
7357                       ["RosyBrown"      "LightSalmon"   "Gray50"        "LightGray"]
7358                       nil
7359                       nil
7360                       [nil              nil             t               t       t]
7361                       nil)
7362                 (list 'font-lock-function-name-face
7363                       (vector
7364                        "Blue"           "LightSkyBlue"  "Gray50"        "LightGray"
7365                        (cdr (assq 'background-color ; if mono
7366                                   (frame-parameters))))
7367                       (vector
7368                        nil              nil             nil             nil
7369                        (cdr (assq 'foreground-color ; if mono
7370                                   (frame-parameters))))
7371                       [nil              nil             t               t       t]
7372                       nil
7373                       nil)
7374                 (list 'font-lock-variable-name-face
7375                       ["DarkGoldenrod"  "LightGoldenrod" "DimGray"      "Gray90"]
7376                       nil
7377                       [nil              nil             t               t       t]
7378                       [nil              nil             t               t       t]
7379                       nil)
7380                 (list 'font-lock-type-face
7381                       ["DarkOliveGreen" "PaleGreen"     "DimGray"       "Gray80"]
7382                       nil
7383                       [nil              nil             t               t       t]
7384                       nil
7385                       [nil              nil             t               t       t])
7386                 (list 'font-lock-warning-face
7387                       ["Pink"           "Red"           "Gray50"        "LightGray"]
7388                       ["gray20"         "gray90"
7389                                                         "gray80"        "gray20"]
7390                       [nil              nil             t               t       t]
7391                       nil
7392                       [nil              nil             t               t       t]
7393                       )
7394                 (list 'font-lock-constant-face
7395                       ["CadetBlue"      "Aquamarine"    "Gray50"        "LightGray"]
7396                       nil
7397                       [nil              nil             t               t       t]
7398                       nil
7399                       [nil              nil             t               t       t])
7400                 (list 'cperl-nonoverridable-face
7401                       ["chartreuse3"    ("orchid1" "orange")
7402                        nil              "Gray80"]
7403                       [nil              nil             "gray90"]
7404                       [nil              nil             nil             t       t]
7405                       [nil              nil             t               t]
7406                       [nil              nil             t               t       t])
7407                 (list 'cperl-array-face
7408                       ["blue"           "yellow"        nil             "Gray80"]
7409                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
7410                        "gray90"]
7411                       t
7412                       nil
7413                       nil)
7414                 (list 'cperl-hash-face
7415                       ["red"            "red"           nil             "Gray80"]
7416                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
7417                        "gray90"]
7418                       t
7419                       t
7420                       nil))))
7421           ;; Do it the dull way, without choose-color
7422           (defvar cperl-guessed-background nil
7423             "Display characteristics as guessed by cperl.")
7424           ;;      (or (fboundp 'x-color-defined-p)
7425           ;;          (defalias 'x-color-defined-p
7426           ;;            (cond ((fboundp 'color-defined-p) 'color-defined-p)
7427           ;;                  ;; XEmacs >= 19.12
7428           ;;                  ((fboundp 'valid-color-name-p) 'valid-color-name-p)
7429           ;;                  ;; XEmacs 19.11
7430           ;;                  (t 'x-valid-color-name-p))))
7431           (cperl-force-face font-lock-constant-face
7432                             "Face for constant and label names")
7433           (cperl-force-face font-lock-variable-name-face
7434                             "Face for variable names")
7435           (cperl-force-face font-lock-type-face
7436                             "Face for data types")
7437           (cperl-force-face cperl-nonoverridable-face
7438                             "Face for data types from another group")
7439           (cperl-force-face font-lock-warning-face
7440                             "Face for things which should stand out")
7441           (cperl-force-face font-lock-comment-face
7442                             "Face for comments")
7443           (cperl-force-face font-lock-function-name-face
7444                             "Face for function names")
7445           (cperl-force-face cperl-hash-face
7446                             "Face for hashes")
7447           (cperl-force-face cperl-array-face
7448                             "Face for arrays")
7449           ;;(defvar font-lock-constant-face 'font-lock-constant-face)
7450           ;;(defvar font-lock-variable-name-face 'font-lock-variable-name-face)
7451           ;;(or (boundp 'font-lock-type-face)
7452           ;;    (defconst font-lock-type-face
7453           ;;    'font-lock-type-face
7454           ;;    "Face to use for data types."))
7455           ;;(or (boundp 'cperl-nonoverridable-face)
7456           ;;    (defconst cperl-nonoverridable-face
7457           ;;    'cperl-nonoverridable-face
7458           ;;    "Face to use for data types from another group."))
7459           ;;(if (not cperl-xemacs-p) nil
7460           ;;  (or (boundp 'font-lock-comment-face)
7461           ;;    (defconst font-lock-comment-face
7462           ;;      'font-lock-comment-face
7463           ;;      "Face to use for comments."))
7464           ;;  (or (boundp 'font-lock-keyword-face)
7465           ;;    (defconst font-lock-keyword-face
7466           ;;      'font-lock-keyword-face
7467           ;;      "Face to use for keywords."))
7468           ;;  (or (boundp 'font-lock-function-name-face)
7469           ;;    (defconst font-lock-function-name-face
7470           ;;      'font-lock-function-name-face
7471           ;;      "Face to use for function names.")))
7472           (if (and
7473                (not (cperl-is-face 'cperl-array-face))
7474                (cperl-is-face 'font-lock-emphasized-face))
7475               (copy-face 'font-lock-emphasized-face 'cperl-array-face))
7476           (if (and
7477                (not (cperl-is-face 'cperl-hash-face))
7478                (cperl-is-face 'font-lock-other-emphasized-face))
7479               (copy-face 'font-lock-other-emphasized-face
7480                          'cperl-hash-face))
7481           (if (and
7482                (not (cperl-is-face 'cperl-nonoverridable-face))
7483                (cperl-is-face 'font-lock-other-type-face))
7484               (copy-face 'font-lock-other-type-face
7485                          'cperl-nonoverridable-face))
7486           ;;(or (boundp 'cperl-hash-face)
7487           ;;    (defconst cperl-hash-face
7488           ;;    'cperl-hash-face
7489           ;;    "Face to use for hashes."))
7490           ;;(or (boundp 'cperl-array-face)
7491           ;;    (defconst cperl-array-face
7492           ;;    'cperl-array-face
7493           ;;    "Face to use for arrays."))
7494           ;; Here we try to guess background
7495           (let ((background
7496                  (if (boundp 'font-lock-background-mode)
7497                      font-lock-background-mode
7498                    'light))
7499                 (face-list (and (fboundp 'face-list) (face-list))))
7500 ;;;;        (fset 'cperl-is-face
7501 ;;;;              (cond ((fboundp 'find-face)
7502 ;;;;                     (symbol-function 'find-face))
7503 ;;;;                    (face-list
7504 ;;;;                     (function (lambda (face) (member face face-list))))
7505 ;;;;                    (t
7506 ;;;;                     (function (lambda (face) (boundp face))))))
7507             (defvar cperl-guessed-background
7508               (if (and (boundp 'font-lock-display-type)
7509                        (eq font-lock-display-type 'grayscale))
7510                   'gray
7511                 background)
7512               "Background as guessed by CPerl mode")
7513             (and (not (cperl-is-face 'font-lock-constant-face))
7514                  (cperl-is-face 'font-lock-reference-face)
7515                  (copy-face 'font-lock-reference-face 'font-lock-constant-face))
7516             (if (cperl-is-face 'font-lock-type-face) nil
7517               (copy-face 'default 'font-lock-type-face)
7518               (cond
7519                ((eq background 'light)
7520                 (set-face-foreground 'font-lock-type-face
7521                                      (if (x-color-defined-p "seagreen")
7522                                          "seagreen"
7523                                        "sea green")))
7524                ((eq background 'dark)
7525                 (set-face-foreground 'font-lock-type-face
7526                                      (if (x-color-defined-p "os2pink")
7527                                          "os2pink"
7528                                        "pink")))
7529                (t
7530                 (set-face-background 'font-lock-type-face "gray90"))))
7531             (if (cperl-is-face 'cperl-nonoverridable-face)
7532                 nil
7533               (copy-face 'font-lock-type-face 'cperl-nonoverridable-face)
7534               (cond
7535                ((eq background 'light)
7536                 (set-face-foreground 'cperl-nonoverridable-face
7537                                      (if (x-color-defined-p "chartreuse3")
7538                                          "chartreuse3"
7539                                        "chartreuse")))
7540                ((eq background 'dark)
7541                 (set-face-foreground 'cperl-nonoverridable-face
7542                                      (if (x-color-defined-p "orchid1")
7543                                          "orchid1"
7544                                        "orange")))))
7545 ;;;         (if (cperl-is-face 'font-lock-other-emphasized-face) nil
7546 ;;;           (copy-face 'bold-italic 'font-lock-other-emphasized-face)
7547 ;;;           (cond
7548 ;;;            ((eq background 'light)
7549 ;;;             (set-face-background 'font-lock-other-emphasized-face
7550 ;;;                                  (if (x-color-defined-p "lightyellow2")
7551 ;;;                                      "lightyellow2"
7552 ;;;                                    (if (x-color-defined-p "lightyellow")
7553 ;;;                                        "lightyellow"
7554 ;;;                                      "light yellow"))))
7555 ;;;            ((eq background 'dark)
7556 ;;;             (set-face-background 'font-lock-other-emphasized-face
7557 ;;;                                  (if (x-color-defined-p "navy")
7558 ;;;                                      "navy"
7559 ;;;                                    (if (x-color-defined-p "darkgreen")
7560 ;;;                                        "darkgreen"
7561 ;;;                                      "dark green"))))
7562 ;;;            (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
7563 ;;;         (if (cperl-is-face 'font-lock-emphasized-face) nil
7564 ;;;           (copy-face 'bold 'font-lock-emphasized-face)
7565 ;;;           (cond
7566 ;;;            ((eq background 'light)
7567 ;;;             (set-face-background 'font-lock-emphasized-face
7568 ;;;                                  (if (x-color-defined-p "lightyellow2")
7569 ;;;                                      "lightyellow2"
7570 ;;;                                    "lightyellow")))
7571 ;;;            ((eq background 'dark)
7572 ;;;             (set-face-background 'font-lock-emphasized-face
7573 ;;;                                  (if (x-color-defined-p "navy")
7574 ;;;                                      "navy"
7575 ;;;                                    (if (x-color-defined-p "darkgreen")
7576 ;;;                                        "darkgreen"
7577 ;;;                                      "dark green"))))
7578 ;;;            (t (set-face-background 'font-lock-emphasized-face "gray90"))))
7579             (if (cperl-is-face 'font-lock-variable-name-face) nil
7580               (copy-face 'italic 'font-lock-variable-name-face))
7581             (if (cperl-is-face 'font-lock-constant-face) nil
7582               (copy-face 'italic 'font-lock-constant-face))))
7583         (setq cperl-faces-init t))
7584     (error (message "cperl-init-faces (ignored): %s" errs))))
7585
7586
7587 (defun cperl-ps-print-init ()
7588   "Initialization of `ps-print' components for faces used in CPerl."
7589   (eval-after-load "ps-print"
7590     '(setq ps-bold-faces
7591            ;;                   font-lock-variable-name-face
7592            ;;                   font-lock-constant-face
7593            (append '(cperl-array-face
7594                      cperl-hash-face)
7595                    ps-bold-faces)
7596            ps-italic-faces
7597            ;;                   font-lock-constant-face
7598            (append '(cperl-nonoverridable-face
7599                      cperl-hash-face)
7600                    ps-italic-faces)
7601            ps-underlined-faces
7602            ;;        font-lock-type-face
7603            (append '(cperl-array-face
7604                      cperl-hash-face
7605                      underline
7606                      cperl-nonoverridable-face)
7607                    ps-underlined-faces))))
7608
7609 (defvar ps-print-face-extension-alist)
7610
7611 (defun cperl-ps-print (&optional file)
7612   "Pretty-print in CPerl style.
7613 If optional argument FILE is an empty string, prints to printer, otherwise
7614 to the file FILE.  If FILE is nil, prompts for a file name.
7615
7616 Style of printout regulated by the variable `cperl-ps-print-face-properties'."
7617   (interactive)
7618   (or file
7619       (setq file (read-from-minibuffer
7620                   "Print to file (if empty - to printer): "
7621                   (concat (buffer-file-name) ".ps")
7622                   nil nil 'file-name-history)))
7623   (or (> (length file) 0)
7624       (setq file nil))
7625   (require 'ps-print)                   ; To get ps-print-face-extension-alist
7626   (let ((ps-print-color-p t)
7627         (ps-print-face-extension-alist ps-print-face-extension-alist))
7628     (cperl-ps-extend-face-list cperl-ps-print-face-properties)
7629     (ps-print-buffer-with-faces file)))
7630
7631 ;;; (defun cperl-ps-print-init ()
7632 ;;;   "Initialization of `ps-print' components for faces used in CPerl."
7633 ;;;   ;; Guard against old versions
7634 ;;;   (defvar ps-underlined-faces nil)
7635 ;;;   (defvar ps-bold-faces nil)
7636 ;;;   (defvar ps-italic-faces nil)
7637 ;;;   (setq ps-bold-faces
7638 ;;;     (append '(font-lock-emphasized-face
7639 ;;;               cperl-array-face
7640 ;;;               font-lock-keyword-face
7641 ;;;               font-lock-variable-name-face
7642 ;;;               font-lock-constant-face
7643 ;;;               font-lock-reference-face
7644 ;;;               font-lock-other-emphasized-face
7645 ;;;               cperl-hash-face)
7646 ;;;             ps-bold-faces))
7647 ;;;   (setq ps-italic-faces
7648 ;;;     (append '(cperl-nonoverridable-face
7649 ;;;               font-lock-constant-face
7650 ;;;               font-lock-reference-face
7651 ;;;               font-lock-other-emphasized-face
7652 ;;;               cperl-hash-face)
7653 ;;;             ps-italic-faces))
7654 ;;;   (setq ps-underlined-faces
7655 ;;;     (append '(font-lock-emphasized-face
7656 ;;;               cperl-array-face
7657 ;;;               font-lock-other-emphasized-face
7658 ;;;               cperl-hash-face
7659 ;;;               cperl-nonoverridable-face font-lock-type-face)
7660 ;;;             ps-underlined-faces))
7661 ;;;   (cons 'font-lock-type-face ps-underlined-faces))
7662
7663
7664 (if (cperl-enable-font-lock) (cperl-windowed-init))
7665
7666 (defconst cperl-styles-entries
7667   '(cperl-indent-level cperl-brace-offset cperl-continued-brace-offset
7668     cperl-label-offset cperl-extra-newline-before-brace
7669     cperl-merge-trailing-else
7670     cperl-continued-statement-offset))
7671
7672 (defconst cperl-style-alist
7673   '(("CPerl"                         ; =GNU without extra-newline-before-brace
7674      (cperl-indent-level               .  2)
7675      (cperl-brace-offset               .  0)
7676      (cperl-continued-brace-offset     .  0)
7677      (cperl-label-offset               . -2)
7678      (cperl-extra-newline-before-brace .  nil)
7679      (cperl-merge-trailing-else        .  t)
7680      (cperl-continued-statement-offset .  2))
7681     ("PerlStyle"                        ; CPerl with 4 as indent
7682      (cperl-indent-level               .  4)
7683      (cperl-brace-offset               .  0)
7684      (cperl-continued-brace-offset     .  0)
7685      (cperl-label-offset               . -4)
7686      (cperl-extra-newline-before-brace .  nil)
7687      (cperl-merge-trailing-else        .  t)
7688      (cperl-continued-statement-offset .  4))
7689     ("GNU"
7690      (cperl-indent-level               .  2)
7691      (cperl-brace-offset               .  0)
7692      (cperl-continued-brace-offset     .  0)
7693      (cperl-label-offset               . -2)
7694      (cperl-extra-newline-before-brace .  t)
7695      (cperl-merge-trailing-else        .  nil)
7696      (cperl-continued-statement-offset .  2))
7697     ("K&R"
7698      (cperl-indent-level               .  5)
7699      (cperl-brace-offset               .  0)
7700      (cperl-continued-brace-offset     . -5)
7701      (cperl-label-offset               . -5)
7702      ;;(cperl-extra-newline-before-brace .  nil) ; ???
7703      (cperl-merge-trailing-else        .  nil)
7704      (cperl-continued-statement-offset .  5))
7705     ("BSD"
7706      (cperl-indent-level               .  4)
7707      (cperl-brace-offset               .  0)
7708      (cperl-continued-brace-offset     . -4)
7709      (cperl-label-offset               . -4)
7710      ;;(cperl-extra-newline-before-brace .  nil) ; ???
7711      (cperl-continued-statement-offset .  4))
7712     ("C++"
7713      (cperl-indent-level               .  4)
7714      (cperl-brace-offset               .  0)
7715      (cperl-continued-brace-offset     . -4)
7716      (cperl-label-offset               . -4)
7717      (cperl-continued-statement-offset .  4)
7718      (cperl-merge-trailing-else        .  nil)
7719      (cperl-extra-newline-before-brace .  t))
7720     ("Current")
7721     ("Whitesmith"
7722      (cperl-indent-level               .  4)
7723      (cperl-brace-offset               .  0)
7724      (cperl-continued-brace-offset     .  0)
7725      (cperl-label-offset               . -4)
7726      ;;(cperl-extra-newline-before-brace .  nil) ; ???
7727      (cperl-continued-statement-offset .  4)))
7728   "(Experimental) list of variables to set to get a particular indentation style.
7729 Should be used via `cperl-set-style' or via Perl menu.")
7730
7731 (defun cperl-set-style (style)
7732   "Set CPerl mode variables to use one of several different indentation styles.
7733 The arguments are a string representing the desired style.
7734 The list of styles is in `cperl-style-alist', available styles
7735 are GNU, K&R, BSD, C++ and Whitesmith.
7736
7737 The current value of style is memorized (unless there is a memorized
7738 data already), may be restored by `cperl-set-style-back'.
7739
7740 Chosing \"Current\" style will not change style, so this may be used for
7741 side-effect of memorizing only."
7742   (interactive
7743    (let ((list (mapcar (function (lambda (elt) (list (car elt))))
7744                        cperl-style-alist)))
7745      (list (completing-read "Enter style: " list nil 'insist))))
7746   (or cperl-old-style
7747       (setq cperl-old-style
7748             (mapcar (function
7749                      (lambda (name)
7750                        (cons name (eval name))))
7751                     cperl-styles-entries)))
7752   (let ((style (cdr (assoc style cperl-style-alist))) setting str sym)
7753     (while style
7754       (setq setting (car style) style (cdr style))
7755       (set (car setting) (cdr setting)))))
7756
7757 (defun cperl-set-style-back ()
7758   "Restore a style memorised by `cperl-set-style'."
7759   (interactive)
7760   (or cperl-old-style (error "The style was not changed"))
7761   (let (setting)
7762     (while cperl-old-style
7763       (setq setting (car cperl-old-style)
7764             cperl-old-style (cdr cperl-old-style))
7765       (set (car setting) (cdr setting)))))
7766
7767 (defun cperl-check-syntax ()
7768   (interactive)
7769   (require 'mode-compile)
7770   (let ((perl-dbg-flags (concat cperl-extra-perl-args " -wc")))
7771     (eval '(mode-compile))))            ; Avoid a warning
7772
7773 (defun cperl-info-buffer (type)
7774   ;; Returns buffer with documentation.  Creates if missing.
7775   ;; If TYPE, this vars buffer.
7776   ;; Special care is taken to not stomp over an existing info buffer
7777   (let* ((bname (if type "*info-perl-var*" "*info-perl*"))
7778          (info (get-buffer bname))
7779          (oldbuf (get-buffer "*info*")))
7780     (if info info
7781       (save-window-excursion
7782         ;; Get Info running
7783         (require 'info)
7784         (cond (oldbuf
7785                (set-buffer oldbuf)
7786                (rename-buffer "*info-perl-tmp*")))
7787         (save-window-excursion
7788           (info))
7789         (Info-find-node cperl-info-page (if type "perlvar" "perlfunc"))
7790         (set-buffer "*info*")
7791         (rename-buffer bname)
7792         (cond (oldbuf
7793                (set-buffer "*info-perl-tmp*")
7794                (rename-buffer "*info*")
7795                (set-buffer bname)))
7796         (make-local-variable 'window-min-height)
7797         (setq window-min-height 2)
7798         (current-buffer)))))
7799
7800 (defun cperl-word-at-point (&optional p)
7801   "Return the word at point or at P."
7802   (save-excursion
7803     (if p (goto-char p))
7804     (or (cperl-word-at-point-hard)
7805         (progn
7806           (require 'etags)
7807           (funcall (or (and (boundp 'find-tag-default-function)
7808                             find-tag-default-function)
7809                        (get major-mode 'find-tag-default-function)
7810                        ;; XEmacs 19.12 has `find-tag-default-hook'; it is
7811                        ;; automatically used within `find-tag-default':
7812                        'find-tag-default))))))
7813
7814 (defun cperl-info-on-command (command)
7815   "Show documentation for Perl command COMMAND in other window.
7816 If perl-info buffer is shown in some frame, uses this frame.
7817 Customized by setting variables `cperl-shrink-wrap-info-frame',
7818 `cperl-max-help-size'."
7819   (interactive
7820    (let* ((default (cperl-word-at-point))
7821           (read (read-string
7822                  (format "Find doc for Perl function (default %s): "
7823                          default))))
7824      (list (if (equal read "")
7825                default
7826              read))))
7827
7828   (let ((buffer (current-buffer))
7829         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
7830         pos isvar height iniheight frheight buf win fr1 fr2 iniwin not-loner
7831         max-height char-height buf-list)
7832     (if (string-match "^-[a-zA-Z]$" command)
7833         (setq cmd-desc "^-X[ \t\n]"))
7834     (setq isvar (string-match "^[$@%]" command)
7835           buf (cperl-info-buffer isvar)
7836           iniwin (selected-window)
7837           fr1 (window-frame iniwin))
7838     (set-buffer buf)
7839     (goto-char (point-min))
7840     (or isvar
7841         (progn (re-search-forward "^-X[ \t\n]")
7842                (forward-line -1)))
7843     (if (re-search-forward cmd-desc nil t)
7844         (progn
7845           ;; Go back to beginning of the group (ex, for qq)
7846           (if (re-search-backward "^[ \t\n\f]")
7847               (forward-line 1))
7848           (beginning-of-line)
7849           ;; Get some of
7850           (setq pos (point)
7851                 buf-list (list buf "*info-perl-var*" "*info-perl*"))
7852           (while (and (not win) buf-list)
7853             (setq win (get-buffer-window (car buf-list) t))
7854             (setq buf-list (cdr buf-list)))
7855           (or (not win)
7856               (eq (window-buffer win) buf)
7857               (set-window-buffer win buf))
7858           (and win (setq fr2 (window-frame win)))
7859           (if (or (not fr2) (eq fr1 fr2))
7860               (pop-to-buffer buf)
7861             (special-display-popup-frame buf) ; Make it visible
7862             (select-window win))
7863           (goto-char pos)               ; Needed (?!).
7864           ;; Resize
7865           (setq iniheight (window-height)
7866                 frheight (frame-height)
7867                 not-loner (< iniheight (1- frheight))) ; Are not alone
7868           (cond ((if not-loner cperl-max-help-size
7869                    cperl-shrink-wrap-info-frame)
7870                  (setq height
7871                        (+ 2
7872                           (count-lines
7873                            pos
7874                            (save-excursion
7875                              (if (re-search-forward
7876                                   "^[ \t][^\n]*\n+\\([^ \t\n\f]\\|\\'\\)" nil t)
7877                                  (match-beginning 0) (point-max)))))
7878                        max-height
7879                        (if not-loner
7880                            (/ (* (- frheight 3) cperl-max-help-size) 100)
7881                          (setq char-height (frame-char-height))
7882                          ;; Non-functioning under OS/2:
7883                          (if (eq char-height 1) (setq char-height 18))
7884                          ;; Title, menubar, + 2 for slack
7885                          (- (/ (x-display-pixel-height) char-height) 4)))
7886                  (if (> height max-height) (setq height max-height))
7887                  ;;(message "was %s doing %s" iniheight height)
7888                  (if not-loner
7889                      (enlarge-window (- height iniheight))
7890                    (set-frame-height (window-frame win) (1+ height)))))
7891           (set-window-start (selected-window) pos))
7892       (message "No entry for %s found." command))
7893     ;;(pop-to-buffer buffer)
7894     (select-window iniwin)))
7895
7896 (defun cperl-info-on-current-command ()
7897   "Show documentation for Perl command at point in other window."
7898   (interactive)
7899   (cperl-info-on-command (cperl-word-at-point)))
7900
7901 (defun cperl-imenu-info-imenu-search ()
7902   (if (looking-at "^-X[ \t\n]") nil
7903     (re-search-backward
7904      "^\n\\([-a-zA-Z_]+\\)[ \t\n]")
7905     (forward-line 1)))
7906
7907 (defun cperl-imenu-info-imenu-name ()
7908   (buffer-substring
7909    (match-beginning 1) (match-end 1)))
7910
7911 (defun cperl-imenu-on-info ()
7912   "Shows imenu for Perl Info Buffer.
7913 Opens Perl Info buffer if needed."
7914   (interactive)
7915   (let* ((buffer (current-buffer))
7916          imenu-create-index-function
7917          imenu-prev-index-position-function
7918          imenu-extract-index-name-function
7919          (index-item (save-restriction
7920                        (save-window-excursion
7921                          (set-buffer (cperl-info-buffer nil))
7922                          (setq imenu-create-index-function
7923                                'imenu-default-create-index-function
7924                                imenu-prev-index-position-function
7925                                'cperl-imenu-info-imenu-search
7926                                imenu-extract-index-name-function
7927                                'cperl-imenu-info-imenu-name)
7928                          (imenu-choose-buffer-index)))))
7929     (and index-item
7930          (progn
7931            (push-mark)
7932            (pop-to-buffer "*info-perl*")
7933            (cond
7934             ((markerp (cdr index-item))
7935              (goto-char (marker-position (cdr index-item))))
7936             (t
7937              (goto-char (cdr index-item))))
7938            (set-window-start (selected-window) (point))
7939            (pop-to-buffer buffer)))))
7940
7941 (defun cperl-lineup (beg end &optional step minshift)
7942   "Lineup construction in a region.
7943 Beginning of region should be at the start of a construction.
7944 All first occurrences of this construction in the lines that are
7945 partially contained in the region are lined up at the same column.
7946
7947 MINSHIFT is the minimal amount of space to insert before the construction.
7948 STEP is the tabwidth to position constructions.
7949 If STEP is nil, `cperl-lineup-step' will be used
7950 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
7951 Will not move the position at the start to the left."
7952   (interactive "r")
7953   (let (search col tcol seen b)
7954     (save-excursion
7955       (goto-char end)
7956       (end-of-line)
7957       (setq end (point-marker))
7958       (goto-char beg)
7959       (skip-chars-forward " \t\f")
7960       (setq beg (point-marker))
7961       (indent-region beg end nil)
7962       (goto-char beg)
7963       (setq col (current-column))
7964       (if (looking-at "[a-zA-Z0-9_]")
7965           (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
7966               (setq search
7967                     (concat "\\<"
7968                             (regexp-quote
7969                              (buffer-substring (match-beginning 0)
7970                                                (match-end 0))) "\\>"))
7971             (error "Cannot line up in a middle of the word"))
7972         (if (looking-at "$")
7973             (error "Cannot line up end of line"))
7974         (setq search (regexp-quote (char-to-string (following-char)))))
7975       (setq step (or step cperl-lineup-step cperl-indent-level))
7976       (or minshift (setq minshift 1))
7977       (while (progn
7978                (beginning-of-line 2)
7979                (and (< (point) end)
7980                     (re-search-forward search end t)
7981                     (goto-char (match-beginning 0))))
7982         (setq tcol (current-column) seen t)
7983         (if (> tcol col) (setq col tcol)))
7984       (or seen
7985           (error "The construction to line up occurred only once"))
7986       (goto-char beg)
7987       (setq col (+ col minshift))
7988       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
7989       (while
7990           (progn
7991             (cperl-make-indent col)
7992             (beginning-of-line 2)
7993             (and (< (point) end)
7994                  (re-search-forward search end t)
7995                  (goto-char (match-beginning 0)))))))) ; No body
7996
7997 (defun cperl-etags (&optional add all files) ;; NOT USED???
7998   "Run etags with appropriate options for Perl files.
7999 If optional argument ALL is `recursive', will process Perl files
8000 in subdirectories too."
8001   (interactive)
8002   (let ((cmd "etags")
8003         (args '("-l" "none" "-r"
8004                 ;;       1=fullname  2=package?             3=name                       4=proto?             5=attrs? (VERY APPROX!)
8005                 "/\\<sub[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)\\)[ \\t]*\\(([^()]*)[ \t]*\\)?\\([ \t]*:[^#{;]*\\)?\\([{#]\\|$\\)/\\3/"
8006                 "-r"
8007                 "/\\<package[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)\\)[ \\t]*\\([#;]\\|$\\)/\\1/"
8008                 "-r"
8009                 "/\\<\\(package\\)[ \\t]*;/\\1;/"))
8010         res)
8011     (if add (setq args (cons "-a" args)))
8012     (or files (setq files (list buffer-file-name)))
8013     (cond
8014      ((eq all 'recursive)
8015       ;;(error "Not implemented: recursive")
8016       (setq args (append (list "-e"
8017                                "sub wanted {push @ARGV, $File::Find::name if /\\.[pP][Llm]$/}
8018                                 use File::Find;
8019                                 find(\\&wanted, '.');
8020                                 exec @ARGV;"
8021                                cmd) args)
8022             cmd "perl"))
8023      (all
8024       ;;(error "Not implemented: all")
8025       (setq args (append (list "-e"
8026                                "push @ARGV, <*.PL *.pl *.pm>;
8027                                 exec @ARGV;"
8028                                cmd) args)
8029             cmd "perl"))
8030      (t
8031       (setq args (append args files))))
8032     (setq res (apply 'call-process cmd nil nil nil args))
8033     (or (eq res 0)
8034         (message "etags returned \"%s\"" res))))
8035
8036 (defun cperl-toggle-auto-newline ()
8037   "Toggle the state of `cperl-auto-newline'."
8038   (interactive)
8039   (setq cperl-auto-newline (not cperl-auto-newline))
8040   (message "Newlines will %sbe auto-inserted now."
8041            (if cperl-auto-newline "" "not ")))
8042
8043 (defun cperl-toggle-abbrev ()
8044   "Toggle the state of automatic keyword expansion in CPerl mode."
8045   (interactive)
8046   (abbrev-mode (if abbrev-mode 0 1))
8047   (message "Perl control structure will %sbe auto-inserted now."
8048            (if abbrev-mode "" "not ")))
8049
8050
8051 (defun cperl-toggle-electric ()
8052   "Toggle the state of parentheses doubling in CPerl mode."
8053   (interactive)
8054   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
8055   (message "Parentheses will %sbe auto-doubled now."
8056            (if (cperl-val 'cperl-electric-parens) "" "not ")))
8057
8058 (defun cperl-toggle-autohelp ()
8059   "Toggle the state of Auto-Help on Perl constructs (put in the message area).
8060 Delay of auto-help controlled by `cperl-lazy-help-time'."
8061   (interactive)
8062   (if (fboundp 'run-with-idle-timer)
8063       (progn
8064         (if cperl-lazy-installed
8065             (cperl-lazy-unstall)
8066           (cperl-lazy-install))
8067         (message "Perl help messages will %sbe automatically shown now."
8068                  (if cperl-lazy-installed "" "not ")))
8069     (message "Cannot automatically show Perl help messages - run-with-idle-timer missing.")))
8070
8071 (defun cperl-toggle-construct-fix ()
8072   "Toggle whether `indent-region'/`indent-sexp' fix whitespace too."
8073   (interactive)
8074   (setq cperl-indent-region-fix-constructs
8075         (if cperl-indent-region-fix-constructs
8076             nil
8077           1))
8078   (message "indent-region/indent-sexp will %sbe automatically fix whitespace."
8079            (if cperl-indent-region-fix-constructs "" "not ")))
8080
8081 (defun cperl-toggle-set-debug-unwind (arg &optional backtrace)
8082   "Toggle (or, with numeric argument, set) debugging state of syntaxification.
8083 Nonpositive numeric argument disables debugging messages.  The message
8084 summarizes which regions it was decided to rescan for syntactic constructs.
8085
8086 The message looks like this:
8087
8088   Syxify req=123..138 actual=101..146 done-to: 112=>146 statepos: 73=>117
8089
8090 Numbers are character positions in the buffer.  REQ provides the range to
8091 rescan requested by `font-lock'.  ACTUAL is the range actually resyntaxified;
8092 for correct operation it should start and end outside any special syntactic
8093 construct.  DONE-TO and STATEPOS indicate changes to internal caches maintained
8094 by CPerl."
8095   (interactive "P")
8096   (or arg
8097       (setq arg (if (eq cperl-syntaxify-by-font-lock 
8098                         (if backtrace 'backtrace 'message)) 0 1)))
8099   (setq arg (if (> arg 0) (if backtrace 'backtrace 'message) t))
8100   (setq cperl-syntaxify-by-font-lock arg)
8101   (message "Debugging messages of syntax unwind %sabled."
8102            (if (eq arg t) "dis" "en")))
8103
8104 ;;;; Tags file creation.
8105
8106 (defvar cperl-tmp-buffer " *cperl-tmp*")
8107
8108 (defun cperl-setup-tmp-buf ()
8109   (set-buffer (get-buffer-create cperl-tmp-buffer))
8110   (set-syntax-table cperl-mode-syntax-table)
8111   (buffer-disable-undo)
8112   (auto-fill-mode 0)
8113   (if cperl-use-syntax-table-text-property-for-tags
8114       (progn
8115         (make-local-variable 'parse-sexp-lookup-properties)
8116         ;; Do not introduce variable if not needed, we check it!
8117         (set 'parse-sexp-lookup-properties t))))
8118
8119 (defun cperl-xsub-scan ()
8120   (require 'cl)
8121   (require 'imenu)
8122   (let ((index-alist '())
8123         (prev-pos 0) index index1 name package prefix)
8124     (goto-char (point-min))
8125     (if noninteractive
8126         (message "Scanning XSUB for index")
8127       (imenu-progress-message prev-pos 0))
8128     ;; Search for the function
8129     (progn ;;save-match-data
8130       (while (re-search-forward
8131               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
8132               nil t)
8133         (or noninteractive
8134             (imenu-progress-message prev-pos))
8135         (cond
8136          ((match-beginning 2)           ; SECTION
8137           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
8138           (goto-char (match-beginning 0))
8139           (skip-chars-forward " \t")
8140           (forward-char 1)
8141           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
8142               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
8143             (setq prefix nil)))
8144          ((not package) nil)            ; C language section
8145          ((match-beginning 3)           ; XSUB
8146           (goto-char (1+ (match-beginning 3)))
8147           (setq index (imenu-example--name-and-position))
8148           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
8149           (if (and prefix (string-match (concat "^" prefix) name))
8150               (setq name (substring name (length prefix))))
8151           (cond ((string-match "::" name) nil)
8152                 (t
8153                  (setq index1 (cons (concat package "::" name) (cdr index)))
8154                  (push index1 index-alist)))
8155           (setcar index name)
8156           (push index index-alist))
8157          (t                             ; BOOT: section
8158           ;; (beginning-of-line)
8159           (setq index (imenu-example--name-and-position))
8160           (setcar index (concat package "::BOOT:"))
8161           (push index index-alist)))))
8162     (or noninteractive
8163         (imenu-progress-message prev-pos 100))
8164     index-alist))
8165
8166 (defvar cperl-unreadable-ok nil)
8167
8168 (defun cperl-find-tags (ifile xs topdir)
8169   (let ((b (get-buffer cperl-tmp-buffer)) ind lst elt pos ret rel
8170         (cperl-pod-here-fontify nil) f file)
8171     (save-excursion
8172       (if b (set-buffer b)
8173         (cperl-setup-tmp-buf))
8174       (erase-buffer)
8175       (condition-case err
8176           (setq file (car (insert-file-contents ifile)))
8177         (error (if cperl-unreadable-ok nil
8178                  (if (y-or-n-p
8179                       (format "File %s unreadable.  Continue? " ifile))
8180                      (setq cperl-unreadable-ok t)
8181                    (error "Aborting: unreadable file %s" ifile)))))
8182       (if (not file)
8183           (message "Unreadable file %s" ifile)
8184         (message "Scanning file %s ..." file)
8185         (if (and cperl-use-syntax-table-text-property-for-tags
8186                  (not xs))
8187             (condition-case err         ; after __END__ may have garbage
8188                 (cperl-find-pods-heres nil nil noninteractive)
8189               (error (message "While scanning for syntax: %s" err))))
8190         (if xs
8191             (setq lst (cperl-xsub-scan))
8192           (setq ind (cperl-imenu--create-perl-index))
8193           (setq lst (cdr (assoc "+Unsorted List+..." ind))))
8194         (setq lst
8195               (mapcar
8196                (function
8197                 (lambda (elt)
8198                   (cond ((string-match "^[_a-zA-Z]" (car elt))
8199                          (goto-char (cdr elt))
8200                          (beginning-of-line) ; pos should be of the start of the line
8201                          (list (car elt)
8202                                (point)
8203                                (1+ (count-lines 1 (point))) ; 1+ since at beg-o-l
8204                                (buffer-substring (progn
8205                                                    (goto-char (cdr elt))
8206                                                    ;; After name now...
8207                                                    (or (eolp) (forward-char 1))
8208                                                    (point))
8209                                                  (progn
8210                                                    (beginning-of-line)
8211                                                    (point))))))))
8212                lst))
8213         (erase-buffer)
8214         (while lst
8215           (setq elt (car lst) lst (cdr lst))
8216           (if elt
8217               (progn
8218                 (insert (elt elt 3)
8219                         127
8220                         (if (string-match "^package " (car elt))
8221                             (substring (car elt) 8)
8222                           (car elt) )
8223                         1
8224                         (number-to-string (elt elt 2)) ; Line
8225                         ","
8226                         (number-to-string (1- (elt elt 1))) ; Char pos 0-based
8227                         "\n")
8228                 (if (and (string-match "^[_a-zA-Z]+::" (car elt))
8229                          (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
8230                                        (elt elt 3)))
8231                     ;; Need to insert the name without package as well
8232                     (setq lst (cons (cons (substring (elt elt 3)
8233                                                      (match-beginning 1)
8234                                                      (match-end 1))
8235                                           (cdr elt))
8236                                     lst))))))
8237         (setq pos (point))
8238         (goto-char 1)
8239         (setq rel file)
8240         ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
8241         (set-text-properties 0 (length rel) nil rel)
8242         (and (equal topdir (substring rel 0 (length topdir)))
8243              (setq rel (substring file (length topdir))))
8244         (insert "\f\n" rel "," (number-to-string (1- pos)) "\n")
8245         (setq ret (buffer-substring 1 (point-max)))
8246         (erase-buffer)
8247         (or noninteractive
8248             (message "Scanning file %s finished" file))
8249         ret))))
8250
8251 (defun cperl-add-tags-recurse-noxs ()
8252   "Add to TAGS data for \"pure\" Perl files in the current directory and kids.
8253 Use as
8254   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
8255         -f cperl-add-tags-recurse-noxs
8256 "
8257   (cperl-write-tags nil nil t t nil t))
8258
8259 (defun cperl-add-tags-recurse-noxs-fullpath ()
8260   "Add to TAGS data for \"pure\" Perl in the current directory and kids.
8261 Writes down fullpath, so TAGS is relocatable (but if the build directory
8262 is relocated, the file TAGS inside it breaks). Use as
8263   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
8264         -f cperl-add-tags-recurse-noxs-fullpath
8265 "
8266   (cperl-write-tags nil nil t t nil t ""))
8267
8268 (defun cperl-add-tags-recurse ()
8269   "Add to TAGS file data for Perl files in the current directory and kids.
8270 Use as
8271   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
8272         -f cperl-add-tags-recurse
8273 "
8274   (cperl-write-tags nil nil t t))
8275
8276 (defun cperl-write-tags (&optional file erase recurse dir inbuffer noxs topdir)
8277   ;; If INBUFFER, do not select buffer, and do not save
8278   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
8279   (require 'etags)
8280   (if file nil
8281     (setq file (if dir default-directory (buffer-file-name)))
8282     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
8283   (or topdir
8284       (setq topdir default-directory))
8285   (let ((tags-file-name "TAGS")
8286         (case-fold-search (eq system-type 'emx))
8287         xs rel tm)
8288     (save-excursion
8289       (cond (inbuffer nil)              ; Already there
8290             ((file-exists-p tags-file-name)
8291              (if cperl-xemacs-p
8292                  (visit-tags-table-buffer)
8293                (visit-tags-table-buffer tags-file-name)))
8294             (t (set-buffer (find-file-noselect tags-file-name))))
8295       (cond
8296        (dir
8297         (cond ((eq erase 'ignore))
8298               (erase
8299                (erase-buffer)
8300                (setq erase 'ignore)))
8301         (let ((files
8302                (condition-case err
8303                    (directory-files file t
8304                                     (if recurse nil cperl-scan-files-regexp)
8305                                     t)
8306                  (error
8307                   (if cperl-unreadable-ok nil
8308                     (if (y-or-n-p
8309                          (format "Directory %s unreadable.  Continue? " file))
8310                         (setq cperl-unreadable-ok t
8311                               tm nil)   ; Return empty list
8312                       (error "Aborting: unreadable directory %s" file)))))))
8313           (mapcar (function
8314                    (lambda (file)
8315                      (cond
8316                       ((string-match cperl-noscan-files-regexp file)
8317                        nil)
8318                       ((not (file-directory-p file))
8319                        (if (string-match cperl-scan-files-regexp file)
8320                            (cperl-write-tags file erase recurse nil t noxs topdir)))
8321                       ((not recurse) nil)
8322                       (t (cperl-write-tags file erase recurse t t noxs topdir)))))
8323                   files)))
8324        (t
8325         (setq xs (string-match "\\.xs$" file))
8326         (if (not (and xs noxs))
8327             (progn
8328               (cond ((eq erase 'ignore) (goto-char (point-max)))
8329                     (erase (erase-buffer))
8330                     (t
8331                      (goto-char 1)
8332                      (setq rel file)
8333                      ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
8334                      (set-text-properties 0 (length rel) nil rel)
8335                      (and (equal topdir (substring rel 0 (length topdir)))
8336                           (setq rel (substring file (length topdir))))
8337                      (if (search-forward (concat "\f\n" rel ",") nil t)
8338                          (progn
8339                            (search-backward "\f\n")
8340                            (delete-region (point)
8341                                           (save-excursion
8342                                             (forward-char 1)
8343                                             (if (search-forward "\f\n"
8344                                                                 nil 'toend)
8345                                                 (- (point) 2)
8346                                               (point-max)))))
8347                        (goto-char (point-max)))))
8348               (insert (cperl-find-tags file xs topdir))))))
8349       (if inbuffer nil                  ; Delegate to the caller
8350         (save-buffer 0)                 ; No backup
8351         (if (fboundp 'initialize-new-tags-table) ; Do we need something special in XEmacs?
8352             (initialize-new-tags-table))))))
8353
8354 (defvar cperl-tags-hier-regexp-list
8355   (concat
8356    "^\\("
8357       "\\(package\\)\\>"
8358      "\\|"
8359       "sub\\>[^\n]+::"
8360      "\\|"
8361       "[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::" ; XSUB?
8362      "\\|"
8363       "[ \t]*BOOT:\C-?[^\n]+::"         ; BOOT section
8364    "\\)"))
8365
8366 (defvar cperl-hierarchy '(() ())
8367   "Global hierarchy of classes.")
8368
8369 (defun cperl-tags-hier-fill ()
8370   ;; Suppose we are in a tag table cooked by cperl.
8371   (goto-char 1)
8372   (let (type pack name pos line chunk ord cons1 file str info fileind)
8373     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
8374       (setq pos (match-beginning 0)
8375             pack (match-beginning 2))
8376       (beginning-of-line)
8377       (if (looking-at (concat
8378                        "\\([^\n]+\\)"
8379                        "\C-?"
8380                        "\\([^\n]+\\)"
8381                        "\C-a"
8382                        "\\([0-9]+\\)"
8383                        ","
8384                        "\\([0-9]+\\)"))
8385           (progn
8386             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
8387                   name (buffer-substring (match-beginning 2) (match-end 2))
8388                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
8389                   line (buffer-substring (match-beginning 3) (match-end 3))
8390                   ord (if pack 1 0)
8391                   file (file-of-tag)
8392                   fileind (format "%s:%s" file line)
8393                   ;; Moves to beginning of the next line:
8394                   info (cperl-etags-snarf-tag file line))
8395             ;; Move back
8396             (forward-char -1)
8397             ;; Make new member of hierarchy name ==> file ==> pos if needed
8398             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
8399                 ;; Name known
8400                 (setcdr cons1 (cons (cons fileind (vector file info))
8401                                     (cdr cons1)))
8402               ;; First occurrence of the name, start alist
8403               (setq cons1 (cons name (list (cons fileind (vector file info)))))
8404               (if pack
8405                   (setcar (cdr cperl-hierarchy)
8406                           (cons cons1 (nth 1 cperl-hierarchy)))
8407                 (setcar cperl-hierarchy
8408                         (cons cons1 (car cperl-hierarchy)))))))
8409       (end-of-line))))
8410
8411 (defun cperl-tags-hier-init (&optional update)
8412   "Show hierarchical menu of classes and methods.
8413 Finds info about classes by a scan of loaded TAGS files.
8414 Supposes that the TAGS files contain fully qualified function names.
8415 One may build such TAGS files from CPerl mode menu."
8416   (interactive)
8417   (require 'etags)
8418   (require 'imenu)
8419   (if (or update (null (nth 2 cperl-hierarchy)))
8420       (let ((remover (function (lambda (elt) ; (name (file1...) (file2..))
8421                                  (or (nthcdr 2 elt)
8422                                      ;; Only in one file
8423                                      (setcdr elt (cdr (nth 1 elt)))))))
8424             pack name cons1 to l1 l2 l3 l4 b)
8425         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
8426         (setq cperl-hierarchy (list l1 l2 l3))
8427         (if cperl-xemacs-p              ; Not checked
8428             (progn
8429               (or tags-file-name
8430                   ;; Does this work in XEmacs?
8431                   (call-interactively 'visit-tags-table))
8432               (message "Updating list of classes...")
8433               (set-buffer (get-file-buffer tags-file-name))
8434               (cperl-tags-hier-fill))
8435           (or tags-table-list
8436               (call-interactively 'visit-tags-table))
8437           (mapcar
8438            (function
8439             (lambda (tagsfile)
8440               (message "Updating list of classes... %s" tagsfile)
8441               (set-buffer (get-file-buffer tagsfile))
8442               (cperl-tags-hier-fill)))
8443            tags-table-list)
8444           (message "Updating list of classes... postprocessing..."))
8445         (mapcar remover (car cperl-hierarchy))
8446         (mapcar remover (nth 1 cperl-hierarchy))
8447         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
8448                        (cons "Methods: " (car cperl-hierarchy))))
8449         (cperl-tags-treeify to 1)
8450         (setcar (nthcdr 2 cperl-hierarchy)
8451                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
8452         (message "Updating list of classes: done, requesting display...")
8453         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
8454         ))
8455   (or (nth 2 cperl-hierarchy)
8456       (error "No items found"))
8457   (setq update
8458 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
8459         (if (if (fboundp 'display-popup-menus-p)
8460                 (let ((f 'display-popup-menus-p))
8461                   (funcall f))
8462               window-system)
8463             (x-popup-menu t (nth 2 cperl-hierarchy))
8464           (require 'tmm)
8465           (tmm-prompt (nth 2 cperl-hierarchy))))
8466   (if (and update (listp update))
8467       (progn (while (cdr update) (setq update (cdr update)))
8468              (setq update (car update)))) ; Get the last from the list
8469   (if (vectorp update)
8470       (progn
8471         (find-file (elt update 0))
8472         (cperl-etags-goto-tag-location (elt update 1))))
8473   (if (eq update -999) (cperl-tags-hier-init t)))
8474
8475 (defun cperl-tags-treeify (to level)
8476   ;; cadr of `to' is read-write.  On start it is a cons
8477   (let* ((regexp (concat "^\\(" (mapconcat
8478                                  'identity
8479                                  (make-list level "[_a-zA-Z0-9]+")
8480                                  "::")
8481                          "\\)\\(::\\)?"))
8482          (packages (cdr (nth 1 to)))
8483          (methods (cdr (nth 2 to)))
8484          l1 head tail cons1 cons2 ord writeto packs recurse
8485          root-packages root-functions ms many_ms same_name ps
8486          (move-deeper
8487           (function
8488            (lambda (elt)
8489              (cond ((and (string-match regexp (car elt))
8490                          (or (eq ord 1) (match-end 2)))
8491                     (setq head (substring (car elt) 0 (match-end 1))
8492                           tail (if (match-end 2) (substring (car elt)
8493                                                             (match-end 2)))
8494                           recurse t)
8495                     (if (setq cons1 (assoc head writeto)) nil
8496                       ;; Need to init new head
8497                       (setcdr writeto (cons (list head (list "Packages: ")
8498                                                   (list "Methods: "))
8499                                             (cdr writeto)))
8500                       (setq cons1 (nth 1 writeto)))
8501                     (setq cons2 (nth ord cons1)) ; Either packs or meths
8502                     (setcdr cons2 (cons elt (cdr cons2))))
8503                    ((eq ord 2)
8504                     (setq root-functions (cons elt root-functions)))
8505                    (t
8506                     (setq root-packages (cons elt root-packages))))))))
8507     (setcdr to l1)                      ; Init to dynamic space
8508     (setq writeto to)
8509     (setq ord 1)
8510     (mapcar move-deeper packages)
8511     (setq ord 2)
8512     (mapcar move-deeper methods)
8513     (if recurse
8514         (mapcar (function (lambda (elt)
8515                           (cperl-tags-treeify elt (1+ level))))
8516                 (cdr to)))
8517     ;;Now clean up leaders with one child only
8518     (mapcar (function (lambda (elt)
8519                         (if (not (and (listp (cdr elt))
8520                                       (eq (length elt) 2))) nil
8521                             (setcar elt (car (nth 1 elt)))
8522                             (setcdr elt (cdr (nth 1 elt))))))
8523             (cdr to))
8524     ;; Sort the roots of subtrees
8525     (if (default-value 'imenu-sort-function)
8526         (setcdr to
8527                 (sort (cdr to) (default-value 'imenu-sort-function))))
8528     ;; Now add back functions removed from display
8529     (mapcar (function (lambda (elt)
8530                         (setcdr to (cons elt (cdr to)))))
8531             (if (default-value 'imenu-sort-function)
8532                 (nreverse
8533                  (sort root-functions (default-value 'imenu-sort-function)))
8534               root-functions))
8535     ;; Now add back packages removed from display
8536     (mapcar (function (lambda (elt)
8537                         (setcdr to (cons (cons (concat "package " (car elt))
8538                                                (cdr elt))
8539                                          (cdr to)))))
8540             (if (default-value 'imenu-sort-function)
8541                 (nreverse
8542                  (sort root-packages (default-value 'imenu-sort-function)))
8543               root-packages))))
8544
8545 ;;;(x-popup-menu t
8546 ;;;   '(keymap "Name1"
8547 ;;;         ("Ret1" "aa")
8548 ;;;         ("Head1" "ab"
8549 ;;;          keymap "Name2"
8550 ;;;          ("Tail1" "x") ("Tail2" "y"))))
8551
8552 (defun cperl-list-fold (list name limit)
8553   (let (list1 list2 elt1 (num 0))
8554     (if (<= (length list) limit) list
8555       (setq list1 nil list2 nil)
8556       (while list
8557         (setq num (1+ num)
8558               elt1 (car list)
8559               list (cdr list))
8560         (if (<= num imenu-max-items)
8561             (setq list2 (cons elt1 list2))
8562           (setq list1 (cons (cons name
8563                                   (nreverse list2))
8564                             list1)
8565                 list2 (list elt1)
8566                 num 1)))
8567       (nreverse (cons (cons name
8568                             (nreverse list2))
8569                       list1)))))
8570
8571 (defun cperl-menu-to-keymap (menu &optional name)
8572   (let (list)
8573     (cons 'keymap
8574           (mapcar
8575            (function
8576             (lambda (elt)
8577               (cond ((listp (cdr elt))
8578                      (setq list (cperl-list-fold
8579                                  (cdr elt) (car elt) imenu-max-items))
8580                      (cons nil
8581                            (cons (car elt)
8582                                  (cperl-menu-to-keymap list))))
8583                     (t
8584                      (list (cdr elt) (car elt) t))))) ; t is needed in 19.34
8585            (cperl-list-fold menu "Root" imenu-max-items)))))
8586
8587 \f
8588 (defvar cperl-bad-style-regexp
8589   (mapconcat 'identity
8590              '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
8591                "[-<>=+^&|]+[^- \t\n=+<>~]") ; sign+ char
8592              "\\|")
8593   "Finds places such that insertion of a whitespace may help a lot.")
8594
8595 (defvar cperl-not-bad-style-regexp
8596   (mapconcat
8597    'identity
8598    '("[^-\t <>=+]\\(--\\|\\+\\+\\)"     ; var-- var++
8599      "[a-zA-Z0-9_][|&][a-zA-Z0-9_$]"    ; abc|def abc&def are often used.
8600      "&[(a-zA-Z0-9_$]"                  ; &subroutine &(var->field)
8601      "<\\$?\\sw+\\(\\.\\(\\sw\\|_\\)+\\)?>"     ; <IN> <stdin.h>
8602      "-[a-zA-Z][ \t]+[_$\"'`a-zA-Z]"    ; -f file, -t STDIN
8603      "-[0-9]"                           ; -5
8604      "\\+\\+"                           ; ++var
8605      "--"                               ; --var
8606      ".->"                              ; a->b
8607      "->"                               ; a SPACE ->b
8608      "\\[-"                             ; a[-1]
8609      "\\\\[&$@*\\\\]"                   ; \&func
8610      "^="                               ; =head
8611      "\\$."                             ; $|
8612      "<<[a-zA-Z_'\"`]"                  ; <<FOO, <<'FOO'
8613      "||"
8614      "&&"
8615      "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
8616      "-[a-zA-Z_0-9]+[ \t]*=>"           ; -option => value
8617      ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
8618      ;;"[*/+-|&<.]+="
8619      )
8620    "\\|")
8621   "If matches at the start of match found by `my-bad-c-style-regexp',
8622 insertion of a whitespace will not help.")
8623
8624 (defvar found-bad)
8625
8626 (defun cperl-find-bad-style ()
8627   "Find places in the buffer where insertion of a whitespace may help.
8628 Prompts user for insertion of spaces.
8629 Currently it is tuned to C and Perl syntax."
8630   (interactive)
8631   (let (found-bad (p (point)))
8632     (setq last-nonmenu-event 13)        ; To disable popup
8633     (goto-char (point-min))
8634     (map-y-or-n-p "Insert space here? "
8635                   (lambda (arg) (insert " "))
8636                   'cperl-next-bad-style
8637                   '("location" "locations" "insert a space into")
8638                   '((?\C-r (lambda (arg)
8639                              (let ((buffer-quit-function
8640                                     'exit-recursive-edit))
8641                                (message "Exit with Esc Esc")
8642                                (recursive-edit)
8643                                t))      ; Consider acted upon
8644                            "edit, exit with Esc Esc")
8645                     (?e (lambda (arg)
8646                           (let ((buffer-quit-function
8647                                  'exit-recursive-edit))
8648                             (message "Exit with Esc Esc")
8649                             (recursive-edit)
8650                             t))         ; Consider acted upon
8651                         "edit, exit with Esc Esc"))
8652                   t)
8653     (if found-bad (goto-char found-bad)
8654       (goto-char p)
8655       (message "No appropriate place found"))))
8656
8657 (defun cperl-next-bad-style ()
8658   (let (p (not-found t) (point (point)) found)
8659     (while (and not-found
8660                 (re-search-forward cperl-bad-style-regexp nil 'to-end))
8661       (setq p (point))
8662       (goto-char (match-beginning 0))
8663       (if (or
8664            (looking-at cperl-not-bad-style-regexp)
8665            ;; Check for a < -b and friends
8666            (and (eq (following-char) ?\-)
8667                 (save-excursion
8668                   (skip-chars-backward " \t\n")
8669                   (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\( ?\[ ?\{))))
8670            ;; Now check for syntax type
8671            (save-match-data
8672              (setq found (point))
8673              (beginning-of-defun)
8674              (let ((pps (parse-partial-sexp (point) found)))
8675                (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
8676           (goto-char (match-end 0))
8677         (goto-char (1- p))
8678         (setq not-found nil
8679               found-bad found)))
8680     (not not-found)))
8681
8682 \f
8683 ;;; Getting help
8684 (defvar cperl-have-help-regexp
8685   ;;(concat "\\("
8686   (mapconcat
8687    'identity
8688    '("[$@%*&][0-9a-zA-Z_:]+\\([ \t]*[[{]\\)?" ; Usual variable
8689      "[$@]\\^[a-zA-Z]"                  ; Special variable
8690      "[$@][^ \n\t]"                     ; Special variable
8691      "-[a-zA-Z]"                        ; File test
8692      "\\\\[a-zA-Z0]"                    ; Special chars
8693      "^=[a-z][a-zA-Z0-9_]*"             ; POD sections
8694      "[-!&*+,-./<=>?\\\\^|~]+"          ; Operator
8695      "[a-zA-Z_0-9:]+"                   ; symbol or number
8696      "x="
8697      "#!")
8698    ;;"\\)\\|\\("
8699    "\\|")
8700   ;;"\\)"
8701   ;;)
8702   "Matches places in the buffer we can find help for.")
8703
8704 (defvar cperl-message-on-help-error t)
8705 (defvar cperl-help-from-timer nil)
8706
8707 (defun cperl-word-at-point-hard ()
8708   ;; Does not save-excursion
8709   ;; Get to the something meaningful
8710   (or (eobp) (eolp) (forward-char 1))
8711   (re-search-backward "[-a-zA-Z0-9_:!&*+,-./<=>?\\\\^|~$%@]"
8712                       (save-excursion (beginning-of-line) (point))
8713                       'to-beg)
8714   ;;  (cond
8715   ;;   ((or (eobp) (looking-at "[][ \t\n{}();,]")) ; Not at a symbol
8716   ;;    (skip-chars-backward " \n\t\r({[]});,")
8717   ;;    (or (bobp) (backward-char 1))))
8718   ;; Try to backtrace
8719   (cond
8720    ((looking-at "[a-zA-Z0-9_:]")        ; symbol
8721     (skip-chars-backward "a-zA-Z0-9_:")
8722     (cond
8723      ((and (eq (preceding-char) ?^)     ; $^I
8724            (eq (char-after (- (point) 2)) ?\$))
8725       (forward-char -2))
8726      ((memq (preceding-char) (append "*$@%&\\" nil)) ; *glob
8727       (forward-char -1))
8728      ((and (eq (preceding-char) ?\=)
8729            (eq (current-column) 1))
8730       (forward-char -1)))               ; =head1
8731     (if (and (eq (preceding-char) ?\<)
8732              (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <FH>
8733         (forward-char -1)))
8734    ((and (looking-at "=") (eq (preceding-char) ?x)) ; x=
8735     (forward-char -1))
8736    ((and (looking-at "\\^") (eq (preceding-char) ?\$)) ; $^I
8737     (forward-char -1))
8738    ((looking-at "[-!&*+,-./<=>?\\\\^|~]")
8739     (skip-chars-backward "-!&*+,-./<=>?\\\\^|~")
8740     (cond
8741      ((and (eq (preceding-char) ?\$)
8742            (not (eq (char-after (- (point) 2)) ?\$))) ; $-
8743       (forward-char -1))
8744      ((and (eq (following-char) ?\>)
8745            (string-match "[a-zA-Z0-9_]" (char-to-string (preceding-char)))
8746            (save-excursion
8747              (forward-sexp -1)
8748              (and (eq (preceding-char) ?\<)
8749                   (looking-at "\\$?[a-zA-Z0-9_:]+>")))) ; <FH>
8750       (search-backward "<"))))
8751    ((and (eq (following-char) ?\$)
8752          (eq (preceding-char) ?\<)
8753          (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <$fh>
8754     (forward-char -1)))
8755   (if (looking-at cperl-have-help-regexp)
8756       (buffer-substring (match-beginning 0) (match-end 0))))
8757
8758 (defun cperl-get-help ()
8759   "Get one-line docs on the symbol at the point.
8760 The data for these docs is a little bit obsolete and may be in fact longer
8761 than a line.  Your contribution to update/shorten it is appreciated."
8762   (interactive)
8763   (save-match-data                      ; May be called "inside" query-replace
8764     (save-excursion
8765       (let ((word (cperl-word-at-point-hard)))
8766         (if word
8767             (if (and cperl-help-from-timer ; Bail out if not in mainland
8768                      (not (string-match "^#!\\|\\\\\\|^=" word)) ; Show help even in comments/strings.
8769                      (or (memq (get-text-property (point) 'face)
8770                                '(font-lock-comment-face font-lock-string-face))
8771                          (memq (get-text-property (point) 'syntax-type)
8772                                '(pod here-doc format))))
8773                 nil
8774               (cperl-describe-perl-symbol word))
8775           (if cperl-message-on-help-error
8776               (message "Nothing found for %s..."
8777                        (buffer-substring (point) (min (+ 5 (point)) (point-max))))))))))
8778
8779 ;;; Stolen from perl-descr.el by Johan Vromans:
8780
8781 (defvar cperl-doc-buffer " *perl-doc*"
8782   "Where the documentation can be found.")
8783
8784 (defun cperl-describe-perl-symbol (val)
8785   "Display the documentation of symbol at point, a Perl operator."
8786   (let ((enable-recursive-minibuffers t)
8787         args-file regexp)
8788     (cond
8789      ((string-match "^[&*][a-zA-Z_]" val)
8790       (setq val (concat (substring val 0 1) "NAME")))
8791      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*\\[" val)
8792       (setq val (concat "@" (substring val 1 (match-end 1)))))
8793      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*{" val)
8794       (setq val (concat "%" (substring val 1 (match-end 1)))))
8795      ((and (string= val "x") (string-match "^x=" val))
8796       (setq val "x="))
8797      ((string-match "^\\$[\C-a-\C-z]" val)
8798       (setq val (concat "$^" (char-to-string (+ ?A -1 (aref val 1))))))
8799      ((string-match "^CORE::" val)
8800       (setq val "CORE::"))
8801      ((string-match "^SUPER::" val)
8802       (setq val "SUPER::"))
8803      ((and (string= "<" val) (string-match "^<\\$?[a-zA-Z0-9_:]+>" val))
8804       (setq val "<NAME>")))
8805     (setq regexp (concat "^"
8806                          "\\([^a-zA-Z0-9_:]+[ \t]+\\)?"
8807                          (regexp-quote val)
8808                          "\\([ \t([/]\\|$\\)"))
8809
8810     ;; get the buffer with the documentation text
8811     (cperl-switch-to-doc-buffer)
8812
8813     ;; lookup in the doc
8814     (goto-char (point-min))
8815     (let ((case-fold-search nil))
8816       (list
8817        (if (re-search-forward regexp (point-max) t)
8818            (save-excursion
8819              (beginning-of-line 1)
8820              (let ((lnstart (point)))
8821                (end-of-line)
8822                (message "%s" (buffer-substring lnstart (point)))))
8823          (if cperl-message-on-help-error
8824              (message "No definition for %s" val)))))))
8825
8826 (defvar cperl-short-docs 'please-ignore-this-line
8827   ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl)
8828   "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5]
8829 ...     Range (list context); flip/flop [no flop when flip] (scalar context).
8830 ! ...   Logical negation.
8831 ... != ...      Numeric inequality.
8832 ... !~ ...      Search pattern, substitution, or translation (negated).
8833 $!      In numeric context: errno.  In a string context: error string.
8834 $\"     The separator which joins elements of arrays interpolated in strings.
8835 $#      The output format for printed numbers.  Default is %.15g or close.
8836 $$      Process number of this script.  Changes in the fork()ed child process.
8837 $%      The current page number of the currently selected output channel.
8838
8839         The following variables are always local to the current block:
8840
8841 $1      Match of the 1st set of parentheses in the last match (auto-local).
8842 $2      Match of the 2nd set of parentheses in the last match (auto-local).
8843 $3      Match of the 3rd set of parentheses in the last match (auto-local).
8844 $4      Match of the 4th set of parentheses in the last match (auto-local).
8845 $5      Match of the 5th set of parentheses in the last match (auto-local).
8846 $6      Match of the 6th set of parentheses in the last match (auto-local).
8847 $7      Match of the 7th set of parentheses in the last match (auto-local).
8848 $8      Match of the 8th set of parentheses in the last match (auto-local).
8849 $9      Match of the 9th set of parentheses in the last match (auto-local).
8850 $&      The string matched by the last pattern match (auto-local).
8851 $'      The string after what was matched by the last match (auto-local).
8852 $`      The string before what was matched by the last match (auto-local).
8853
8854 $(      The real gid of this process.
8855 $)      The effective gid of this process.
8856 $*      Deprecated: Set to 1 to do multiline matching within a string.
8857 $+      The last bracket matched by the last search pattern.
8858 $,      The output field separator for the print operator.
8859 $-      The number of lines left on the page.
8860 $.      The current input line number of the last filehandle that was read.
8861 $/      The input record separator, newline by default.
8862 $0      Name of the file containing the current perl script (read/write).
8863 $:     String may be broken after these characters to fill ^-lines in a format.
8864 $;      Subscript separator for multi-dim array emulation.  Default \"\\034\".
8865 $<      The real uid of this process.
8866 $=      The page length of the current output channel.  Default is 60 lines.
8867 $>      The effective uid of this process.
8868 $?      The status returned by the last ``, pipe close or `system'.
8869 $@      The perl error message from the last eval or do @var{EXPR} command.
8870 $ARGV   The name of the current file used with <> .
8871 $[      Deprecated: The index of the first element/char in an array/string.
8872 $\\     The output record separator for the print operator.
8873 $]      The perl version string as displayed with perl -v.
8874 $^      The name of the current top-of-page format.
8875 $^A     The current value of the write() accumulator for format() lines.
8876 $^D     The value of the perl debug (-D) flags.
8877 $^E     Information about the last system error other than that provided by $!.
8878 $^F     The highest system file descriptor, ordinarily 2.
8879 $^H     The current set of syntax checks enabled by `use strict'.
8880 $^I     The value of the in-place edit extension (perl -i option).
8881 $^L     What formats output to perform a formfeed.  Default is \f.
8882 $^M     A buffer for emergency memory allocation when running out of memory.
8883 $^O     The operating system name under which this copy of Perl was built.
8884 $^P     Internal debugging flag.
8885 $^T     The time the script was started.  Used by -A/-M/-C file tests.
8886 $^W     True if warnings are requested (perl -w flag).
8887 $^X     The name under which perl was invoked (argv[0] in C-speech).
8888 $_      The default input and pattern-searching space.
8889 $|      Auto-flush after write/print on current output channel?  Default 0.
8890 $~      The name of the current report format.
8891 ... % ...       Modulo division.
8892 ... %= ...      Modulo division assignment.
8893 %ENV    Contains the current environment.
8894 %INC    List of files that have been require-d or do-ne.
8895 %SIG    Used to set signal handlers for various signals.
8896 ... & ...       Bitwise and.
8897 ... && ...      Logical and.
8898 ... &&= ...     Logical and assignment.
8899 ... &= ...      Bitwise and assignment.
8900 ... * ...       Multiplication.
8901 ... ** ...      Exponentiation.
8902 *NAME   Glob: all objects refered by NAME.  *NAM1 = *NAM2 aliases NAM1 to NAM2.
8903 &NAME(arg0, ...)        Subroutine call.  Arguments go to @_.
8904 ... + ...       Addition.               +EXPR   Makes EXPR into scalar context.
8905 ++      Auto-increment (magical on strings).    ++EXPR  EXPR++
8906 ... += ...      Addition assignment.
8907 ,       Comma operator.
8908 ... - ...       Subtraction.
8909 --      Auto-decrement (NOT magical on strings).        --EXPR  EXPR--
8910 ... -= ...      Subtraction assignment.
8911 -A      Access time in days since script started.
8912 -B      File is a non-text (binary) file.
8913 -C      Inode change time in days since script started.
8914 -M      Age in days since script started.
8915 -O      File is owned by real uid.
8916 -R      File is readable by real uid.
8917 -S      File is a socket .
8918 -T      File is a text file.
8919 -W      File is writable by real uid.
8920 -X      File is executable by real uid.
8921 -b      File is a block special file.
8922 -c      File is a character special file.
8923 -d      File is a directory.
8924 -e      File exists .
8925 -f      File is a plain file.
8926 -g      File has setgid bit set.
8927 -k      File has sticky bit set.
8928 -l      File is a symbolic link.
8929 -o      File is owned by effective uid.
8930 -p      File is a named pipe (FIFO).
8931 -r      File is readable by effective uid.
8932 -s      File has non-zero size.
8933 -t      Tests if filehandle (STDIN by default) is opened to a tty.
8934 -u      File has setuid bit set.
8935 -w      File is writable by effective uid.
8936 -x      File is executable by effective uid.
8937 -z      File has zero size.
8938 .       Concatenate strings.
8939 ..      Range (list context); flip/flop (scalar context) operator.
8940 .=      Concatenate assignment strings
8941 ... / ...       Division.       /PATTERN/ioxsmg Pattern match
8942 ... /= ...      Division assignment.
8943 /PATTERN/ioxsmg Pattern match.
8944 ... < ...    Numeric less than. <pattern>       Glob.   See <NAME>, <> as well.
8945 <NAME>  Reads line from filehandle NAME (a bareword or dollar-bareword).
8946 <pattern>       Glob (Unless pattern is bareword/dollar-bareword - see <NAME>).
8947 <>      Reads line from union of files in @ARGV (= command line) and STDIN.
8948 ... << ...      Bitwise shift left.     <<      start of HERE-DOCUMENT.
8949 ... <= ...      Numeric less than or equal to.
8950 ... <=> ...     Numeric compare.
8951 ... = ...       Assignment.
8952 ... == ...      Numeric equality.
8953 ... =~ ...      Search pattern, substitution, or translation
8954 ... > ...       Numeric greater than.
8955 ... >= ...      Numeric greater than or equal to.
8956 ... >> ...      Bitwise shift right.
8957 ... >>= ...     Bitwise shift right assignment.
8958 ... ? ... : ... Condition=if-then-else operator.   ?PAT? One-time pattern match.
8959 ?PATTERN?       One-time pattern match.
8960 @ARGV   Command line arguments (not including the command name - see $0).
8961 @INC    List of places to look for perl scripts during do/include/use.
8962 @_    Parameter array for subroutines; result of split() unless in list context.
8963 \\  Creates reference to what follows, like \$var, or quotes non-\w in strings.
8964 \\0     Octal char, e.g. \\033.
8965 \\E     Case modification terminator.  See \\Q, \\L, and \\U.
8966 \\L     Lowercase until \\E .  See also \l, lc.
8967 \\U     Upcase until \\E .  See also \u, uc.
8968 \\Q     Quote metacharacters until \\E .  See also quotemeta.
8969 \\a     Alarm character (octal 007).
8970 \\b     Backspace character (octal 010).
8971 \\c     Control character, e.g. \\c[ .
8972 \\e     Escape character (octal 033).
8973 \\f     Formfeed character (octal 014).
8974 \\l     Lowercase the next character.  See also \\L and \\u, lcfirst.
8975 \\n     Newline character (octal 012 on most systems).
8976 \\r     Return character (octal 015 on most systems).
8977 \\t     Tab character (octal 011).
8978 \\u     Upcase the next character.  See also \\U and \\l, ucfirst.
8979 \\x     Hex character, e.g. \\x1b.
8980 ... ^ ...       Bitwise exclusive or.
8981 __END__ Ends program source.
8982 __DATA__        Ends program source.
8983 __FILE__        Current (source) filename.
8984 __LINE__        Current line in current source.
8985 __PACKAGE__     Current package.
8986 ARGV    Default multi-file input filehandle.  <ARGV> is a synonym for <>.
8987 ARGVOUT Output filehandle with -i flag.
8988 BEGIN { ... }   Immediately executed (during compilation) piece of code.
8989 END { ... }     Pseudo-subroutine executed after the script finishes.
8990 CHECK { ... }   Pseudo-subroutine executed after the script is compiled.
8991 INIT { ... }    Pseudo-subroutine executed before the script starts running.
8992 DATA    Input filehandle for what follows after __END__ or __DATA__.
8993 accept(NEWSOCKET,GENERICSOCKET)
8994 alarm(SECONDS)
8995 atan2(X,Y)
8996 bind(SOCKET,NAME)
8997 binmode(FILEHANDLE)
8998 caller[(LEVEL)]
8999 chdir(EXPR)
9000 chmod(LIST)
9001 chop[(LIST|VAR)]
9002 chown(LIST)
9003 chroot(FILENAME)
9004 close(FILEHANDLE)
9005 closedir(DIRHANDLE)
9006 ... cmp ...     String compare.
9007 connect(SOCKET,NAME)
9008 continue of { block } continue { block }.  Is executed after `next' or at end.
9009 cos(EXPR)
9010 crypt(PLAINTEXT,SALT)
9011 dbmclose(%HASH)
9012 dbmopen(%HASH,DBNAME,MODE)
9013 defined(EXPR)
9014 delete($HASH{KEY})
9015 die(LIST)
9016 do { ... }|SUBR while|until EXPR        executes at least once
9017 do(EXPR|SUBR([LIST]))   (with while|until executes at least once)
9018 dump LABEL
9019 each(%HASH)
9020 endgrent
9021 endhostent
9022 endnetent
9023 endprotoent
9024 endpwent
9025 endservent
9026 eof[([FILEHANDLE])]
9027 ... eq ...      String equality.
9028 eval(EXPR) or eval { BLOCK }
9029 exec(LIST)
9030 exit(EXPR)
9031 exp(EXPR)
9032 fcntl(FILEHANDLE,FUNCTION,SCALAR)
9033 fileno(FILEHANDLE)
9034 flock(FILEHANDLE,OPERATION)
9035 for (EXPR;EXPR;EXPR) { ... }
9036 foreach [VAR] (@ARRAY) { ... }
9037 fork
9038 ... ge ...      String greater than or equal.
9039 getc[(FILEHANDLE)]
9040 getgrent
9041 getgrgid(GID)
9042 getgrnam(NAME)
9043 gethostbyaddr(ADDR,ADDRTYPE)
9044 gethostbyname(NAME)
9045 gethostent
9046 getlogin
9047 getnetbyaddr(ADDR,ADDRTYPE)
9048 getnetbyname(NAME)
9049 getnetent
9050 getpeername(SOCKET)
9051 getpgrp(PID)
9052 getppid
9053 getpriority(WHICH,WHO)
9054 getprotobyname(NAME)
9055 getprotobynumber(NUMBER)
9056 getprotoent
9057 getpwent
9058 getpwnam(NAME)
9059 getpwuid(UID)
9060 getservbyname(NAME,PROTO)
9061 getservbyport(PORT,PROTO)
9062 getservent
9063 getsockname(SOCKET)
9064 getsockopt(SOCKET,LEVEL,OPTNAME)
9065 gmtime(EXPR)
9066 goto LABEL
9067 ... gt ...      String greater than.
9068 hex(EXPR)
9069 if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXPR if EXPR
9070 index(STR,SUBSTR[,OFFSET])
9071 int(EXPR)
9072 ioctl(FILEHANDLE,FUNCTION,SCALAR)
9073 join(EXPR,LIST)
9074 keys(%HASH)
9075 kill(LIST)
9076 last [LABEL]
9077 ... le ...      String less than or equal.
9078 length(EXPR)
9079 link(OLDFILE,NEWFILE)
9080 listen(SOCKET,QUEUESIZE)
9081 local(LIST)
9082 localtime(EXPR)
9083 log(EXPR)
9084 lstat(EXPR|FILEHANDLE|VAR)
9085 ... lt ...      String less than.
9086 m/PATTERN/iogsmx
9087 mkdir(FILENAME,MODE)
9088 msgctl(ID,CMD,ARG)
9089 msgget(KEY,FLAGS)
9090 msgrcv(ID,VAR,SIZE,TYPE.FLAGS)
9091 msgsnd(ID,MSG,FLAGS)
9092 my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, or %HASH).
9093 our VAR or our (VAR1,...) Lexically enable a global variable ($V, @A, or %H).
9094 ... ne ...      String inequality.
9095 next [LABEL]
9096 oct(EXPR)
9097 open(FILEHANDLE[,EXPR])
9098 opendir(DIRHANDLE,EXPR)
9099 ord(EXPR)       ASCII value of the first char of the string.
9100 pack(TEMPLATE,LIST)
9101 package NAME    Introduces package context.
9102 pipe(READHANDLE,WRITEHANDLE)    Create a pair of filehandles on ends of a pipe.
9103 pop(ARRAY)
9104 print [FILEHANDLE] [(LIST)]
9105 printf [FILEHANDLE] (FORMAT,LIST)
9106 push(ARRAY,LIST)
9107 q/STRING/       Synonym for 'STRING'
9108 qq/STRING/      Synonym for \"STRING\"
9109 qx/STRING/      Synonym for `STRING`
9110 rand[(EXPR)]
9111 read(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
9112 readdir(DIRHANDLE)
9113 readlink(EXPR)
9114 recv(SOCKET,SCALAR,LEN,FLAGS)
9115 redo [LABEL]
9116 rename(OLDNAME,NEWNAME)
9117 require [FILENAME | PERL_VERSION]
9118 reset[(EXPR)]
9119 return(LIST)
9120 reverse(LIST)
9121 rewinddir(DIRHANDLE)
9122 rindex(STR,SUBSTR[,OFFSET])
9123 rmdir(FILENAME)
9124 s/PATTERN/REPLACEMENT/gieoxsm
9125 scalar(EXPR)
9126 seek(FILEHANDLE,POSITION,WHENCE)
9127 seekdir(DIRHANDLE,POS)
9128 select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT)
9129 semctl(ID,SEMNUM,CMD,ARG)
9130 semget(KEY,NSEMS,SIZE,FLAGS)
9131 semop(KEY,...)
9132 send(SOCKET,MSG,FLAGS[,TO])
9133 setgrent
9134 sethostent(STAYOPEN)
9135 setnetent(STAYOPEN)
9136 setpgrp(PID,PGRP)
9137 setpriority(WHICH,WHO,PRIORITY)
9138 setprotoent(STAYOPEN)
9139 setpwent
9140 setservent(STAYOPEN)
9141 setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
9142 shift[(ARRAY)]
9143 shmctl(ID,CMD,ARG)
9144 shmget(KEY,SIZE,FLAGS)
9145 shmread(ID,VAR,POS,SIZE)
9146 shmwrite(ID,STRING,POS,SIZE)
9147 shutdown(SOCKET,HOW)
9148 sin(EXPR)
9149 sleep[(EXPR)]
9150 socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
9151 socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
9152 sort [SUBROUTINE] (LIST)
9153 splice(ARRAY,OFFSET[,LENGTH[,LIST]])
9154 split[(/PATTERN/[,EXPR[,LIMIT]])]
9155 sprintf(FORMAT,LIST)
9156 sqrt(EXPR)
9157 srand(EXPR)
9158 stat(EXPR|FILEHANDLE|VAR)
9159 study[(SCALAR)]
9160 sub [NAME [(format)]] { BODY }  sub NAME [(format)];    sub [(format)] {...}
9161 substr(EXPR,OFFSET[,LEN])
9162 symlink(OLDFILE,NEWFILE)
9163 syscall(LIST)
9164 sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
9165 system(LIST)
9166 syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
9167 tell[(FILEHANDLE)]
9168 telldir(DIRHANDLE)
9169 time
9170 times
9171 tr/SEARCHLIST/REPLACEMENTLIST/cds
9172 truncate(FILE|EXPR,LENGTH)
9173 umask[(EXPR)]
9174 undef[(EXPR)]
9175 unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR
9176 unlink(LIST)
9177 unpack(TEMPLATE,EXPR)
9178 unshift(ARRAY,LIST)
9179 until (EXPR) { ... }                                    EXPR until EXPR
9180 utime(LIST)
9181 values(%HASH)
9182 vec(EXPR,OFFSET,BITS)
9183 wait
9184 waitpid(PID,FLAGS)
9185 wantarray       Returns true if the sub/eval is called in list context.
9186 warn(LIST)
9187 while  (EXPR) { ... }                                   EXPR while EXPR
9188 write[(EXPR|FILEHANDLE)]
9189 ... x ...       Repeat string or array.
9190 x= ...  Repetition assignment.
9191 y/SEARCHLIST/REPLACEMENTLIST/
9192 ... | ...       Bitwise or.
9193 ... || ...      Logical or.
9194 ~ ...           Unary bitwise complement.
9195 #!      OS interpreter indicator.  If contains `perl', used for options, and -x.
9196 AUTOLOAD {...}  Shorthand for `sub AUTOLOAD {...}'.
9197 CORE::          Prefix to access builtin function if imported sub obscures it.
9198 SUPER::         Prefix to lookup for a method in @ISA classes.
9199 DESTROY         Shorthand for `sub DESTROY {...}'.
9200 ... EQ ...      Obsolete synonym of `eq'.
9201 ... GE ...      Obsolete synonym of `ge'.
9202 ... GT ...      Obsolete synonym of `gt'.
9203 ... LE ...      Obsolete synonym of `le'.
9204 ... LT ...      Obsolete synonym of `lt'.
9205 ... NE ...      Obsolete synonym of `ne'.
9206 abs [ EXPR ]    absolute value
9207 ... and ...             Low-precedence synonym for &&.
9208 bless REFERENCE [, PACKAGE]     Makes reference into an object of a package.
9209 chomp [LIST]    Strips $/ off LIST/$_.  Returns count.  Special if $/ eq ''!
9210 chr             Converts a number to char with the same ordinal.
9211 else            Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
9212 elsif           Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
9213 exists $HASH{KEY}       True if the key exists.
9214 format [NAME] =  Start of output format.  Ended by a single dot (.) on a line.
9215 formline PICTURE, LIST  Backdoor into \"format\" processing.
9216 glob EXPR       Synonym of <EXPR>.
9217 lc [ EXPR ]     Returns lowercased EXPR.
9218 lcfirst [ EXPR ]        Returns EXPR with lower-cased first letter.
9219 grep EXPR,LIST  or grep {BLOCK} LIST    Filters LIST via EXPR/BLOCK.
9220 map EXPR, LIST  or map {BLOCK} LIST     Applies EXPR/BLOCK to elts of LIST.
9221 no PACKAGE [SYMBOL1, ...]  Partial reverse for `use'.  Runs `unimport' method.
9222 not ...         Low-precedence synonym for ! - negation.
9223 ... or ...              Low-precedence synonym for ||.
9224 pos STRING    Set/Get end-position of the last match over this string, see \\G.
9225 quotemeta [ EXPR ]      Quote regexp metacharacters.
9226 qw/WORD1 .../           Synonym of split('', 'WORD1 ...')
9227 readline FH     Synonym of <FH>.
9228 readpipe CMD    Synonym of `CMD`.
9229 ref [ EXPR ]    Type of EXPR when dereferenced.
9230 sysopen FH, FILENAME, MODE [, PERM]     (MODE is numeric, see Fcntl.)
9231 tie VAR, PACKAGE, LIST  Hide an object behind a simple Perl variable.
9232 tied            Returns internal object for a tied data.
9233 uc [ EXPR ]     Returns upcased EXPR.
9234 ucfirst [ EXPR ]        Returns EXPR with upcased first letter.
9235 untie VAR       Unlink an object from a simple Perl variable.
9236 use PACKAGE [SYMBOL1, ...]  Compile-time `require' with consequent `import'.
9237 ... xor ...             Low-precedence synonym for exclusive or.
9238 prototype \&SUB Returns prototype of the function given a reference.
9239 =head1          Top-level heading.
9240 =head2          Second-level heading.
9241 =head3          Third-level heading (is there such?).
9242 =over [ NUMBER ]        Start list.
9243 =item [ TITLE ]         Start new item in the list.
9244 =back           End list.
9245 =cut            Switch from POD to Perl.
9246 =pod            Switch from Perl to POD.
9247 ")
9248
9249 (defun cperl-switch-to-doc-buffer ()
9250   "Go to the perl documentation buffer and insert the documentation."
9251   (interactive)
9252   (let ((buf (get-buffer-create cperl-doc-buffer)))
9253     (if (interactive-p)
9254         (switch-to-buffer-other-window buf)
9255       (set-buffer buf))
9256     (if (= (buffer-size) 0)
9257         (progn
9258           (insert (documentation-property 'cperl-short-docs
9259                                           'variable-documentation))
9260           (setq buffer-read-only t)))))
9261
9262 (defun cperl-beautify-regexp-piece (b e embed level)
9263   ;; b is before the starting delimiter, e before the ending
9264   ;; e should be a marker, may be changed, but remains "correct".
9265   ;; EMBED is nil iff we process the whole REx.
9266   ;; The REx is guaranteed to have //x
9267   ;; LEVEL shows how many levels deep to go
9268   ;; position at enter and at leave is not defined
9269   (let (s c tmp (m (make-marker)) (m1 (make-marker)) c1 spaces inline code pos)
9270     (if (not embed)
9271         (goto-char (1+ b))
9272       (goto-char b)
9273       (cond ((looking-at "(\\?\\\\#")   ;  (?#) wrongly commented when //x-ing
9274              (forward-char 2)
9275              (delete-char 1)
9276              (forward-char 1))
9277             ((looking-at "(\\?[^a-zA-Z]")
9278              (forward-char 3))
9279             ((looking-at "(\\?")        ; (?i)
9280              (forward-char 2))
9281             (t
9282              (forward-char 1))))
9283     (setq c (if embed (current-indentation) (1- (current-column)))
9284           c1 (+ c (or cperl-regexp-indent-step cperl-indent-level)))
9285     (or (looking-at "[ \t]*[\n#]")
9286         (progn
9287           (insert "\n")))
9288     (goto-char e)
9289     (beginning-of-line)
9290     (if (re-search-forward "[^ \t]" e t)
9291         (progn                         ; Something before the ending delimiter
9292           (goto-char e)
9293           (delete-horizontal-space)
9294           (insert "\n")
9295           (cperl-make-indent c)
9296           (set-marker e (point))))
9297     (goto-char b)
9298     (end-of-line 2)
9299     (while (< (point) (marker-position e))
9300       (beginning-of-line)
9301       (setq s (point)
9302             inline t)
9303       (skip-chars-forward " \t")
9304       (delete-region s (point))
9305       (cperl-make-indent c1)
9306       (while (and
9307               inline
9308               (looking-at
9309                (concat "\\([a-zA-Z0-9]+[^*+{?]\\)" ; 1 word
9310                        "\\|"            ; Embedded variable
9311                        "\\$\\([a-zA-Z0-9_]+\\([[{]\\)?\\|[^\n \t)|]\\)" ; 2 3
9312                        "\\|"            ; $ ^
9313                        "[$^]"
9314                        "\\|"            ; simple-code simple-code*?
9315                        "\\(\\\\.\\|[^][()#|*+?\n]\\)\\([*+{?]\\??\\)?" ; 4 5
9316                        "\\|"            ; Class
9317                        "\\(\\[\\)"      ; 6
9318                        "\\|"            ; Grouping
9319                        "\\((\\(\\?\\)?\\)" ; 7 8
9320                        "\\|"            ; |
9321                        "\\(|\\)")))     ; 9
9322         (goto-char (match-end 0))
9323         (setq spaces t)
9324         (cond ((match-beginning 1)      ; Alphanum word + junk
9325                (forward-char -1))
9326               ((or (match-beginning 3)  ; $ab[12]
9327                    (and (match-beginning 5) ; X* X+ X{2,3}
9328                         (eq (preceding-char) ?\{)))
9329                (forward-char -1)
9330                (forward-sexp 1))
9331               ((and                     ; [], already syntaxified
9332                 (match-beginning 6)
9333                 cperl-regexp-scan
9334                 cperl-use-syntax-table-text-property)
9335                (forward-char -1)
9336                (forward-sexp 1)
9337                (or (eq (preceding-char) ?\])
9338                    (error "[]-group not terminated"))
9339                (re-search-forward
9340                 "\\=\\([*+?]\\|{[0-9]+\\(,[0-9]*\\)?}\\)\\??" e t))
9341               ((match-beginning 6)      ; []
9342                (setq tmp (point))
9343                (if (looking-at "\\^?\\]")
9344                    (goto-char (match-end 0)))
9345                ;; XXXX POSIX classes?!
9346                (while (and (not pos)
9347                            (re-search-forward "\\[:\\|\\]" e t))
9348                  (if (eq (preceding-char) ?:)
9349                      (or (re-search-forward ":\\]" e t)
9350                          (error "[:POSIX:]-group in []-group not terminated"))
9351                    (setq pos t)))
9352                (or (eq (preceding-char) ?\])
9353                    (error "[]-group not terminated"))
9354                (re-search-forward
9355                 "\\=\\([*+?]\\|{[0-9]+\\(,[0-9]*\\)?}\\)\\??" e t))
9356               ((match-beginning 7)      ; ()
9357                (goto-char (match-beginning 0))
9358                (setq pos (current-column))
9359                (or (eq pos c1)
9360                    (progn
9361                      (delete-horizontal-space)
9362                      (insert "\n")
9363                      (cperl-make-indent c1)))
9364                (setq tmp (point))
9365                (forward-sexp 1)
9366                ;;              (or (forward-sexp 1)
9367                ;;                  (progn
9368                ;;                    (goto-char tmp)
9369                ;;                    (error "()-group not terminated")))
9370                (set-marker m (1- (point)))
9371                (set-marker m1 (point))
9372                (if (= level 1)
9373                    (if (progn           ; indent rigidly if multiline
9374                          ;; In fact does not make a lot of sense, since
9375                          ;; the starting position can be already lost due
9376                          ;; to insertion of "\n" and " "
9377                          (goto-char tmp)
9378                          (search-forward "\n" m1 t))
9379                        (indent-rigidly (point) m1 (- c1 pos)))
9380                  (setq level (1- level))
9381                  (cond
9382                   ((not (match-beginning 8))
9383                    (cperl-beautify-regexp-piece tmp m t level))
9384                   ((eq (char-after (+ 2 tmp)) ?\{) ; Code
9385                    t)
9386                   ((eq (char-after (+ 2 tmp)) ?\() ; Conditional
9387                    (goto-char (+ 2 tmp))
9388                    (forward-sexp 1)
9389                    (cperl-beautify-regexp-piece (point) m t level))
9390                   ((eq (char-after (+ 2 tmp)) ?<) ; Lookbehind
9391                    (goto-char (+ 3 tmp))
9392                    (cperl-beautify-regexp-piece (point) m t level))
9393                   (t
9394                    (cperl-beautify-regexp-piece tmp m t level))))
9395                (goto-char m1)
9396                (cond ((looking-at "[*+?]\\??")
9397                       (goto-char (match-end 0)))
9398                      ((eq (following-char) ?\{)
9399                       (forward-sexp 1)
9400                       (if (eq (following-char) ?\?)
9401                           (forward-char))))
9402                (skip-chars-forward " \t")
9403                (setq spaces nil)
9404                (if (looking-at "[#\n]")
9405                    (progn
9406                      (or (eolp) (indent-for-comment))
9407                      (beginning-of-line 2))
9408                  (delete-horizontal-space)
9409                  (insert "\n"))
9410                (end-of-line)
9411                (setq inline nil))
9412               ((match-beginning 9)      ; |
9413                (forward-char -1)
9414                (setq tmp (point))
9415                (beginning-of-line)
9416                (if (re-search-forward "[^ \t]" tmp t)
9417                    (progn
9418                      (goto-char tmp)
9419                      (delete-horizontal-space)
9420                      (insert "\n"))
9421                  ;; first at line
9422                  (delete-region (point) tmp))
9423                (cperl-make-indent c)
9424                (forward-char 1)
9425                (skip-chars-forward " \t")
9426                (setq spaces nil)
9427                (if (looking-at "[#\n]")
9428                    (beginning-of-line 2)
9429                  (delete-horizontal-space)
9430                  (insert "\n"))
9431                (end-of-line)
9432                (setq inline nil)))
9433         (or (looking-at "[ \t\n]")
9434             (not spaces)
9435             (insert " "))
9436         (skip-chars-forward " \t"))
9437       (or (looking-at "[#\n]")
9438           (error "Unknown code `%s' in a regexp"
9439                  (buffer-substring (point) (1+ (point)))))
9440       (and inline (end-of-line 2)))
9441     ;; Special-case the last line of group
9442     (if (and (>= (point) (marker-position e))
9443              (/= (current-indentation) c))
9444         (progn
9445           (beginning-of-line)
9446           (cperl-make-indent c)))))
9447
9448 (defun cperl-make-regexp-x ()
9449   ;; Returns position of the start
9450   ;; XXX this is called too often!  Need to cache the result!
9451   (save-excursion
9452     (or cperl-use-syntax-table-text-property
9453         (error "I need to have a regexp marked!"))
9454     ;; Find the start
9455     (if (looking-at "\\s|")
9456         nil                             ; good already
9457       (if (looking-at "\\([smy]\\|qr\\)\\s|")
9458           (forward-char 1)
9459         (re-search-backward "\\s|")))   ; Assume it is scanned already.
9460     ;;(forward-char 1)
9461     (let ((b (point)) (e (make-marker)) have-x delim (c (current-column))
9462           (sub-p (eq (preceding-char) ?s)) s)
9463       (forward-sexp 1)
9464       (set-marker e (1- (point)))
9465       (setq delim (preceding-char))
9466       (if (and sub-p (eq delim (char-after (- (point) 2))))
9467           (error "Possible s/blah// - do not know how to deal with"))
9468       (if sub-p (forward-sexp 1))
9469       (if (looking-at "\\sw*x")
9470           (setq have-x t)
9471         (insert "x"))
9472       ;; Protect fragile " ", "#"
9473       (if have-x nil
9474         (goto-char (1+ b))
9475         (while (re-search-forward "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*[ \t\n#]" e t) ; Need to include (?#) too?
9476           (forward-char -1)
9477           (insert "\\")
9478           (forward-char 1)))
9479       b)))
9480
9481 (defun cperl-beautify-regexp (&optional deep)
9482   "Do it.  (Experimental, may change semantics, recheck the result.)
9483 We suppose that the regexp is scanned already."
9484   (interactive "P")
9485   (setq deep (if deep (prefix-numeric-value deep) -1))
9486   (save-excursion
9487     (goto-char (cperl-make-regexp-x))
9488     (let ((b (point)) (e (make-marker)))
9489       (forward-sexp 1)
9490       (set-marker e (1- (point)))
9491       (cperl-beautify-regexp-piece b e nil deep))))
9492
9493 (defun cperl-regext-to-level-start ()
9494   "Goto start of an enclosing group in regexp.
9495 We suppose that the regexp is scanned already."
9496   (interactive)
9497   (let ((limit (cperl-make-regexp-x)) done)
9498     (while (not done)
9499       (or (eq (following-char) ?\()
9500           (search-backward "(" (1+ limit) t)
9501           (error "Cannot find `(' which starts a group"))
9502       (setq done
9503             (save-excursion
9504               (skip-chars-backward "\\")
9505               (looking-at "\\(\\\\\\\\\\)*(")))
9506       (or done (forward-char -1)))))
9507
9508 (defun cperl-contract-level ()
9509   "Find an enclosing group in regexp and contract it.
9510 \(Experimental, may change semantics, recheck the result.)
9511 We suppose that the regexp is scanned already."
9512   (interactive)
9513   ;; (save-excursion            ; Can't, breaks `cperl-contract-levels'
9514   (cperl-regext-to-level-start)
9515   (let ((b (point)) (e (make-marker)) c)
9516     (forward-sexp 1)
9517     (set-marker e (1- (point)))
9518     (goto-char b)
9519     (while (re-search-forward "\\(#\\)\\|\n" e 'to-end)
9520       (cond
9521        ((match-beginning 1)             ; #-comment
9522         (or c (setq c (current-indentation)))
9523         (beginning-of-line 2)           ; Skip
9524         (cperl-make-indent c))
9525        (t
9526         (delete-char -1)
9527         (just-one-space))))))
9528
9529 (defun cperl-contract-levels ()
9530   "Find an enclosing group in regexp and contract all the kids.
9531 \(Experimental, may change semantics, recheck the result.)
9532 We suppose that the regexp is scanned already."
9533   (interactive)
9534   (save-excursion
9535     (condition-case nil
9536         (cperl-regext-to-level-start)
9537       (error                            ; We are outside outermost group
9538        (goto-char (cperl-make-regexp-x))))
9539     (let ((b (point)) (e (make-marker)) s c)
9540       (forward-sexp 1)
9541       (set-marker e (1- (point)))
9542       (goto-char (1+ b))
9543       (while (re-search-forward "\\(\\\\\\\\\\)\\|(" e t)
9544         (cond
9545          ((match-beginning 1)           ; Skip
9546           nil)
9547          (t                             ; Group
9548           (cperl-contract-level)))))))
9549
9550 (defun cperl-beautify-level (&optional deep)
9551   "Find an enclosing group in regexp and beautify it.
9552 \(Experimental, may change semantics, recheck the result.)
9553 We suppose that the regexp is scanned already."
9554   (interactive "P")
9555   (setq deep (if deep (prefix-numeric-value deep) -1))
9556   (save-excursion
9557     (cperl-regext-to-level-start)
9558     (let ((b (point)) (e (make-marker)))
9559       (forward-sexp 1)
9560       (set-marker e (1- (point)))
9561       (cperl-beautify-regexp-piece b e nil deep))))
9562
9563 (defun cperl-invert-if-unless-modifiers ()
9564   "Change `B if A;' into `if (A) {B}' etc if possible.
9565 \(Unfinished.)"
9566   (interactive)                         ; 
9567   (let (A B pre-B post-B pre-if post-if pre-A post-A if-string
9568           (w-rex "\\<\\(if\\|unless\\|while\\|until\\|for\\|foreach\\)\\>"))
9569     (and (= (char-syntax (preceding-char)) ?w)
9570          (forward-sexp -1))
9571     (setq pre-if (point))
9572     (cperl-backward-to-start-of-expr)
9573     (setq pre-B (point))
9574     (forward-sexp 1)            ; otherwise forward-to-end-of-expr is NOP
9575     (cperl-forward-to-end-of-expr)
9576     (setq post-A (point))
9577     (goto-char pre-if)
9578     (or (looking-at w-rex)
9579         ;; Find the position
9580         (progn (goto-char post-A)
9581                (while (and
9582                        (not (looking-at w-rex))
9583                        (> (point) pre-B))
9584                  (forward-sexp -1))
9585                (setq pre-if (point))))
9586     (or (looking-at w-rex)
9587         (error "Can't find `if', `unless', `while', `until', `for' or `foreach'"))
9588     ;; 1 B 2 ... 3 B-com ... 4 if 5 ... if-com 6 ... 7 A 8
9589     (setq if-string (buffer-substring (match-beginning 0) (match-end 0)))
9590     ;; First, simple part: find code boundaries
9591     (forward-sexp 1)
9592     (setq post-if (point))
9593     (forward-sexp -2)
9594     (forward-sexp 1)
9595     (setq post-B (point))
9596     (cperl-backward-to-start-of-expr)
9597     (setq pre-B (point))
9598     (setq B (buffer-substring pre-B post-B))
9599     (goto-char pre-if)
9600     (forward-sexp 2)
9601     (forward-sexp -1)
9602     (setq pre-A (point))
9603     (cperl-forward-to-end-of-expr)
9604     (setq post-A (point))
9605     (setq A (buffer-substring pre-A post-A))
9606     ;; Now modify (from end, to not break the stuff)
9607     (skip-chars-forward " \t;")
9608     (delete-region pre-A (point))       ; we move to pre-A
9609     (insert "\n" B ";\n}")
9610     (and (looking-at "[ \t]*#") (cperl-indent-for-comment))
9611     (delete-region pre-if post-if)
9612     (delete-region pre-B post-B)
9613     (goto-char pre-B)
9614     (insert if-string " (" A ") {")
9615     (setq post-B (point))
9616     (if (looking-at "[ \t]+$")
9617         (delete-horizontal-space)
9618       (if (looking-at "[ \t]*#")
9619           (cperl-indent-for-comment)
9620         (just-one-space)))
9621     (forward-line 1)
9622     (if (looking-at "[ \t]*$")
9623         (progn                          ; delete line
9624           (delete-horizontal-space)
9625           (delete-region (point) (1+ (point)))))
9626     (cperl-indent-line)
9627     (goto-char (1- post-B))
9628     (forward-sexp 1)
9629     (cperl-indent-line)
9630     (goto-char pre-B)))
9631
9632 (defun cperl-invert-if-unless ()
9633   "Change `if (A) {B}' into `B if A;' etc (or visa versa) if possible.
9634 If the cursor is not on the leading keyword of the BLOCK flavor of
9635 construct, will assume it is the STATEMENT flavor, so will try to find
9636 the appropriate statement modifier."
9637   (interactive)
9638   (and (= (char-syntax (preceding-char)) ?w)
9639        (forward-sexp -1))
9640   (if (looking-at "\\<\\(if\\|unless\\|while\\|until\\|for\\|foreach\\)\\>")
9641       (let ((pre-if (point))
9642             pre-A post-A pre-B post-B A B state p end-B-code is-block B-comment
9643             (if-string (buffer-substring (match-beginning 0) (match-end 0))))
9644         (forward-sexp 2)
9645         (setq post-A (point))
9646         (forward-sexp -1)
9647         (setq pre-A (point))
9648         (setq is-block (and (eq (following-char) ?\( )
9649                             (save-excursion
9650                               (condition-case nil
9651                                   (progn
9652                                     (forward-sexp 2)
9653                                     (forward-sexp -1)
9654                                     (eq (following-char) ?\{ ))
9655                                 (error nil)))))
9656         (if is-block
9657             (progn
9658               (goto-char post-A)
9659               (forward-sexp 1)
9660               (setq post-B (point))
9661               (forward-sexp -1)
9662               (setq pre-B (point))
9663               (if (and (eq (following-char) ?\{ )
9664                        (progn
9665                          (cperl-backward-to-noncomment post-A)
9666                          (eq (preceding-char) ?\) )))
9667                   (if (condition-case nil
9668                           (progn
9669                             (goto-char post-B)
9670                             (forward-sexp 1)
9671                             (forward-sexp -1)
9672                             (looking-at "\\<els\\(e\\|if\\)\\>"))
9673                         (error nil))
9674                       (error
9675                        "`%s' (EXPR) {BLOCK} with `else'/`elsif'" if-string)
9676                     (goto-char (1- post-B))
9677                     (cperl-backward-to-noncomment pre-B)
9678                     (if (eq (preceding-char) ?\;)
9679                         (forward-char -1))
9680                     (setq end-B-code (point))
9681                     (goto-char pre-B)
9682                     (while (re-search-forward "\\<\\(for\\|foreach\\|if\\|unless\\|while\\|until\\)\\>\\|;" end-B-code t)
9683                       (setq p (match-beginning 0)
9684                             A (buffer-substring p (match-end 0))
9685                             state (parse-partial-sexp pre-B p))
9686                       (or (nth 3 state)
9687                           (nth 4 state)
9688                           (nth 5 state)
9689                           (error "`%s' inside `%s' BLOCK" A if-string))
9690                       (goto-char (match-end 0)))
9691                     ;; Finally got it
9692                     (goto-char (1+ pre-B))
9693                     (skip-chars-forward " \t\n")
9694                     (setq B (buffer-substring (point) end-B-code))
9695                     (goto-char end-B-code)
9696                     (or (looking-at ";?[ \t\n]*}")
9697                         (progn
9698                           (skip-chars-forward "; \t\n")
9699                           (setq B-comment
9700                                 (buffer-substring (point) (1- post-B)))))
9701                     (and (equal B "")
9702                          (setq B "1"))
9703                     (goto-char (1- post-A))
9704                     (cperl-backward-to-noncomment pre-A)
9705                     (or (looking-at "[ \t\n]*)")
9706                         (goto-char (1- post-A)))
9707                     (setq p (point))
9708                     (goto-char (1+ pre-A))
9709                     (skip-chars-forward " \t\n")
9710                     (setq A (buffer-substring (point) p))
9711                     (delete-region pre-B post-B)
9712                     (delete-region pre-A post-A)
9713                     (goto-char pre-if)
9714                     (insert B " ")
9715                     (and B-comment (insert B-comment " "))
9716                     (just-one-space)
9717                     (forward-word 1)
9718                     (setq pre-A (point))
9719                     (insert " " A ";")
9720                     (delete-horizontal-space)
9721                     (setq post-B (point))
9722                     (if (looking-at "#")
9723                         (indent-for-comment))
9724                     (goto-char post-B)
9725                     (forward-char -1)
9726                     (delete-horizontal-space)
9727                     (goto-char pre-A)
9728                     (just-one-space)
9729                     (goto-char pre-if)
9730                     (setq pre-A (set-marker (make-marker) pre-A))
9731                     (while (<= (point) (marker-position pre-A))
9732                       (cperl-indent-line)
9733                       (forward-line 1))
9734                     (goto-char (marker-position pre-A))
9735                     (if B-comment
9736                         (progn
9737                           (forward-line -1)
9738                           (indent-for-comment)
9739                           (goto-char (marker-position pre-A)))))
9740                 (error "`%s' (EXPR) not with an {BLOCK}" if-string)))
9741           ;; (error "`%s' not with an (EXPR)" if-string)
9742           (forward-sexp -1)
9743           (cperl-invert-if-unless-modifiers)))
9744     ;;(error "Not at `if', `unless', `while', `until', `for' or `foreach'")
9745     (cperl-invert-if-unless-modifiers)))
9746
9747 ;;; By Anthony Foiani <afoiani@uswest.com>
9748 ;;; Getting help on modules in C-h f ?
9749 ;;; This is a modified version of `man'.
9750 ;;; Need to teach it how to lookup functions
9751 ;;;###autoload
9752 (defun cperl-perldoc (word)
9753   "Run `perldoc' on WORD."
9754   (interactive
9755    (list (let* ((default-entry (cperl-word-at-point))
9756                 (input (read-string
9757                         (format "perldoc entry%s: "
9758                                 (if (string= default-entry "")
9759                                     ""
9760                                   (format " (default %s)" default-entry))))))
9761            (if (string= input "")
9762                (if (string= default-entry "")
9763                    (error "No perldoc args given")
9764                  default-entry)
9765              input))))
9766   (require 'man)
9767   (let* ((case-fold-search nil)
9768          (is-func (and
9769                    (string-match "^[a-z]+$" word)
9770                    (string-match (concat "^" word "\\>")
9771                                  (documentation-property
9772                                   'cperl-short-docs
9773                                   'variable-documentation))))
9774          (manual-program (if is-func "perldoc -f" "perldoc")))
9775     (cond
9776      (cperl-xemacs-p
9777       (let ((Manual-program "perldoc")
9778             (Manual-switches (if is-func (list "-f"))))
9779         (manual-entry word)))
9780      (t
9781       (Man-getpage-in-background word)))))
9782
9783 ;;;###autoload
9784 (defun cperl-perldoc-at-point ()
9785   "Run a `perldoc' on the word around point."
9786   (interactive)
9787   (cperl-perldoc (cperl-word-at-point)))
9788
9789 (defcustom pod2man-program "pod2man"
9790   "*File name for `pod2man'."
9791   :type 'file
9792   :group 'cperl)
9793
9794 ;;; By Nick Roberts <Nick.Roberts@src.bae.co.uk> (with changes)
9795 (defun cperl-pod-to-manpage ()
9796   "Create a virtual manpage in Emacs from the Perl Online Documentation."
9797   (interactive)
9798   (require 'man)
9799   (let* ((pod2man-args (concat buffer-file-name " | nroff -man "))
9800          (bufname (concat "Man " buffer-file-name))
9801          (buffer (generate-new-buffer bufname)))
9802     (save-excursion
9803       (set-buffer buffer)
9804       (let ((process-environment (copy-sequence process-environment)))
9805         ;; Prevent any attempt to use display terminal fanciness.
9806         (setenv "TERM" "dumb")
9807         (set-process-sentinel
9808          (start-process pod2man-program buffer "sh" "-c"
9809                         (format (cperl-pod2man-build-command) pod2man-args))
9810          'Man-bgproc-sentinel)))))
9811
9812 ;;; Updated version by him too
9813 (defun cperl-build-manpage ()
9814   "Create a virtual manpage in Emacs from the POD in the file."
9815   (interactive)
9816   (require 'man)
9817   (cond
9818    (cperl-xemacs-p
9819     (let ((Manual-program "perldoc"))
9820       (manual-entry buffer-file-name)))
9821    (t
9822     (let* ((manual-program "perldoc"))
9823       (Man-getpage-in-background buffer-file-name)))))
9824
9825 (defun cperl-pod2man-build-command ()
9826   "Builds the entire background manpage and cleaning command."
9827   (let ((command (concat pod2man-program " %s 2>/dev/null"))
9828         (flist (and (boundp 'Man-filter-list) Man-filter-list)))
9829     (while (and flist (car flist))
9830       (let ((pcom (car (car flist)))
9831             (pargs (cdr (car flist))))
9832         (setq command
9833               (concat command " | " pcom " "
9834                       (mapconcat '(lambda (phrase)
9835                                     (if (not (stringp phrase))
9836                                         (error "Malformed Man-filter-list"))
9837                                     phrase)
9838                                  pargs " ")))
9839         (setq flist (cdr flist))))
9840     command))
9841
9842
9843 (defun cperl-next-interpolated-REx-1 ()
9844   "Move point to next REx which has interpolated parts without //o.
9845 Skips RExes consisting of one interpolated variable.
9846
9847 Note that skipped RExen are not performance hits."
9848   (interactive "")
9849   (cperl-next-interpolated-REx 1))
9850
9851 (defun cperl-next-interpolated-REx-0 ()
9852   "Move point to next REx which has interpolated parts without //o."
9853   (interactive "")
9854   (cperl-next-interpolated-REx 0))
9855
9856 (defun cperl-next-interpolated-REx (&optional skip beg limit)
9857   "Move point to next REx which has interpolated parts.
9858 SKIP is a list of possible types to skip, BEG and LIMIT are the starting
9859 point and the limit of search (default to point and end of buffer).
9860
9861 SKIP may be a number, then it behaves as list of numbers up to SKIP; this
9862 semantic may be used as a numeric argument.
9863
9864 Types are 0 for / $rex /o (interpolated once), 1 for /$rex/ (if $rex is
9865 a result of qr//, this is not a performance hit), t for the rest."
9866   (interactive "P")
9867   (if (numberp skip) (setq skip (list 0 skip)))
9868   (or beg (setq beg (point)))
9869   (or limit (setq limit (point-max)))   ; needed for n-s-p-c
9870   (let (pp)
9871     (and (eq (get-text-property beg 'syntax-type) 'string)
9872          (setq beg (next-single-property-change beg 'syntax-type nil limit)))
9873     (cperl-map-pods-heres
9874      (function (lambda (s e p)
9875                  (if (memq (get-text-property s 'REx-interpolated) skip)
9876                      t
9877                    (setq pp s)
9878                    nil)))       ; nil stops
9879      'REx-interpolated beg limit)
9880     (if pp (goto-char pp)
9881       (message "No more interpolated REx"))))
9882
9883 ;;; Initial version contributed by Trey Belew
9884 (defun cperl-here-doc-spell (&optional beg end)
9885   "Spell-check HERE-documents in the Perl buffer.
9886 If a region is highlighted, restricts to the region."
9887   (interactive "")
9888   (cperl-pod-spell t beg end))
9889
9890 (defun cperl-pod-spell (&optional do-heres beg end)
9891   "Spell-check POD documentation.
9892 If invoked with prefix argument, will do HERE-DOCs instead.
9893 If a region is highlighted, restricts to the region."
9894   (interactive "P")
9895   (save-excursion
9896     (let (beg end)
9897       (if (cperl-mark-active)
9898           (setq beg (min (mark) (point))
9899                 end (max (mark) (point)))
9900         (setq beg (point-min)
9901               end (point-max)))
9902       (cperl-map-pods-heres (function
9903                              (lambda (s e p)
9904                                (if do-heres
9905                                    (setq e (save-excursion
9906                                              (goto-char e)
9907                                              (forward-line -1)
9908                                              (point))))
9909                                (ispell-region s e)
9910                                t))
9911                             (if do-heres 'here-doc-group 'in-pod)
9912                             beg end))))
9913
9914 (defun cperl-map-pods-heres (func &optional prop s end)
9915   "Executes a function over regions of pods or here-documents.
9916 PROP is the text-property to search for; default to `in-pod'.  Stop when
9917 function returns nil."
9918   (let (pos posend has-prop (cont t))
9919     (or prop (setq prop 'in-pod))
9920     (or s (setq s (point-min)))
9921     (or end (setq end (point-max)))
9922     (cperl-update-syntaxification end end)
9923     (save-excursion
9924       (goto-char (setq pos s))
9925       (while (and cont (< pos end))
9926         (setq has-prop (get-text-property pos prop))
9927         (setq posend (next-single-property-change pos prop nil end))
9928         (and has-prop
9929              (setq cont (funcall func pos posend prop)))
9930         (setq pos posend)))))
9931
9932 ;;; Based on code by Masatake YAMATO:
9933 (defun cperl-get-here-doc-region (&optional pos pod)
9934   "Return HERE document region around the point.
9935 Return nil if the point is not in a HERE document region.  If POD is non-nil,
9936 will return a POD section if point is in a POD section."
9937   (or pos (setq pos (point)))
9938   (cperl-update-syntaxification pos pos)
9939   (if (or (eq 'here-doc  (get-text-property pos 'syntax-type))
9940           (and pod
9941                (eq 'pod (get-text-property pos 'syntax-type))))
9942       (let ((b (cperl-beginning-of-property pos 'syntax-type))
9943             (e (next-single-property-change pos 'syntax-type)))
9944         (cons b (or e (point-max))))))
9945
9946 (defun cperl-narrow-to-here-doc (&optional pos)
9947   "Narrows editing region to the HERE-DOC at POS.
9948 POS defaults to the point."
9949   (interactive "d")
9950   (or pos (setq pos (point)))
9951   (let ((p (cperl-get-here-doc-region pos)))
9952     (or p (error "Not inside a HERE document"))
9953     (narrow-to-region (car p) (cdr p))
9954     (message
9955      "When you are finished with narrow editing, type C-x n w")))
9956
9957 (defun cperl-select-this-pod-or-here-doc (&optional pos)
9958   "Select the HERE-DOC (or POD section) at POS.
9959 POS defaults to the point."
9960   (interactive "d")
9961   (let ((p (cperl-get-here-doc-region pos t)))
9962     (if p
9963         (progn
9964           (goto-char (car p))
9965           (push-mark (cdr p) nil t))    ; Message, activate in transient-mode
9966       (message "I do not think POS is in POD or a HERE-doc..."))))
9967
9968 (defun cperl-facemenu-add-face-function (face end)
9969   "A callback to process user-initiated font-change requests.
9970 Translates `bold', `italic', and `bold-italic' requests to insertion of
9971 corresponding POD directives, and `underline' to C<> POD directive.
9972
9973 Such requests are usually bound to M-o LETTER."
9974   (or (get-text-property (point) 'in-pod)
9975       (error "Faces can only be set within POD"))
9976   (setq facemenu-end-add-face (if (eq face 'bold-italic) ">>" ">"))
9977   (cdr (or (assq face '((bold . "B<")
9978                         (italic . "I<")
9979                         (bold-italic . "B<I<")
9980                         (underline . "C<")))
9981            (error "Face %s not configured for cperl-mode"
9982                   face))))
9983 \f
9984 (defun cperl-time-fontification (&optional l step lim)
9985   "Times how long it takes to do incremental fontification in a region.
9986 L is the line to start at, STEP is the number of lines to skip when
9987 doing next incremental fontification, LIM is the maximal number of
9988 incremental fontification to perform.  Messages are accumulated in
9989 *Messages* buffer.
9990
9991 May be used for pinpointing which construct slows down buffer fontification:
9992 start with default arguments, then refine the slowdown regions."
9993   (interactive "nLine to start at: \nnStep to do incremental fontification: ")
9994   (or l (setq l 1))
9995   (or step (setq step 500))
9996   (or lim (setq lim 40))
9997   (let* ((timems (function (lambda ()
9998                              (let ((tt (current-time)))
9999                                (+ (* 1000 (nth 1 tt)) (/ (nth 2 tt) 1000))))))
10000          (tt (funcall timems)) (c 0) delta tot)
10001     (goto-line l)
10002     (cperl-mode)
10003     (setq tot (- (- tt (setq tt (funcall timems)))))
10004     (message "cperl-mode at %s: %s" l tot)
10005     (while (and (< c lim) (not (eobp)))
10006       (forward-line step)
10007       (setq l (+ l step))
10008       (setq c (1+ c))
10009       (cperl-update-syntaxification (point) (point))
10010       (setq delta (- (- tt (setq tt (funcall timems)))) tot (+ tot delta))
10011       (message "to %s:%6s,%7s" l delta tot))
10012     tot))
10013
10014 (defun cperl-emulate-lazy-lock (&optional window-size)
10015   "Emulate `lazy-lock' without `condition-case', so `debug-on-error' works.
10016 Start fontifying the buffer from the start (or end) using the given
10017 WINDOW-SIZE (units is lines).  Negative WINDOW-SIZE starts at end, and
10018 goes backwards; default is -50.  This function is not CPerl-specific; it
10019 may be used to debug problems with delayed incremental fontification."
10020   (interactive
10021    "nSize of window for incremental fontification, negative goes backwards: ")
10022   (or window-size (setq window-size -50))
10023   (let ((pos (if (> window-size 0)
10024                  (point-min)
10025                (point-max)))
10026         p)
10027     (goto-char pos)
10028     (normal-mode)
10029     ;; Why needed???  With older font-locks???
10030     (set (make-local-variable 'font-lock-cache-position) (make-marker))
10031     (while (if (> window-size 0)
10032                (< pos (point-max))
10033              (> pos (point-min)))
10034       (setq p (progn
10035                 (forward-line window-size)
10036                 (point)))
10037       (font-lock-fontify-region (min p pos) (max p pos))
10038       (setq pos p))))
10039
10040 \f
10041 (defun cperl-lazy-install ())           ; Avoid a warning
10042 (defun cperl-lazy-unstall ())           ; Avoid a warning
10043
10044 (if (fboundp 'run-with-idle-timer)
10045     (progn
10046       (defvar cperl-help-shown nil
10047         "Non-nil means that the help was already shown now.")
10048
10049       (defvar cperl-lazy-installed nil
10050         "Non-nil means that the lazy-help handlers are installed now.")
10051
10052       (defun cperl-lazy-install ()
10053         "Switches on Auto-Help on Perl constructs (put in the message area).
10054 Delay of auto-help controlled by `cperl-lazy-help-time'."
10055         (interactive)
10056         (make-variable-buffer-local 'cperl-help-shown)
10057         (if (and (cperl-val 'cperl-lazy-help-time)
10058                  (not cperl-lazy-installed))
10059             (progn
10060               (add-hook 'post-command-hook 'cperl-lazy-hook)
10061               (run-with-idle-timer
10062                (cperl-val 'cperl-lazy-help-time 1000000 5)
10063                t
10064                'cperl-get-help-defer)
10065               (setq cperl-lazy-installed t))))
10066
10067       (defun cperl-lazy-unstall ()
10068         "Switches off Auto-Help on Perl constructs (put in the message area).
10069 Delay of auto-help controlled by `cperl-lazy-help-time'."
10070         (interactive)
10071         (remove-hook 'post-command-hook 'cperl-lazy-hook)
10072         (cancel-function-timers 'cperl-get-help-defer)
10073         (setq cperl-lazy-installed nil))
10074
10075       (defun cperl-lazy-hook ()
10076         (setq cperl-help-shown nil))
10077
10078       (defun cperl-get-help-defer ()
10079         (if (not (memq major-mode '(perl-mode cperl-mode))) nil
10080           (let ((cperl-message-on-help-error nil) (cperl-help-from-timer t))
10081             (cperl-get-help)
10082             (setq cperl-help-shown t))))
10083       (cperl-lazy-install)))
10084
10085
10086 ;;; Plug for wrong font-lock:
10087
10088 (defun cperl-font-lock-unfontify-region-function (beg end)
10089   (let* ((modified (buffer-modified-p)) (buffer-undo-list t)
10090          (inhibit-read-only t) (inhibit-point-motion-hooks t)
10091          before-change-functions after-change-functions
10092          deactivate-mark buffer-file-name buffer-file-truename)
10093     (remove-text-properties beg end '(face nil))
10094     (if (and (not modified) (buffer-modified-p))
10095       (set-buffer-modified-p nil))))
10096
10097 (defun cperl-font-lock-fontify-region-function (beg end loudly)
10098   "Extends the region to safe positions, then calls the default function.
10099 Newer `font-lock's can do it themselves.
10100 We unwind only as far as needed for fontification.  Syntaxification may
10101 do extra unwind via `cperl-unwind-to-safe'."
10102   (save-excursion
10103     (goto-char beg)
10104     (while (and beg
10105                 (progn
10106                   (beginning-of-line)
10107                   (eq (get-text-property (setq beg (point)) 'syntax-type)
10108                       'multiline)))
10109       (if (setq beg (cperl-beginning-of-property beg 'syntax-type))
10110           (goto-char beg)))
10111     (setq beg (point))
10112     (goto-char end)
10113     (while (and end
10114                 (progn
10115                   (or (bolp) (condition-case nil
10116                                  (forward-line 1)
10117                                (error nil)))
10118                   (eq (get-text-property (setq end (point)) 'syntax-type)
10119                       'multiline)))
10120       (setq end (next-single-property-change end 'syntax-type nil (point-max)))
10121       (goto-char end))
10122     (setq end (point)))
10123   (font-lock-default-fontify-region beg end loudly))
10124
10125 (defvar cperl-d-l nil)
10126 (defun cperl-fontify-syntaxically (end)
10127   ;; Some vars for debugging only
10128   ;; (message "Syntaxifying...")
10129   (let ((dbg (point)) (iend end) (idone cperl-syntax-done-to)
10130         (istate (car cperl-syntax-state))
10131         start from-start edebug-backtrace-buffer)
10132     (if (eq cperl-syntaxify-by-font-lock 'backtrace)
10133         (progn
10134           (require 'edebug)
10135           (let ((f 'edebug-backtrace))
10136             (funcall f))))      ; Avoid compile-time warning
10137     (or cperl-syntax-done-to
10138         (setq cperl-syntax-done-to (point-min)
10139               from-start t))
10140     (setq start (if (and cperl-hook-after-change
10141                          (not from-start))
10142                     cperl-syntax-done-to ; Fontify without change; ignore start
10143                   ;; Need to forget what is after `start'
10144                   (min cperl-syntax-done-to (point))))
10145     (goto-char start)
10146     (beginning-of-line)
10147     (setq start (point))
10148     (and cperl-syntaxify-unwind
10149          (setq end (cperl-unwind-to-safe t end)
10150                start (point)))
10151     (and (> end start)
10152          (setq cperl-syntax-done-to start) ; In case what follows fails
10153          (cperl-find-pods-heres start end t nil t))
10154     (if (memq cperl-syntaxify-by-font-lock '(backtrace message))
10155         (message "Syxify req=%s..%s actual=%s..%s done-to: %s=>%s statepos: %s=>%s"
10156                  dbg iend start end idone cperl-syntax-done-to
10157                  istate (car cperl-syntax-state))) ; For debugging
10158     nil))                               ; Do not iterate
10159
10160 (defun cperl-fontify-update (end)
10161   (let ((pos (point-min)) prop posend)
10162     (setq end (point-max))
10163     (while (< pos end)
10164       (setq prop (get-text-property pos 'cperl-postpone)
10165             posend (next-single-property-change pos 'cperl-postpone nil end))
10166       (and prop (put-text-property pos posend (car prop) (cdr prop)))
10167       (setq pos posend)))
10168   nil)                                  ; Do not iterate
10169
10170 (defun cperl-fontify-update-bad (end)
10171   ;; Since fontification happens with different region than syntaxification,
10172   ;; do to the end of buffer, not to END;;; likewise, start earlier if needed
10173   (let* ((pos (point)) (prop (get-text-property pos 'cperl-postpone)) posend)
10174     (if prop
10175         (setq pos (or (cperl-beginning-of-property
10176                        (cperl-1+ pos) 'cperl-postpone)
10177                       (point-min))))
10178     (while (< pos end)
10179       (setq posend (next-single-property-change pos 'cperl-postpone))
10180       (and prop (put-text-property pos posend (car prop) (cdr prop)))
10181       (setq pos posend)
10182       (setq prop (get-text-property pos 'cperl-postpone))))
10183   nil)                                  ; Do not iterate
10184
10185 ;; Called when any modification is made to buffer text.
10186 (defun cperl-after-change-function (beg end old-len)
10187   ;; We should have been informed about changes by `font-lock'.  Since it
10188   ;; does not inform as which calls are defered, do it ourselves
10189   (if cperl-syntax-done-to
10190       (setq cperl-syntax-done-to (min cperl-syntax-done-to beg))))
10191
10192 (defun cperl-update-syntaxification (from to)
10193   (if (and cperl-use-syntax-table-text-property
10194            cperl-syntaxify-by-font-lock
10195            (or (null cperl-syntax-done-to)
10196                (< cperl-syntax-done-to to)))
10197       (progn
10198         (save-excursion
10199           (goto-char from)
10200           (cperl-fontify-syntaxically to)))))
10201
10202 (defvar cperl-version
10203   (let ((v  "$Revision: 5.19 $"))
10204     (string-match ":\\s *\\([0-9.]+\\)" v)
10205     (substring v (match-beginning 1) (match-end 1)))
10206   "Version of IZ-supported CPerl package this file is based on.")
10207
10208 (provide 'cperl-mode)
10209
10210 ;;; cperl-mode.el ends here