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