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