This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
PerlIO_importFILE() should increase the reference count on the fd
[perl5.git] / emacs / cperl-mode.el
1 ;;; cperl-mode.el --- Perl code editing commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2003
4 ;;     Free Software Foundation, Inc.
5
6 ;; Author: Ilya Zakharevich and Bob Olson
7 ;; Maintainer: Ilya Zakharevich <cperl@ilyaz.org>
8 ;; Keywords: languages, Perl
9
10 ;; This file is part of GNU Emacs.
11
12 ;;; This code started from the following message of long time ago
13 ;;; (IZ), but Bob does not maintain this mode any more:
14
15 ;;; From: olson@mcs.anl.gov (Bob Olson)
16 ;;; Newsgroups: comp.lang.perl
17 ;;; Subject: cperl-mode: Another perl mode for Gnuemacs
18 ;;; Date: 14 Aug 91 15:20:01 GMT
19
20 ;; Copyright (C) Ilya Zakharevich and Bob Olson
21
22 ;; This file may be distributed
23 ;; either under the same terms as GNU Emacs, or under the same terms
24 ;; as Perl. You should have received a copy of Perl Artistic license
25 ;; along with the Perl distribution.
26
27 ;; GNU Emacs is free software; you can redistribute it and/or modify
28 ;; it under the terms of the GNU General Public License as published by
29 ;; the Free Software Foundation; either version 2, or (at your option)
30 ;; any later version.
31
32 ;; GNU Emacs is distributed in the hope that it will be useful,
33 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
34 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35 ;; GNU General Public License for more details.
36
37 ;; You should have received a copy of the GNU General Public License
38 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
39 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
40 ;; Boston, MA 02110-1301, USA.
41
42 ;;; Corrections made by Ilya Zakharevich cperl@ilyaz.org
43 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
44
45 ;;; Commentary:
46
47 ;; $Id: cperl-mode.el,v 5.0 2003/02/17 01:33:20 vera Exp vera $
48
49 ;;; If your Emacs does not default to `cperl-mode' on Perl files:
50 ;;; To use this mode put the following into
51 ;;; your .emacs file:
52
53 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
54
55 ;; You can either fine-tune the bells and whistles of this mode or
56 ;; bulk enable them by putting
57
58 ;; (setq cperl-hairy t)
59
60 ;; in your .emacs file.  (Emacs rulers do not consider it politically
61 ;; correct to make whistles enabled by default.)
62
63 ;; DO NOT FORGET to read micro-docs (available from `Perl' menu)   <<<<<<
64 ;; or as help on variables `cperl-tips', `cperl-problems',         <<<<<<
65 ;; `cperl-non-problems', `cperl-praise', `cperl-speed'.            <<<<<<
66
67 ;; Additional useful commands to put into your .emacs file (before
68 ;; RMS Emacs 20.3):
69
70 ;; (setq auto-mode-alist
71 ;;      (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
72 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
73 ;;                                      '(("miniperl" . perl-mode))))
74
75 ;; The mode information (on C-h m) provides some customization help.
76 ;; If you use font-lock feature of this mode, it is advisable to use
77 ;; either lazy-lock-mode or fast-lock-mode.  I prefer lazy-lock.
78
79 ;; Faces used now: three faces for first-class and second-class keywords
80 ;; and control flow words, one for each: comments, string, labels,
81 ;; functions definitions and packages, arrays, hashes, and variable
82 ;; definitions.  If you do not see all these faces, your font-lock does
83 ;; not define them, so you need to define them manually.
84 ;; Maybe you have an obsolete font-lock from 19.28 or earlier.  Upgrade.
85
86 ;; If you have a grayscale monitor, and do not have the variable
87 ;; font-lock-display-type bound to 'grayscale, insert
88
89 ;; (setq font-lock-display-type 'grayscale)
90
91 ;; into your .emacs file (this is relevant before RMS Emacs 20).
92
93 ;; This mode supports font-lock, imenu and mode-compile.  In the
94 ;; hairy version font-lock is on, but you should activate imenu
95 ;; yourself (note that mode-compile is not standard yet).  Well, you
96 ;; can use imenu from keyboard anyway (M-x imenu), but it is better
97 ;; to bind it like that:
98
99 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
100
101 ;;; Font lock bugs as of v4.32:
102
103 ;; The following kinds of Perl code erroneously start strings:
104 ;; \$`  \$'  \$"
105 ;; $opt::s  $opt_s  $opt{s}  (s => ...)  /\s+.../
106 ;; likewise with m, tr, y, q, qX instead of s
107
108 ;;; In fact the version of font-lock that this version supports can be
109 ;;; much newer than the version you actually have. This means that a
110 ;;; lot of faces can be set up, but are not visible on your screen
111 ;;; since the coloring rules for this faces are not defined.
112
113 ;;; Updates: ========================================
114
115 ;;; Made less hairy by default: parentheses not electric,
116 ;;; linefeed not magic. Bug with abbrev-mode corrected.
117
118 ;;;; After 1.4:
119 ;;;  Better indentation:
120 ;;;  subs inside braces should work now,
121 ;;;  Toplevel braces obey customization.
122 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
123 ;;;  moves cursor to a correct place.
124 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-(
125 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
126 ;;;  Minor documentation fixes.
127 ;;;  Imenu understands packages as prefixes (including nested).
128 ;;;  Hairy options can be switched off one-by-one by setting to null.
129 ;;;  Names of functions and variables changed to conform to `cperl-' style.
130
131 ;;;; After 1.5:
132 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
133 ;;;  `cperl-indent-region' done (slow :-()).
134 ;;;  `cperl-fill-paragraph' done.
135 ;;;  Better package support for `imenu'.
136 ;;;  Progress indicator for indentation (with `imenu' loaded).
137 ;;;  `Cperl-set' was busted, now setting the individual hairy option
138 ;;;     should be better.
139
140 ;;;; After 1.6:
141 ;;; `cperl-set-style' done.
142 ;;; `cperl-check-syntax' done.
143 ;;; Menu done.
144 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
145 ;;; Bugs with `cperl-auto-newline' corrected.
146 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation
147 ;;; like $hash{.
148
149 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
150 ;;; - use `next-command-event', if `next-command-events' does not exist
151 ;;; - use `find-face' as def. of `is-face'
152 ;;; - corrected def. of `x-color-defined-p'
153 ;;; - added const defs for font-lock-comment-face,
154 ;;;   font-lock-keyword-face and font-lock-function-name-face
155 ;;; - added def. of font-lock-variable-name-face
156 ;;; - added (require 'easymenu) inside an `eval-when-compile'
157 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
158 ;;;   `define-key's
159 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
160 ;;; Todo (at least):
161 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
162 ;;;   for portable code?
163 ;;; - should `cperl-mode' do a
164 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
165 ;;;   or should this be left to the user's `cperl-mode-hook'?
166
167 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
168 ;;; Some bugs under XEmacs introduced by the correction corrected.
169
170 ;;; Some more can remain since there are two many different variants.
171 ;;; Please feedback!
172
173 ;;; We do not support fontification of arrays and hashes under
174 ;;; obsolete font-lock any more. Upgrade.
175
176 ;;;; after 1.8 Minor bug with parentheses.
177 ;;;; after 1.9 Improvements from Joe Marzot.
178 ;;;; after 1.10
179 ;;;  Does not need easymenu to compile under XEmacs.
180 ;;;  `vc-insert-headers' should work better.
181 ;;;  Should work with 19.29 and 19.12.
182 ;;;  Small improvements to fontification.
183 ;;;  Expansion of keywords does not depend on C-? being backspace.
184
185 ;;; after 1.10+
186 ;;; 19.29 and 19.12 supported.
187 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
188 ;;; Support for font-lock-extra.el.
189
190 ;;;; After 1.11:
191 ;;; Tools submenu.
192 ;;; Support for perl5-info.
193 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
194 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
195 ;;; Fontifies `require a if b;', __DATA__.
196 ;;; Arglist for auto-fill-mode was incorrect.
197
198 ;;;; After 1.12:
199 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions
200 ;;; vertically.
201 ;;; `cperl-do-auto-fill' updated for 19.29 style.
202 ;;; `cperl-info-on-command' now has a default.
203 ;;; Workaround for broken C-h on XEmacs.
204 ;;; VC strings escaped.
205 ;;; C-h f now may prompt for function name instead of going on,
206 ;;; controlled by `cperl-info-on-command-no-prompt'.
207
208 ;;;; After 1.13:
209 ;;; Msb buffer list includes perl files
210 ;;; Indent-for-comment uses indent-to
211 ;;; Can write tag files using etags.
212
213 ;;;; After 1.14:
214 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
215 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
216 ;;; Bug with auto-filling comments started with "##" corrected.
217
218 ;;;; Very slow now: on DB::DB 0.91, 486/66:
219
220 ;;;Function Name                             Call Count  Elapsed Time  Average Time
221 ;;;========================================  ==========  ============  ============
222 ;;;cperl-block-p                             469         3.7799999999  0.0080597014
223 ;;;cperl-get-state                           505         163.39000000  0.3235445544
224 ;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
225 ;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
226 ;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
227 ;;;cperl-indent-line                         505         172.88000000  0.3423366336
228 ;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
229 ;;;cperl-indent-exp                          1           177.97000000  177.97000000
230 ;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
231 ;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
232 ;;;cperl-indent-region                       1           177.94000000  177.94000000
233
234 ;;;; After 1.15:
235 ;;; Takes into account white space after opening parentheses during indent.
236 ;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
237 ;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
238 ;;; for indentation so far.
239 ;;; Fontification updated to 19.30 style.
240 ;;; The change 19.29->30 did not add all the required functionality,
241 ;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
242 ;;;       ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
243
244 ;;;; After 1.16:
245 ;;;       else # comment
246 ;;;    recognized as a start of a block.
247 ;;;  Two different font-lock-levels provided.
248 ;;;  `cperl-pod-head-face' introduced. Used for highlighting.
249 ;;;  `imenu' marks pods, +Packages moved to the head.
250
251 ;;;; After 1.17:
252 ;;;  Scan for pods highlights here-docs too.
253 ;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
254 ;;;  Only one here-doc-tag per line is supported, and one in comment
255 ;;;  or a string may break fontification.
256 ;;;  POD headers were supposed to fill one line only.
257
258 ;;;; After 1.18:
259 ;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme
260 ;;;    may  break under XEmacs.
261 ;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
262 ;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
263 ;;;    compatibility with older lazy-lock.el) (older one overfontifies
264 ;;;    something nevertheless :-().
265 ;;;  Will not indent something inside pod and here-documents.
266 ;;;  Fontifies the package name after import/no/bootstrap.
267 ;;;  Added new entry to menu with meta-info about the mode.
268
269 ;;;; After 1.19:
270 ;;;  Prefontification works much better with 19.29. Should be checked
271 ;;;   with 19.30 as well.
272 ;;;  Some misprints in docs corrected.
273 ;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
274 ;;;  Now the pod search is much stricter, so it can help you to find
275 ;;;    pod sections which are broken because of whitespace before =blah
276 ;;;    - just observe the fontification.
277
278 ;;;; After 1.20
279 ;;;  Anonymous subs are indented with respect to the level of
280 ;;;    indentation of `sub' now.
281 ;;;  {} is recognized as hash after `bless' and `return'.
282 ;;;  Anonymous subs are split by `cperl-linefeed' as well.
283 ;;;  Electric parens embrace a region if present.
284 ;;;  To make `cperl-auto-newline' useful,
285 ;;;    `cperl-auto-newline-after-colon' is introduced.
286 ;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
287 ;;;  `cperl-electric-parens-string'.
288 ;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
289 ;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
290 ;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
291 ;;;  Beginning-of-defun-regexp was not anchored.
292
293 ;;;; After 1.21
294 ;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
295 ;;;    after ")".
296 ;;;  {} is recognized as expression after `tr' and friends.
297
298 ;;;; After 1.22
299 ;;;  Entry Hierarchy added to imenu. Very primitive so far.
300 ;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
301 ;;;  Writes its own TAGS files.
302 ;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
303 ;;;  19.31: Problems with scan for PODs corrected.
304 ;;;  First POD header correctly fontified.
305 ;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
306 ;;;  Apparently it makes a lot of hierarchy code obsolete...
307
308 ;;;; After 1.23
309 ;;;  Tags filler now scans *.xs as well.
310 ;;;  The info from *.xs scan is used by the hierarchy viewer.
311 ;;;  Hierarchy viewer documented.
312 ;;;  Bug in 19.31 imenu documented.
313
314 ;;;; After 1.24
315 ;;;  New location for info-files mentioned,
316 ;;;  Electric-; should work better.
317 ;;;  Minor bugs with POD marking.
318
319 ;;;; After 1.25 (probably not...)
320 ;;;  `cperl-info-page' introduced.
321 ;;;  To make `uncomment-region' working, `comment-region' would
322 ;;;  not insert extra space.
323 ;;;  Here documents delimiters better recognized
324 ;;;  (empty one, and non-alphanums in quotes handled). May be wrong with 1<<14?
325 ;;;  `cperl-db' added, used in menu.
326 ;;;  imenu scan removes text-properties, for better debugging
327 ;;;    - but the bug is in 19.31 imenu.
328 ;;;  formats highlighted by font-lock and prescan, embedded comments
329 ;;;  are not treated.
330 ;;;  POD/friends scan merged in one pass.
331 ;;;  Syntax class is not used for analyzing the code, only char-syntax
332 ;;;  may be checked against _ or'ed with w.
333 ;;;  Syntax class of `:' changed to be _.
334 ;;;  `cperl-find-bad-style' added.
335
336 ;;;; After 1.25
337 ;;;  When search for here-documents, we ignore commented << in simplest cases.
338 ;;;  `cperl-get-help' added, available on C-h v and from menu.
339 ;;;  Auto-help added. Default with `cperl-hairy', switchable on/off
340 ;;;   with startup variable `cperl-lazy-help-time' and from
341 ;;;   menu. Requires `run-with-idle-timer'.
342 ;;;  Highlighting of @abc{@efg} was wrong - interchanged two regexps.
343
344 ;;;; After 1.27
345 ;;;  Indentation: At toplevel after a label - fixed.
346 ;;;  1.27 was put to archives in binary mode ===> DOSish :-(
347
348 ;;;; After 1.28
349 ;;;  Thanks to Martin Buchholz <mrb@Eng.Sun.COM>: misprints in
350 ;;;  comments and docstrings corrected, XEmacs support cleaned up.
351 ;;;  The closing parenths would enclose the region into matching
352 ;;;  parens under the same conditions as the opening ones.
353 ;;;  Minor updates to `cperl-short-docs'.
354 ;;;  Will not consider <<= as start of here-doc.
355
356 ;;;; After 1.29
357 ;;;  Added an extra advice to look into Micro-docs. ;-).
358 ;;;  Enclosing of region when you press a closing parenth is regulated by
359 ;;;  `cperl-electric-parens-string'.
360 ;;;  Minor updates to `cperl-short-docs'.
361 ;;;  `initialize-new-tags-table' called only if present (Does this help
362 ;;;     with generation of tags under XEmacs?).
363 ;;;  When creating/updating tag files, new info is written at the old place,
364 ;;;     or at the end (is this a wanted behaviour? I need this in perl build directory).
365
366 ;;;; After 1.30
367 ;;;  All the keywords from keywords.pl included (maybe with dummy explanation).
368 ;;;  No auto-help inside strings, comment, here-docs, formats, and pods.
369 ;;;  Shrinkwrapping of info, regulated by `cperl-max-help-size',
370 ;;;  `cperl-shrink-wrap-info-frame'.
371 ;;;  Info on variables as well.
372 ;;;  Recognision of HERE-DOCS improved yet more.
373 ;;;  Autonewline works on `}' without warnings.
374 ;;;  Autohelp works again on $_[0].
375
376 ;;;; After 1.31
377 ;;;  perl-descr.el found its author - hi, Johan!
378 ;;;  Some support for correct indent after here-docs and friends (may
379 ;;;  be superseeded by eminent change to Emacs internals).
380 ;;;  Should work with older Emaxen as well ( `-style stuff removed).
381
382 ;;;; After 1.32
383
384 ;;;  Started to add support for `syntax-table' property (should work
385 ;;;  with patched Emaxen), controlled by
386 ;;;  `cperl-use-syntax-table-text-property'. Currently recognized:
387 ;;;    All quote-like operators: m, s, y, tr, qq, qw, qx, q,
388 ;;;    // in most frequent context:
389 ;;;          after block or
390 ;;;                    ~ { ( = | & + - * ! , ;
391 ;;;          or
392 ;;;                    while if unless until and or not xor split grep map
393 ;;;    Here-documents, formats, PODs,
394 ;;;    ${...}
395 ;;;    'abc$'
396 ;;;    sub a ($); sub a ($) {}
397 ;;;  (provide 'cperl-mode) was missing!
398 ;;;  `cperl-after-expr-p' is now much smarter after `}'.
399 ;;;  `cperl-praise' added to mini-docs.
400 ;;;  Utilities try to support subs-with-prototypes.
401
402 ;;;; After 1.32.1
403 ;;;  `cperl-after-expr-p' is now much smarter after "() {}" and "word {}":
404 ;;;     if word is "else, map, grep".
405 ;;;  Updated for new values of syntax-table constants.
406 ;;;  Uses `help-char' (at last!) (disabled, does not work?!)
407 ;;;  A couple of regexps where missing _ in character classes.
408 ;;;  -s could be considered as start of regexp, 1../blah/ was not,
409 ;;;  as was not /blah/ at start of file.
410
411 ;;;; After 1.32.2
412 ;;;  "\C-hv" was wrongly "\C-hf"
413 ;;;  C-hv was not working on `[index()]' because of [] in skip-chars-*.
414 ;;;  `__PACKAGE__' supported.
415 ;;;  Thanks for Greg Badros: `cperl-lazy-unstall' is more complete,
416 ;;;  `cperl-get-help' is made compatible with `query-replace'.
417
418 ;;;; As of Apr 15, development version of 19.34 supports
419 ;;;; `syntax-table' text properties. Try setting
420 ;;;; `cperl-use-syntax-table-text-property'.
421
422 ;;;; After 1.32.3
423 ;;;  We scan for s{}[] as well (in simplest situations).
424 ;;;  We scan for $blah'foo as well.
425 ;;;  The default is to use `syntax-table' text property if Emacs is good enough.
426 ;;;  `cperl-lineup' is put on C-M-| (=C-M-S-\\).
427 ;;;  Start of `cperl-beautify-regexp'.
428
429 ;;;; After 1.32.4
430 ;;; `cperl-tags-hier-init' did not work in text-mode.
431 ;;; `cperl-noscan-files-regexp' had a misprint.
432 ;;; Generation of Class Hierarchy was broken due to a bug in `x-popup-menu'
433 ;;;  in 19.34.
434
435 ;;;; After 1.33:
436 ;;; my,local highlight vars after {} too.
437 ;;; TAGS could not be created before imenu was loaded.
438 ;;; `cperl-indent-left-aligned-comments' created.
439 ;;; Logic of `cperl-indent-exp' changed a little bit, should be more
440 ;;;  robust w.r.t. multiline strings.
441 ;;; Recognition of blah'foo takes into account strings.
442 ;;; Added '.al' to the list of Perl extensions.
443 ;;; Class hierarchy is "mostly" sorted (need to rethink algorthm
444 ;;;  of pruning one-root-branch subtrees to get yet better sorting.)
445 ;;; Regeneration of TAGS was busted.
446 ;;; Can use `syntax-table' property when generating TAGS
447 ;;;  (governed by  `cperl-use-syntax-table-text-property-for-tags').
448
449 ;;;; After 1.35:
450 ;;; Can process several =pod/=cut sections one after another.
451 ;;; Knows of `extproc' when under `emx', indents with `__END__' and `__DATA__'.
452 ;;; `cperl-under-as-char' implemented (XEmacs people like broken behaviour).
453 ;;; Beautifier for regexps fixed.
454 ;;; `cperl-beautify-level', `cperl-contract-level' coded
455 ;;;
456 ;;;; Emacs's 20.2 problems:
457 ;;; `imenu.el' has bugs, `imenu-add-to-menubar' does not work.
458 ;;; Couple of others problems with 20.2 were reported, my ability to check/fix
459 ;;; them is very reduced now.
460
461 ;;;; After 1.36:
462 ;;;  'C-M-|' in XEmacs fixed
463
464 ;;;; After 1.37:
465 ;;;  &&s was not recognized as start of regular expression;
466 ;;;  Will "preprocess" the contents of //e part of s///e too;
467 ;;;  What to do with s# blah # foo #e ?
468 ;;;  Should handle s;blah;foo;; better.
469 ;;;  Now the only known problems with regular expression recognition:
470 ;;;;;;;  s<foo>/bar/    - different delimiters (end ignored)
471 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into one chunk)
472 ;;;;;;;  s/foo//        - empty subst (made into one chunk + '/')
473 ;;;;;;;  s/foo/(bar)/   - start-group at start of subst (internal group will not match backwards)
474
475 ;;;; After 1.38:
476 ;;;  We highlight closing / of s/blah/foo/e;
477 ;;;  This handles s# blah # foo #e too;
478 ;;;  s//blah/, s///, s/blah// works again, and s#blah## too, the algorithm
479 ;;;   is much simpler now;
480 ;;;  Next round of changes: s\\\ works, s<blah>/foo/,
481 ;;;   comments between the first and the second part allowed
482 ;;;  Another problem discovered:
483 ;;;;;;;  s[foo] <blah>e - e part delimited by different <> (will not match)
484 ;;;  `cperl-find-pods-heres' somehow maybe called when string-face is undefined
485 ;;;   - put a stupid workaround for 20.1
486
487 ;;;; After 1.39:
488 ;;;  Could indent here-docs for comments;
489 ;;;  These problems fixed:
490 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into two chunk)
491 ;;;;;;;  s[foo] <blah>e - "e" part delimited by "different" <> (will match)
492 ;;;  Matching brackets honor prefices, may expand abbreviations;
493 ;;;  When expanding abbrevs, will remove last char only after
494 ;;;    self-inserted whitespace;
495 ;;;  More convenient "Refress hard constructs" in menu;
496 ;;;  `cperl-add-tags-recurse', `cperl-add-tags-recurse-noxs'
497 ;;;    added (for -batch mode);
498 ;;;  Better handling of errors when scanning for Perl constructs;
499 ;;;;;;;  Possible "problem" with class hierarchy in Perl distribution
500 ;;;;;;;    directory: ./ext duplicates ./lib;
501 ;;;  Write relative paths for generated TAGS;
502
503 ;;;; After 1.40:
504 ;;;  s  /// may be separated by "\n\f" too;
505 ;;;  `s  #blah' recognized as a comment;
506 ;;;  Would highlight s/abc//s wrong;
507 ;;;  Debugging code in `cperl-electric-keywords' was leaking a message;
508
509 ;;;; After 1.41:
510 ;;;  RMS changes for 20.3 merged
511
512 ;;;; 2.0.1.0: RMS mode (has 3 misprints)
513
514 ;;;; After 2.0:
515 ;;;  RMS whitespace changes for 20.3 merged
516
517 ;;;; After 2.1:
518 ;;;  History updated
519
520 ;;;; After 2.2:
521 ;;;  Merge `c-style-alist' since `c-mode' is no more.  (Somebody who
522 ;;;    uses the styles should check that they work OK!)
523 ;;;  All the variable warnings go away, some undef functions too.
524
525 ;;;; After 2.3:
526 ;;;  Added `cperl-perldoc' (thanks to Anthony Foiani <afoiani@uswest.com>)
527 ;;;  Added `cperl-pod-to-manpage' (thanks to Nick Roberts <Nick.Roberts@src.bae.co.uk>)
528 ;;;  All the function warnings go away.
529
530 ;;;; After 2.4:
531 ;;;  `Perl doc', `Regexp' submenus created (latter to allow short displays).
532 ;;;  `cperl-clobber-lisp-bindings' added.
533 ;;;  $a->y() is not y///.
534 ;;;  `cperl-after-block-p' was missing a `save-excursion' => wrong results.
535 ;;;  `cperl-val' was defined too late.
536 ;;;  `cperl-init-faces' was failing.
537 ;;;  Init faces when loading `ps-print'.
538
539 ;;;; After 2.4:
540 ;;;  `cperl-toggle-autohelp' implemented.
541 ;;;  `while SPACE LESS' was buggy.
542 ;;;  `-text' in `[-text => 1]' was not highlighted.
543 ;;;  `cperl-after-block-p' was FALSE after `sub f {}'.
544
545 ;;;; After 2.5:
546 ;;;  `foreachmy', `formy' expanded too.
547 ;;;  Expand `=pod-directive'.
548 ;;;  `cperl-linefeed' behaves reasonable in POD-directive lines.
549 ;;;  `cperl-electric-keyword' prints a message, governed by
550 ;;;    `cperl-message-electric-keyword'.
551
552 ;;;; After 2.6:
553 ;;;  Typing `}' was not checking for being block or not.
554 ;;;  Beautifying levels in RE: Did not know about lookbehind;
555 ;;;                            finding *which* level was not intuitive;
556 ;;;                            `cperl-beautify-levels' added.
557 ;;;  Allow here-docs contain `=head1' and friends (at least for keywords).
558
559 ;;;; After 2.7:
560 ;;;  Fix for broken `font-lock-unfontify-region-function'.  Should
561 ;;;    preserve `syntax-table' properties even with `lazy-lock'.
562
563 ;;;; After 2.8:
564 ;;;  Some more compile time warnings crept in.
565 ;;;  `cperl-indent-region-fix-else' implemented.
566 ;;;  `cperl-fix-line-spacing' implemented.
567 ;;;  `cperl-invert-if-unless' implemented (C-c C-t and in Menu).
568 ;;;  Upgraded hints to mention 20.2's goods/bads.
569 ;;;  Started to use `cperl-extra-newline-before-brace-multiline',
570 ;;;    `cperl-break-one-line-blocks-when-indent',
571 ;;;    `cperl-fix-hanging-brace-when-indent', `cperl-merge-trailing-else'.
572
573 ;;;; After 2.9:
574 ;;;  Workaround for another `font-lock's `syntax-table' text-property bug.
575 ;;;  `zerop' could be applied to nil.
576 ;;;  At last, may work with `font-lock' without setting `cperl-font-lock'.
577 ;;;    (We expect that starting from 19.33, `font-lock' supports keywords
578 ;;;     being a function - what is a correct version?)
579 ;;;  Rename `cperl-indent-region-fix-else' to
580 ;;;    `cperl-indent-region-fix-constructs'.
581 ;;;  `cperl-fix-line-spacing' could be triggered inside strings, would not
582 ;;;     know what to do with BLOCKs of map/printf/etc.
583 ;;;  `cperl-merge-trailing-else' and `cperl-fix-line-spacing' handle
584 ;;;     `continue' too.
585 ;;;  Indentation after {BLOCK} knows about map/printf/etc.
586 ;;;  Finally: treat after-comma lines as continuation lines.
587
588 ;;;; After 2.10:
589 ;;;  `continue' made electric.
590 ;;;  Electric `do' inserts `do/while'.
591 ;;;  Some extra compile-time warnings crept in.
592 ;;;  `font-lock' of 19.33 could not handle font-lock-keywords being a function
593 ;;;      returning a symbol.
594
595 ;;;; After 2.11:
596 ;;;  Changes to make syntaxification to be autoredone via `font-lock'.
597 ;;;    Switched on by `cperl-syntaxify-by-font-lock', off by default so far.
598
599 ;;;; After 2.12:
600 ;;;  Remove some commented out chunks.
601 ;;;  Styles are slightly updated (a lot of work is needed, especially
602 ;;;    with new `cperl-fix-line-spacing').
603
604 ;;;; After 2.13:
605 ;;;  Old value of style is memorized when choosing a new style, may be
606 ;;;    restored from the same menu.
607 ;;;  Mode-documentation added to micro-docs.
608 ;;;  `cperl-praise' updated.
609 ;;;  `cperl-toggle-construct-fix' added on C-c C-w and menu.
610 ;;;  `auto-fill-mode' added on C-c C-f and menu.
611 ;;;  `PerlStyle' style added.
612 ;;;  Message for termination of scan corrected.
613
614 ;;;; After 2.14:
615
616 ;;;  Did not work with -q
617
618 ;;;; After 2.15:
619
620 ;;;  `cperl-speed' hints added.
621 ;;;  Minor style fixes.
622
623 ;;;; After 2.15:
624 ;;;  Make backspace electric after expansion of `else/continue' too.
625
626 ;;;; After 2.16:
627 ;;;  Starting to merge changes to RMS emacs version.
628
629 ;;;; After 2.17:
630 ;;;  Merged custom stuff and darn `font-lock-constant-face'.
631
632 ;;;; After 2.18:
633 ;;;  Bumped the version to 3.1
634
635 ;;;; After 3.1:
636 ;;;  Fixed customization to honor cperl-hairy.
637 ;;;  Created customization groups.  Sent to RMS to include into 2.3.
638
639 ;;;; After 3.2:
640 ;;;  Interaction of `font-lock-hot-pass' and `cperl-syntaxify-by-font-lock'.
641 ;;;  (`cperl-after-block-and-statement-beg'):
642 ;;;  (`cperl-after-block-p'):
643 ;;;  (`cperl-after-expr-p'):    It is BLOCK if we reach lim when backup sexp.
644 ;;;  (`cperl-indent-region'):   Make a marker for END - text added/removed.
645 ;;;  (`cperl-style-alist', `cperl-styles-entries')
646 ;;;             Include `cperl-merge-trailing-else' where the value is clear.
647
648 ;;;; After 3.3:
649 ;;;  (`cperl-tips'):
650 ;;;  (`cperl-problems'):        Improvements to docs.
651
652 ;;;; After 3.4:
653 ;;;  (`cperl-mode'):            Make lazy syntaxification possible.
654 ;;;  (`cperl-find-pods-heres'): Safe a position in buffer where it is safe to
655 ;;;                             restart syntaxification.
656 ;;;  (`cperl-syntaxify-by-font-lock'): Set to t, should be safe now.
657
658 ;;;; After 3.5:
659 ;;;  (`cperl-syntaxify-by-font-lock'): Better default, customizes to
660 ;;;                             `message' too.
661
662 ;;;; After 3.6:
663 ;;;  (`cperl-find-pods-heres'): changed so that -d ?foo? is a RE.
664 ;;;  (`cperl-array-face'): changed name from `font-lock-emphasized-face'.
665 ;;;  (`cperl-hash-face'): changed name from  `font-lock-other-emphasized-face'.
666 ;;;  Use `defface' to define these two extra faces.
667
668 ;;;; After 3.7:
669 ;;;  Can use linear algorithm for indentation if Emacs supports it:
670 ;;;  indenting DB::DB (800+ lines) improved from 69 sec to 11 sec
671 ;;;  (73 vs 15 with imenu).
672 ;;;  (`cperl-emacs-can-parse'): New state.
673 ;;;  (`cperl-indent-line'):     Corrected to use global state.
674 ;;;  (`cperl-calculate-indent'):        Likewise.
675 ;;;  (`cperl-fix-line-spacing'):        Likewise (not used yet).
676
677 ;;;; After 3.8:
678 ;;;  (`cperl-choose-color'):    Converted to a function (to be compilable in text-mode).
679
680 ;;;; After 3.9:
681 ;;;  (`cperl-dark-background '):        Disable without window-system.
682
683 ;;;; After 3.10:
684 ;;;  Do `defface' only if window-system.
685
686 ;;;; After 3.11:
687 ;;;  (`cperl-fix-line-spacing'):        sped up to bail out early.
688 ;;;  (`cperl-indent-region'):   Disable hooks during the call (how to call them later?).
689
690 ;;;  Now indents 820-line-long function in 6.5 sec (including syntaxification) the first time
691 ;;;  (when buffer has few properties), 7.1 sec the second time.
692
693 ;;;Function Name                              Call Count  Elapsed Time  Average Time
694 ;;;=========================================  ==========  ============  ============
695 ;;;cperl-indent-exp                           1           10.039999999  10.039999999
696 ;;;cperl-indent-region                        1           10.0          10.0
697 ;;;cperl-indent-line                          821         6.2100000000  0.0075639464
698 ;;;cperl-calculate-indent                     821         5.0199999999  0.0061144945
699 ;;;cperl-backward-to-noncomment               2856        2.0500000000  0.0007177871
700 ;;;cperl-fontify-syntaxically                 2           1.78          0.8900000000
701 ;;;cperl-find-pods-heres                      2           1.78          0.8900000000
702 ;;;cperl-update-syntaxification               1           1.78          1.78
703 ;;;cperl-fix-line-spacing                     769         1.4800000000  0.0019245773
704 ;;;cperl-after-block-and-statement-beg        163         1.4100000000  0.0086503067
705 ;;;cperl-block-p                              775         1.1800000000  0.0015225806
706 ;;;cperl-to-comment-or-eol                    3652        1.1200000000  0.0003066812
707 ;;;cperl-after-block-p                        165         1.0500000000  0.0063636363
708 ;;;cperl-commentify                           141         0.22          0.0015602836
709 ;;;cperl-get-state                            813         0.16          0.0001968019
710 ;;;cperl-backward-to-start-of-continued-exp   26          0.12          0.0046153846
711 ;;;cperl-delay-update-hook                    2107        0.0899999999  4.271...e-05
712 ;;;cperl-protect-defun-start                  141         0.0700000000  0.0004964539
713 ;;;cperl-after-label                          407         0.0599999999  0.0001474201
714 ;;;cperl-forward-re                           139         0.0299999999  0.0002158273
715 ;;;cperl-comment-indent                       26          0.0299999999  0.0011538461
716 ;;;cperl-use-region-p                         8           0.0           0.0
717 ;;;cperl-lazy-hook                            15          0.0           0.0
718 ;;;cperl-after-expr-p                         8           0.0           0.0
719 ;;;cperl-font-lock-unfontify-region-function  1           0.0           0.0
720
721 ;;;Function Name                              Call Count  Elapsed Time  Average Time
722 ;;;=========================================  ==========  ============  ============
723 ;;;cperl-fix-line-spacing                     769         1.4500000000  0.0018855656
724 ;;;cperl-indent-line                          13          0.3100000000  0.0238461538
725 ;;;cperl-after-block-and-statement-beg        69          0.2700000000  0.0039130434
726 ;;;cperl-after-block-p                        69          0.2099999999  0.0030434782
727 ;;;cperl-calculate-indent                     13          0.1000000000  0.0076923076
728 ;;;cperl-backward-to-noncomment               177         0.0700000000  0.0003954802
729 ;;;cperl-get-state                            13          0.0           0.0
730 ;;;cperl-to-comment-or-eol                    179         0.0           0.0
731 ;;;cperl-get-help-defer                       1           0.0           0.0
732 ;;;cperl-lazy-hook                            11          0.0           0.0
733 ;;;cperl-after-expr-p                         2           0.0           0.0
734 ;;;cperl-block-p                              13          0.0           0.0
735 ;;;cperl-after-label                          5           0.0           0.0
736
737 ;;;; After 3.12:
738 ;;;  (`cperl-find-pods-heres'): do not warn on `=cut' if doing a chunk only.
739
740 ;;;; After 3.13:
741 ;;;  (`cperl-mode'): load pseudo-faces on `cperl-find-pods-heres' (for 19.30).
742 ;;;  (`x-color-defined-p'): was not compiling on XEmacs
743 ;;;  (`cperl-find-pods-heres'): 1 << 6 was OK, but 1<<6 was considered as HERE
744 ;;;                             <file/glob> made into a string.
745
746 ;;;; After 3.14:
747 ;;;  (`cperl-find-pods-heres'): Postpone addition of faces after syntactic step
748 ;;;                             Recognition of <FH> was wrong.
749 ;;;  (`cperl-clobber-lisp-bindings'): if set, C-c variants are the old ones
750 ;;;  (`cperl-unwind-to-safe'):  New function.
751 ;;;  (`cperl-fontify-syntaxically'): Use `cperl-unwind-to-safe' to start at reasonable position.
752
753 ;;;; After 3.15:
754 ;;;  (`cperl-forward-re'):      Highlight the trailing / in s/foo// as string.
755 ;;;                     Highlight the starting // in s//foo/ as function-name.
756
757 ;;;; After 3.16:
758 ;;;  (`cperl-find-pods-heres'): Highlight `gem' in s///gem as a keyword.
759
760 ;;;; After 4.0:
761 ;;;  (`cperl-find-pods-heres'): `qr' added
762 ;;;  (`cperl-electric-keyword'):        Likewise
763 ;;;  (`cperl-electric-else'):           Likewise
764 ;;;  (`cperl-to-comment-or-eol'):       Likewise
765 ;;;  (`cperl-make-regexp-x'):   Likewise
766 ;;;  (`cperl-init-faces'):      Likewise, and `lock' (as overridable?).
767 ;;;  (`cperl-find-pods-heres'): Knows that split// is null-RE.
768 ;;;                             Highlights separators in 3-parts expressions
769 ;;;                             as labels.
770
771 ;;;; After 4.1:
772 ;;;  (`cperl-find-pods-heres'): <> was considered as a glob
773 ;;;  (`cperl-syntaxify-unwind'): New configuration variable
774 ;;;  (`cperl-fontify-m-as-s'):  New configuration variable
775
776 ;;;; After 4.2:
777 ;;;  (`cperl-find-pods-heres'): of the last line being `=head1' fixed.
778
779 ;;;  Handling of a long construct is still buggy if only the part of
780 ;;;  construct touches the updated region (we unwind to the start of
781 ;;;  long construct, but the end may have residual properties).
782
783 ;;;  (`cperl-unwind-to-safe'):  would not go to beginning of buffer.
784 ;;;  (`cperl-electric-pod'):    check for after-expr was performed
785 ;;;                             inside of POD too.
786
787 ;;;; After 4.3:
788 ;;;  (`cperl-backward-to-noncomment'):  better treatment of PODs and HEREs.
789
790 ;;;  Indent-line works good, but indent-region does not - at toplevel...
791 ;;;  (`cperl-unwind-to-safe'):  Signature changed.
792 ;;;  (`x-color-defined-p'):     was defmacro'ed with a tick.  Remove another def.
793 ;;;  (`cperl-clobber-mode-lists'): New configuration variable.
794 ;;;  (`cperl-array-face'): One of definitions was garbled.
795
796 ;;;; After 4.4:
797 ;;;  (`cperl-not-bad-style-regexp'):    Updated.
798 ;;;  (`cperl-make-regexp-x'):   Misprint in a message.
799 ;;;  (`cperl-find-pods-heres'): $a-1 ? foo : bar; was a regexp.
800 ;;;                             `<< (' was considered a start of POD.
801 ;;;  Init:                      `cperl-is-face' was busted.
802 ;;;  (`cperl-make-face'):       New macros.
803 ;;;  (`cperl-force-face'):      New macros.
804 ;;;  (`cperl-init-faces'):      Corrected to use new macros;
805 ;;;                             `if' for copying `reference-face' to
806 ;;;                             `constant-face' was backward.
807 ;;;  (`font-lock-other-type-face'): Done via `defface' too.
808
809 ;;;; After 4.5:
810 ;;;  (`cperl-init-faces-weak'): use `cperl-force-face'.
811 ;;;  (`cperl-after-block-p'):   After END/BEGIN we are a block.
812 ;;;  (`cperl-mode'):            `font-lock-unfontify-region-function'
813 ;;;                             was set to a wrong function.
814 ;;;  (`cperl-comment-indent'):  Commenting __END__ was not working.
815 ;;;  (`cperl-indent-for-comment'):      Likewise.
816 ;;;                             (Indenting is still misbehaving at toplevel.)
817
818 ;;;; After 4.5:
819 ;;;  (`cperl-unwind-to-safe'):  Signature changed, unwinds end too.
820 ;;;  (`cperl-find-pods-heres'): mark qq[]-etc sections as syntax-type=string
821 ;;;  (`cperl-fontify-syntaxically'): Unwinds start and end to go out of
822 ;;;                                  long strings (not very successful).
823
824 ;;;   >>>>  CPerl should be usable in write mode too now <<<<
825
826 ;;;  (`cperl-syntaxify-by-font-lock'): Better default - off in text-mode.
827 ;;;  (`cperl-tips'):            Updated docs.
828 ;;;  (`cperl-problems'):        Updated docs.
829
830 ;;;; After 4.6:
831 ;;;  (`cperl-calculate-indent'):        Did not consider `,' as continuation mark for statements.
832 ;;;  (`cperl-write-tags'):      Correct for XEmacs's `visit-tags-table-buffer'.
833
834 ;;;; After 4.7:
835 ;;;  (`cperl-calculate-indent'): Avoid parse-data optimization at toplevel.
836 ;;;                              Should indent correctly at toplevel too.
837 ;;;  (`cperl-tags-hier-init'):  Gross hack to pretend we work (are we?).
838 ;;;  (`cperl-find-pods-heres'): Was not processing sub protos after a comment ine.
839 ;;;                             Was treating $a++ <= 5 as a glob.
840
841 ;;;; After 4.8:
842 ;;;  (toplevel):                require custom unprotected => failure on 19.28.
843 ;;;  (`cperl-xemacs-p')         defined when compile too
844 ;;;  (`cperl-tags-hier-init'):  Another try to work around XEmacs problems
845 ;;;                             Better progress messages.
846 ;;;  (`cperl-find-tags'):       Was writing line/pos in a wrong order,
847 ;;;                             pos off by 1 and not at beg-of-line.
848 ;;;  (`cperl-etags-snarf-tag'): New macro
849 ;;;  (`cperl-etags-goto-tag-location'): New macro
850 ;;;  (`cperl-write-tags'):      When removing old TAGS info was not
851 ;;;                             relativizing filename
852
853 ;;;; After 4.9:
854 ;;;  (`cperl-version'):         New variable.  New menu entry
855
856 ;;;; After 4.10:
857 ;;;  (`cperl-tips'):            Updated.
858 ;;;  (`cperl-non-problems'):    Updated.
859 ;;;  random:                    References to future 20.3 removed.
860
861 ;;;; After 4.11:
862 ;;;  (`perl-font-lock-keywords'): Would not highlight `sub foo($$);'.
863 ;;;  Docstrings:                Menu was described as `CPerl' instead of `Perl'
864
865 ;;;; After 4.12:
866 ;;;  (`cperl-toggle-construct-fix'): Was toggling to t instead of 1.
867 ;;;  (`cperl-ps-print-init'):   Associate `cperl-array-face', `cperl-hash-face'
868 ;;;                             remove `font-lock-emphasized-face'.
869 ;;;                             remove `font-lock-other-emphasized-face'.
870 ;;;                             remove `font-lock-reference-face'.
871 ;;;                             remove `font-lock-keyword-face'.
872 ;;;                             Use `eval-after-load'.
873 ;;;  (`cperl-init-faces'):      remove init `font-lock-other-emphasized-face'.
874 ;;;                             remove init `font-lock-emphasized-face'.
875 ;;;                             remove init `font-lock-keyword-face'.
876 ;;;  (`cperl-tips-faces'):      New variable and an entry into Mini-docs.
877 ;;;  (`cperl-indent-region'):   Do not indent whitespace lines
878 ;;;  (`cperl-indent-exp'):      Was not processing else-blocks.
879 ;;;  (`cperl-calculate-indent'): Remove another parse-data optimization
880 ;;;                              at toplevel: would indent correctly.
881 ;;;  (`cperl-get-state'):       NOP line removed.
882
883 ;;;; After 4.13:
884 ;;;  (`cperl-ps-print-init'):   Remove not-CPerl-related faces.
885 ;;;  (`cperl-ps-print'):        New function and menu entry.
886 ;;;  (`cperl-ps-print-face-properties'):        New configuration variable.
887 ;;;  (`cperl-invalid-face'):    New configuration variable.
888 ;;;  (`cperl-nonoverridable-face'):     New face.  Renamed from
889 ;;;                                     `font-lock-other-type-face'.
890 ;;;  (`perl-font-lock-keywords'):       Highlight trailing whitespace
891 ;;;  (`cperl-contract-levels'): Documentation corrected.
892 ;;;  (`cperl-contract-level'):  Likewise.
893
894 ;;;; After 4.14:
895 ;;;  (`cperl-ps-print'): `ps-print-face-extension-alist' was not in old Emaxen,
896 ;;;                             same with `ps-extend-face-list'
897 ;;;  (`cperl-ps-extend-face-list'):     New macro.
898
899 ;;;; After 4.15:
900 ;;;  (`cperl-init-faces'):      Interpolate `cperl-invalid-face'.
901 ;;;  (`cperl-forward-re'):      Emit a meaningful error instead of a cryptic
902 ;;;                             one for uncomplete REx near end-of-buffer.
903 ;;;  (`cperl-find-pods-heres'): Tolerate unfinished REx at end-of-buffer.
904
905 ;;;; After 4.16:
906 ;;;  (`cperl-find-pods-heres'): `unwind-protect' was left commented.
907
908 ;;;; After 4.17:
909 ;;;  (`cperl-invalid-face'):    Change to ''underline.
910
911 ;;;; After 4.18:
912 ;;;  (`cperl-find-pods-heres'): / and ? after : start a REx.
913 ;;;  (`cperl-after-expr-p'):    Skip labels when checking
914 ;;;  (`cperl-calculate-indent'): Correct for labels when calculating
915 ;;;                                     indentation of continuations.
916 ;;;                             Docstring updated.
917
918 ;;;; After 4.19:
919 ;;;  Minor (mostly spelling) corrections from 20.3.3 merged.
920
921 ;;;; After 4.20:
922 ;;;  (`cperl-tips'):            Another workaround added.  Sent to RMS for 20.4.
923
924 ;;;; After 4.21:
925 ;;;  (`cperl-praise'):          Mention linear-time indent.
926 ;;;  (`cperl-find-pods-heres'): @if ? a : b was considered a REx.
927
928 ;;;; After 4.22:
929 ;;;  (`cperl-after-expr-p'):    Make true after __END__.
930 ;;;  (`cperl-electric-pod'):    "SYNOPSIS" was misspelled.
931
932 ;;;; After 4.23:
933 ;;;  (`cperl-beautify-regexp-piece'):   Was not allowing for *? after a class.
934 ;;;                                     Allow for POSIX char-classes.
935 ;;;                                     Remove trailing whitespace when
936 ;;;                                     adding new linebreak.
937 ;;;                                     Add a level counter to stop shallow.
938 ;;;                                     Indents unprocessed groups rigidly.
939 ;;;  (`cperl-beautify-regexp'): Add an optional count argument to go that
940 ;;;                             many levels deep.
941 ;;;  (`cperl-beautify-level'):  Likewise
942 ;;;  Menu:                      Add new entries to Regexp menu to do one level
943 ;;;  (`cperl-contract-level'):  Was entering an infinite loop
944 ;;;  (`cperl-find-pods-heres'): Typo (double quoting).
945 ;;;                             Was detecting < $file > as FH instead of glob.
946 ;;;                             Support for comments in RExen (except
947 ;;;                             for m#\#comment#x), governed by
948 ;;;                             `cperl-regexp-scan'.
949 ;;;  (`cperl-regexp-scan'):     New customization variable.
950 ;;;  (`cperl-forward-re'):      Improve logic of resetting syntax table.
951
952 ;;;; After 4.23 and: After 4.24:
953 ;;;  (`cperl-contract-levels'): Restore position.
954 ;;;  (`cperl-beautify-level'):  Likewise.
955 ;;;  (`cperl-beautify-regexp'): Likewise.
956 ;;;  (`cperl-commentify'):      Rudimental support for length=1 runs
957 ;;;  (`cperl-find-pods-heres'): Process 1-char long REx comments too /a#/x
958 ;;;                             Processes REx-comments in #-delimited RExen.
959 ;;;                             MAJOR BUG CORRECTED: after a misparse
960 ;;;                               a body of a subroutine could be corrupted!!!
961 ;;;                               One might need to reeval the function body
962 ;;;                               to fix things.  (A similar bug was
963 ;;;                               present in `cperl-indent-region' eons ago.)
964 ;;; To reproduce:
965 ;;   (defun foo () (let ((a '(t))) (insert (format "%s" a)) (setcar a 'BUG) t))
966 ;;   (foo)
967 ;;   (foo)
968 ;;; C-x C-e the above three lines (at end-of-line).  First evaluation
969 ;;; of `foo' inserts (t), second one inserts (BUG) ?!
970 ;;;
971 ;;; In CPerl it was triggered by inserting then deleting `/' at start of
972 ;;;      /  a (?# asdf  {[(}asdf )ef,/;
973
974 ;;;; After 4.25:
975 ;;; (`cperl-commentify'):       Was recognizing length=2 "strings" as length=1.
976 ;;; (`imenu-example--create-perl-index'):
977 ;;;                             Was not enforcing syntaxification-to-the-end.
978 ;;; (`cperl-invert-if-unless'): Allow `for', `foreach'.
979 ;;; (`cperl-find-pods-heres'):  Quote `cperl-nonoverridable-face'.
980 ;;;                             Mark qw(), m()x as indentable.
981 ;;; (`cperl-init-faces'):       Highlight `sysopen' too.
982 ;;;                             Highlight $var in `for my $var' too.
983 ;;; (`cperl-invert-if-unless'): Was leaving whitespace at end.
984 ;;; (`cperl-linefeed'):         Was splitting $var{$foo} if point after `{'.
985 ;;; (`cperl-calculate-indent'): Remove old commented out code.
986 ;;;                             Support (primitive) indentation of qw(), m()x.
987
988
989 ;;;; After 4.26:
990 ;;; (`cperl-problems'):         Mention `fill-paragraph' on comment. \"" and
991 ;;;                             q [] with intervening newlines.
992 ;;; (`cperl-autoindent-on-semi'):       New customization variable.
993 ;;; (`cperl-electric-semi'):    Use `cperl-autoindent-on-semi'.
994 ;;; (`cperl-tips'):             Mention how to make CPerl the default mode.
995 ;;; (`cperl-mode'):             Support `outline-minor-mode'
996 ;;;                             (Thanks to Mark A. Hershberger).
997 ;;; (`cperl-outline-level'):    New function.
998 ;;; (`cperl-highlight-variables-indiscriminately'):     New customization var.
999 ;;; (`cperl-init-faces'):       Use `cperl-highlight-variables-indiscriminately'.
1000 ;;;                             (Thanks to Sean Kamath <kamath@pogo.wv.tek.com>).
1001 ;;; (`cperl-after-block-p'):    Support CHECK and INIT.
1002 ;;; (`cperl-init-faces'):       Likewise and "our".
1003 ;;;                             (Thanks to Doug MacEachern <dougm@covalent.net>).
1004 ;;; (`cperl-short-docs'):       Likewise and "our".
1005
1006
1007 ;;;; After 4.27:
1008 ;;; (`cperl-find-pods-heres'):  Recognize \"" as a string.
1009 ;;;                             Mark whitespace and comments between q and []
1010 ;;;                               as `syntax-type' => `prestring'.
1011 ;;;                             Allow whitespace between << and "FOO".
1012 ;;; (`cperl-problems'):         Remove \"" and q [] with intervening newlines.
1013 ;;;                             Mention multiple <<EOF as unsupported.
1014 ;;; (`cperl-highlight-variables-indiscriminately'):     Doc misprint fixed.
1015 ;;; (`cperl-indent-parens-as-block'):   New configuration variable.
1016 ;;; (`cperl-calculate-indent'): Merge cases of indenting non-BLOCK groups.
1017 ;;;                             Use `cperl-indent-parens-as-block'.
1018 ;;; (`cperl-find-pods-heres'):  Test for =cut without empty line instead of
1019 ;;;                             complaining about no =cut.
1020 ;;; (`cperl-electric-pod'):     Change the REx for POD from "\n\n=" to "^\n=".
1021 ;;; (`cperl-find-pods-heres'):  Likewise.
1022 ;;; (`cperl-electric-pod'):     Change `forward-sexp' to `forward-word':
1023 ;;;                             POD could've been marked as comment already.
1024 ;;; (`cperl-unwind-to-safe'):   Unwind before start of POD too.
1025
1026 ;;;; After 4.28:
1027 ;;; (`cperl-forward-re'):       Throw an error at proper moment REx unfinished.
1028
1029 ;;;; After 4.29:
1030 ;;; (`x-color-defined-p'):      Make an extra case to peacify the warning.
1031 ;;; Toplevel:                   `defvar' to peacify the warnings.
1032 ;;; (`cperl-find-pods-heres'):  Could access `font-lock-comment-face' in -nw.
1033 ;;;;                            No -nw-compile time warnings now.
1034 ;;; (`cperl-find-tags'):        TAGS file had too short substring-to-search.
1035 ;;;                             Be less verbose in non-interactive mode
1036 ;;; (`imenu-example--create-perl-index'):       Set index-marker after name
1037 ;;; (`cperl-outline-regexp'):   New variable.
1038 ;;; (`cperl-outline-level'):    Made compatible with `cperl-outline-regexp'.
1039 ;;; (`cperl-mode'):             Made use `cperl-outline-regexp'.
1040
1041 ;;;; After 4.30:
1042 ;;; (`cperl-find-pods-heres'):  =cut the last thing, no blank line, was error.
1043 ;;; (`cperl-outline-level'):    Make start-of-file same level as `package'.
1044
1045 ;;;; After 4.31:
1046 ;;; (`cperl-electric-pod'):     `head1' and `over' electric only if empty.
1047 ;;; (`cperl-unreadable-ok'):    New variable.
1048 ;;; (`cperl-find-tags'):        Use `cperl-unreadable-ok', do not fail
1049 ;;;                             on an unreadable file
1050 ;;; (`cperl-write-tags'):       Use `cperl-unreadable-ok', do not fail
1051 ;;;                             on an unreadable directory
1052
1053 ;;;; After 4.32:
1054 ;;;  Syncronized with v1.60 from Emacs 21.3.
1055 ;;;  Mostly docstring and formatting changes, and:
1056
1057 ;;;  (`cperl-noscan-files-regexp'): Do not scan CVS subdirs
1058 ;;;  (`cperl-problems'):        Note that newer XEmacsen may syntaxify too
1059 ;;;  (`imenu-example--create-perl-index'):
1060 ;;;                             Renamed to `cperl-imenu--create-perl-index'
1061 ;;;  (`cperl-mode'):            Replace `make-variable-buffer-local' by `make-local-variable'
1062 ;;;  (`cperl-setup-tmp-buf'):   Likewise
1063 ;;;  (`cperl-fix-line-spacing'): Fix a misprint of "t" for "\t"
1064 ;;;  (`cperl-next-bad-style'):  Fix misprints in character literals
1065
1066 ;;;; After 4.33:
1067 ;;;  (`cperl-font-lock-keywords'): +etc: Aliased to perl-font-lock-keywords.
1068
1069 ;;;; After 4.34:
1070 ;;;  Further updates of whitespace and spelling w.r.t. RMS version.
1071 ;;;  (`cperl-font-lock-keywords'): +etc: Avoid warnings when aliasing.
1072 ;;;  (`cperl-mode'):            Use `normal-auto-fill-function' if present.
1073 ;;;  (`cperl-use-major-mode'):  New variable
1074 ;;;  (`cperl-can-font-lock'):   New variable; replaces `window-system'
1075 ;;;  (`cperl-tags-hier-init'):  use `display-popup-menus-p' (if present)
1076 ;;;                             to choose `x-popup-menu' vs `tmm-prompt'
1077
1078 ;;;; 4.35 has the following differences from version 1.40+ of RMS Emacs:
1079
1080 ;;; New variables `cperl-use-major-mode', `cperl-can-font-lock';
1081 ;;; `cperl-use-major-mode' is (effectively) 'cperl-mode in RMS.
1082 ;;; `cperl-under-as-char'  is nil in RMS.
1083 ;;; Minor differences in docstrings, and `cperl-non-problems'.
1084 ;;; Backward compatibility addressed: (`); (function (lambda ...)); font-lock;
1085 ;;; (:italic t bold t) vs (:slant italic :weight bold) in faces;
1086 ;;; `normal-auto-fill-function'.
1087 ;;; RMS version has wrong logic in `cperl-calculate-indent': $a = { } is
1088 ;;; wrongly indented if the closing brace is on a separate line.
1089 ;;; Different choice of ordering if's for is-x-REx and (eq (char-after b) ?\#)
1090 ;;; in `cperl-find-pods-heres'. [Cosmetic]
1091
1092 ;;;; After 4.35:
1093 ;;;  (`cperl-find-pods-heres'): If no end of HERE-doc found, mark to the end
1094 ;;;                             of buffer.  This enables recognition of end
1095 ;;;                             of HERE-doc "as one types".
1096 ;;;                             Require "\n" after trailing tag of HERE-doc.
1097 ;;;                             \( made non-quoting outside of string/comment
1098 ;;;                             (gdj-contributed).
1099 ;;;                             Likewise for \$.
1100 ;;;                             Remove `here-doc-group' text property at start
1101 ;;;                             (makes this property reliable).
1102 ;;;                             Text property `first-format-line' ==> t.
1103 ;;;                             Do not recognize $opt_s and $opt::s as s///.
1104 ;;;  (`cperl-perldoc'):         Use case-sensitive search (contributed).
1105 ;;;  (`cperl-fix-line-spacing'): Allow "_" in $vars of foreach etc. when
1106 ;;;                             underscore isn't a word char (gdj-contributed).
1107 ;;;  (`defun-prompt-regexp'):   Allow prototypes.
1108 ;;;  (`cperl-vc-header-alist'): Extract numeric version from the Id.
1109 ;;;  Toplevel:                  Put toggle-autohelp into the mode menu.
1110 ;;;                             Better docs for toggle/set/unset autohelp.
1111 ;;;  (`cperl-electric-backspace-untabify'): New customization variable
1112 ;;;  (`cperl-after-expr-p'):    Works after here-docs, formats, and PODs too
1113 ;;;                             (affects many electric constructs).
1114 ;;;  (`cperl-calculate-indent'): Takes into account `first-format-line' ==>
1115 ;;;                             works after format.
1116 ;;;  (`cperl-short-docs'):      Make it work with ... too.
1117 ;;;                             "array context" ==> "list context"
1118 ;;;  (`cperl-electric-keyword'): make $if (etc: "$@%&*") non-electric
1119 ;;;                             '(' after keyword would insert a doubled paren
1120 ;;;  (`cperl-electric-paren'):  documented affected by `cperl-electric-parens'
1121 ;;;  (`cperl-electric-rparen'): Likewise
1122 ;;;  (`cperl-build-manpage'):   New function by Nick Roberts
1123 ;;;  (`cperl-perldoc'):         Make it work in XEmacs too
1124
1125 ;;;; After 4.36:
1126 ;;;  (`cperl-find-pods-heres'): Recognize s => 1 and {s} (as a key or varname),
1127 ;;;                             { s:: } and { s::bar::baz } as varnames.
1128 ;;;  (`cperl-after-expr-p'):    Updates syntaxification before checks
1129 ;;;  (`cperl-calculate-indent'): Likewise
1130 ;;;                             Fix wrong indent of blocks starting with POD
1131 ;;;  (`cperl-after-block-p'):   Optional argument for checking for a pre-block
1132 ;;;                             Recognize `continue' blocks too.
1133 ;;;  (`cperl-electric-brace'):  use `cperl-after-block-p' for detection;
1134 ;;;                             Now works for else/continue/sub blocks
1135 ;;;  (`cperl-short-docs'):      Minor edits; make messages fit 80-column screen
1136
1137 ;;;; After 4.37:
1138 ;;;  `cperl-add-tags-recurse-noxs-fullpath'
1139 ;;;    added (for -batch mode);
1140
1141 ;;; Code:
1142
1143 \f
1144 (if (fboundp 'eval-when-compile)
1145     (eval-when-compile
1146       (condition-case nil
1147           (require 'custom)
1148         (error nil))
1149       (condition-case nil
1150           (require 'man)
1151         (error nil))
1152       (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1153       (defvar cperl-can-font-lock
1154         (or cperl-xemacs-p
1155             (and (boundp 'emacs-major-version)
1156                  (or window-system
1157                      (> emacs-major-version 20)))))
1158       (if cperl-can-font-lock
1159           (require 'font-lock))
1160       (defvar msb-menu-cond)
1161       (defvar gud-perldb-history)
1162       (defvar font-lock-background-mode) ; not in Emacs
1163       (defvar font-lock-display-type)   ; ditto
1164       (or (fboundp 'defgroup)
1165           (defmacro defgroup (name val doc &rest arr)
1166             nil))
1167       (or (fboundp 'custom-declare-variable)
1168           (defmacro defcustom (name val doc &rest arr)
1169             (` (defvar (, name) (, val) (, doc)))))
1170       (or (and (fboundp 'custom-declare-variable)
1171                (string< "19.31" emacs-version)) ;  Checked with 19.30: defface does not work
1172           (defmacro defface (&rest arr)
1173             nil))
1174       ;; Avoid warning (tmp definitions)
1175       (or (fboundp 'x-color-defined-p)
1176           (defmacro x-color-defined-p (col)
1177             (cond ((fboundp 'color-defined-p) (` (color-defined-p (, col))))
1178                   ;; XEmacs >= 19.12
1179                   ((fboundp 'valid-color-name-p) (` (valid-color-name-p (, col))))
1180                   ;; XEmacs 19.11
1181                   ((fboundp 'x-valid-color-name-p) (` (x-valid-color-name-p (, col))))
1182                   (t '(error "Cannot implement color-defined-p")))))
1183       (defmacro cperl-is-face (arg)     ; Takes quoted arg
1184         (cond ((fboundp 'find-face)
1185                (` (find-face (, arg))))
1186               (;;(and (fboundp 'face-list)
1187                ;;       (face-list))
1188                (fboundp 'face-list)
1189                (` (member (, arg) (and (fboundp 'face-list)
1190                                        (face-list)))))
1191               (t
1192                (` (boundp (, arg))))))
1193       (defmacro cperl-make-face (arg descr) ; Takes unquoted arg
1194         (cond ((fboundp 'make-face)
1195                (` (make-face (quote (, arg)))))
1196               (t
1197                (` (defvar (, arg) (quote (, arg)) (, descr))))))
1198       (defmacro cperl-force-face (arg descr) ; Takes unquoted arg
1199         (` (progn
1200              (or (cperl-is-face (quote (, arg)))
1201                  (cperl-make-face (, arg) (, descr)))
1202              (or (boundp (quote (, arg))) ; We use unquoted variants too
1203                  (defvar (, arg) (quote (, arg)) (, descr))))))
1204       (if cperl-xemacs-p
1205           (defmacro cperl-etags-snarf-tag (file line)
1206             (` (progn
1207                  (beginning-of-line 2)
1208                  (list (, file) (, line)))))
1209         (defmacro cperl-etags-snarf-tag (file line)
1210           (` (etags-snarf-tag))))
1211       (if cperl-xemacs-p
1212           (defmacro cperl-etags-goto-tag-location (elt)
1213             (`;;(progn
1214              ;; (switch-to-buffer (get-file-buffer (elt (, elt) 0)))
1215              ;; (set-buffer (get-file-buffer (elt (, elt) 0)))
1216              ;; Probably will not work due to some save-excursion???
1217              ;; Or save-file-position?
1218              ;; (message "Did I get to line %s?" (elt (, elt) 1))
1219              (goto-line (string-to-int (elt (, elt) 1)))))
1220         ;;)
1221         (defmacro cperl-etags-goto-tag-location (elt)
1222           (` (etags-goto-tag-location (, elt)))))))
1223
1224 (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
1225
1226 (defvar cperl-can-font-lock
1227   (or cperl-xemacs-p
1228       (and (boundp 'emacs-major-version)
1229            (or window-system
1230                (> emacs-major-version 20)))))
1231
1232 (condition-case nil
1233     (require 'custom)
1234   (error nil))                          ; Already fixed by eval-when-compile
1235
1236 (defun cperl-choose-color (&rest list)
1237   (let (answer)
1238     (while list
1239       (or answer
1240           (if (or (x-color-defined-p (car list))
1241                   (null (cdr list)))
1242               (setq answer (car list))))
1243       (setq list (cdr list)))
1244     answer))
1245
1246 \f
1247 (defgroup cperl nil
1248   "Major mode for editing Perl code."
1249   :prefix "cperl-"
1250   :group 'languages)
1251
1252 (defgroup cperl-indentation-details nil
1253   "Indentation."
1254   :prefix "cperl-"
1255   :group 'cperl)
1256
1257 (defgroup cperl-affected-by-hairy nil
1258   "Variables affected by `cperl-hairy'."
1259   :prefix "cperl-"
1260   :group 'cperl)
1261
1262 (defgroup cperl-autoinsert-details nil
1263   "Auto-insert tuneup."
1264   :prefix "cperl-"
1265   :group 'cperl)
1266
1267 (defgroup cperl-faces nil
1268   "Fontification colors."
1269   :prefix "cperl-"
1270   :group 'cperl)
1271
1272 (defgroup cperl-speed nil
1273   "Speed vs. validity tuneup."
1274   :prefix "cperl-"
1275   :group 'cperl)
1276
1277 (defgroup cperl-help-system nil
1278   "Help system tuneup."
1279   :prefix "cperl-"
1280   :group 'cperl)
1281
1282 \f
1283 (defcustom cperl-extra-newline-before-brace nil
1284   "*Non-nil means that if, elsif, while, until, else, for, foreach
1285 and do constructs look like:
1286
1287         if ()
1288         {
1289         }
1290
1291 instead of:
1292
1293         if () {
1294         }"
1295   :type 'boolean
1296   :group 'cperl-autoinsert-details)
1297
1298 (defcustom cperl-extra-newline-before-brace-multiline
1299   cperl-extra-newline-before-brace
1300   "*Non-nil means the same as `cperl-extra-newline-before-brace', but
1301 for constructs with multiline if/unless/while/until/for/foreach condition."
1302   :type 'boolean
1303   :group 'cperl-autoinsert-details)
1304
1305 (defcustom cperl-indent-level 2
1306   "*Indentation of CPerl statements with respect to containing block."
1307   :type 'integer
1308   :group 'cperl-indentation-details)
1309
1310 (defcustom cperl-lineup-step nil
1311   "*`cperl-lineup' will always lineup at multiple of this number.
1312 If nil, the value of `cperl-indent-level' will be used."
1313   :type '(choice (const nil) integer)
1314   :group 'cperl-indentation-details)
1315
1316 (defcustom cperl-brace-imaginary-offset 0
1317   "*Imagined indentation of a Perl open brace that actually follows a statement.
1318 An open brace following other text is treated as if it were this far
1319 to the right of the start of its line."
1320   :type 'integer
1321   :group 'cperl-indentation-details)
1322
1323 (defcustom cperl-brace-offset 0
1324   "*Extra indentation for braces, compared with other text in same context."
1325   :type 'integer
1326   :group 'cperl-indentation-details)
1327 (defcustom cperl-label-offset -2
1328   "*Offset of CPerl label lines relative to usual indentation."
1329   :type 'integer
1330   :group 'cperl-indentation-details)
1331 (defcustom cperl-min-label-indent 1
1332   "*Minimal offset of CPerl label lines."
1333   :type 'integer
1334   :group 'cperl-indentation-details)
1335 (defcustom cperl-continued-statement-offset 2
1336   "*Extra indent for lines not starting new statements."
1337   :type 'integer
1338   :group 'cperl-indentation-details)
1339 (defcustom cperl-continued-brace-offset 0
1340   "*Extra indent for substatements that start with open-braces.
1341 This is in addition to cperl-continued-statement-offset."
1342   :type 'integer
1343   :group 'cperl-indentation-details)
1344 (defcustom cperl-close-paren-offset -1
1345   "*Extra indent for substatements that start with close-parenthesis."
1346   :type 'integer
1347   :group 'cperl-indentation-details)
1348
1349 (defcustom cperl-auto-newline nil
1350   "*Non-nil means automatically newline before and after braces,
1351 and after colons and semicolons, inserted in CPerl code.  The following
1352 \\[cperl-electric-backspace] will remove the inserted whitespace.
1353 Insertion after colons requires both this variable and
1354 `cperl-auto-newline-after-colon' set."
1355   :type 'boolean
1356   :group 'cperl-autoinsert-details)
1357
1358 (defcustom cperl-autoindent-on-semi nil
1359   "*Non-nil means automatically indent after insertion of (semi)colon.
1360 Active if `cperl-auto-newline' is false."
1361   :type 'boolean
1362   :group 'cperl-autoinsert-details)
1363
1364 (defcustom cperl-auto-newline-after-colon nil
1365   "*Non-nil means automatically newline even after colons.
1366 Subject to `cperl-auto-newline' setting."
1367   :type 'boolean
1368   :group 'cperl-autoinsert-details)
1369
1370 (defcustom cperl-tab-always-indent t
1371   "*Non-nil means TAB in CPerl mode should always reindent the current line,
1372 regardless of where in the line point is when the TAB command is used."
1373   :type 'boolean
1374   :group 'cperl-indentation-details)
1375
1376 (defcustom cperl-font-lock nil
1377   "*Non-nil (and non-null) means CPerl buffers will use `font-lock-mode'.
1378 Can be overwritten by `cperl-hairy' if nil."
1379   :type '(choice (const null) boolean)
1380   :group 'cperl-affected-by-hairy)
1381
1382 (defcustom cperl-electric-lbrace-space nil
1383   "*Non-nil (and non-null) means { after $ should be preceded by ` '.
1384 Can be overwritten by `cperl-hairy' if nil."
1385   :type '(choice (const null) boolean)
1386   :group 'cperl-affected-by-hairy)
1387
1388 (defcustom cperl-electric-parens-string "({[]})<"
1389   "*String of parentheses that should be electric in CPerl.
1390 Closing ones are electric only if the region is highlighted."
1391   :type 'string
1392   :group 'cperl-affected-by-hairy)
1393
1394 (defcustom cperl-electric-parens nil
1395   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
1396 Can be overwritten by `cperl-hairy' if nil."
1397   :type '(choice (const null) boolean)
1398   :group 'cperl-affected-by-hairy)
1399
1400 (defvar zmacs-regions)                  ; Avoid warning
1401
1402 (defcustom cperl-electric-parens-mark
1403   (and window-system
1404        (or (and (boundp 'transient-mark-mode) ; For Emacs
1405                 transient-mark-mode)
1406            (and (boundp 'zmacs-regions) ; For XEmacs
1407                 zmacs-regions)))
1408   "*Not-nil means that electric parens look for active mark.
1409 Default is yes if there is visual feedback on mark."
1410   :type 'boolean
1411   :group 'cperl-autoinsert-details)
1412
1413 (defcustom cperl-electric-linefeed nil
1414   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
1415 In any case these two mean plain and hairy linefeeds together.
1416 Can be overwritten by `cperl-hairy' if nil."
1417   :type '(choice (const null) boolean)
1418   :group 'cperl-affected-by-hairy)
1419
1420 (defcustom cperl-electric-keywords nil
1421   "*Not-nil (and non-null) means keywords are electric in CPerl.
1422 Can be overwritten by `cperl-hairy' if nil."
1423   :type '(choice (const null) boolean)
1424   :group 'cperl-affected-by-hairy)
1425
1426 (defcustom cperl-electric-backspace-untabify t
1427   "*Not-nil means electric-backspace will untabify in CPerl."
1428   :type 'boolean
1429   :group 'cperl-autoinsert-details)
1430
1431 (defcustom cperl-hairy nil
1432   "*Not-nil means most of the bells and whistles are enabled in CPerl.
1433 Affects: `cperl-font-lock', `cperl-electric-lbrace-space',
1434 `cperl-electric-parens', `cperl-electric-linefeed', `cperl-electric-keywords',
1435 `cperl-info-on-command-no-prompt', `cperl-clobber-lisp-bindings',
1436 `cperl-lazy-help-time'."
1437   :type 'boolean
1438   :group 'cperl-affected-by-hairy)
1439
1440 (defcustom cperl-comment-column 32
1441   "*Column to put comments in CPerl (use \\[cperl-indent] to lineup with code)."
1442   :type 'integer
1443   :group 'cperl-indentation-details)
1444
1445 (defcustom cperl-vc-header-alist '((SCCS "($sccs) = ('%W\%' =~ /(\\d+(\\.\\d+)+)/) ;")
1446                                    (RCS "($rcs) = (' $Id\$ ' =~ /(\\d+(\\.\\d+)+)/) ;"))
1447   "*What to use as `vc-header-alist' in CPerl."
1448   :type '(repeat (list symbol string))
1449   :group 'cperl)
1450
1451 (defcustom cperl-clobber-mode-lists
1452   (not
1453    (and
1454     (boundp 'interpreter-mode-alist)
1455     (assoc "miniperl" interpreter-mode-alist)
1456     (assoc "\\.\\([pP][Llm]\\|al\\)$" auto-mode-alist)))
1457   "*Whether to install us into `interpreter-' and `extension' mode lists."
1458   :type 'boolean
1459   :group 'cperl)
1460
1461 (defcustom cperl-info-on-command-no-prompt nil
1462   "*Not-nil (and non-null) means not to prompt on C-h f.
1463 The opposite behaviour is always available if prefixed with C-c.
1464 Can be overwritten by `cperl-hairy' if nil."
1465   :type '(choice (const null) boolean)
1466   :group 'cperl-affected-by-hairy)
1467
1468 (defcustom cperl-clobber-lisp-bindings nil
1469   "*Not-nil (and non-null) means not overwrite C-h f.
1470 The function is available on \\[cperl-info-on-command], \\[cperl-get-help].
1471 Can be overwritten by `cperl-hairy' if nil."
1472   :type '(choice (const null) boolean)
1473   :group 'cperl-affected-by-hairy)
1474
1475 (defcustom cperl-lazy-help-time nil
1476   "*Not-nil (and non-null) means to show lazy help after given idle time.
1477 Can be overwritten by `cperl-hairy' to be 5 sec if nil."
1478   :type '(choice (const null) (const nil) integer)
1479   :group 'cperl-affected-by-hairy)
1480
1481 (defcustom cperl-pod-face 'font-lock-comment-face
1482   "*The result of evaluation of this expression is used for POD highlighting."
1483   :type 'face
1484   :group 'cperl-faces)
1485
1486 (defcustom cperl-pod-head-face 'font-lock-variable-name-face
1487   "*The result of evaluation of this expression is used for POD highlighting.
1488 Font for POD headers."
1489   :type 'face
1490   :group 'cperl-faces)
1491
1492 (defcustom cperl-here-face 'font-lock-string-face
1493   "*The result of evaluation of this expression is used for here-docs highlighting."
1494   :type 'face
1495   :group 'cperl-faces)
1496
1497 (defcustom cperl-invalid-face ''underline ; later evaluated by `font-lock'
1498   "*The result of evaluation of this expression highlights trailing whitespace."
1499   :type 'face
1500   :group 'cperl-faces)
1501
1502 (defcustom cperl-pod-here-fontify '(featurep 'font-lock)
1503   "*Not-nil after evaluation means to highlight POD and here-docs sections."
1504   :type 'boolean
1505   :group 'cperl-faces)
1506
1507 (defcustom cperl-fontify-m-as-s t
1508   "*Not-nil means highlight 1arg regular expressions operators same as 2arg."
1509   :type 'boolean
1510   :group 'cperl-faces)
1511
1512 (defcustom cperl-highlight-variables-indiscriminately nil
1513   "*Non-nil means perform additional highlighting on variables.
1514 Currently only changes how scalar variables are highlighted.
1515 Note that that variable is only read at initialization time for
1516 the variable `perl-font-lock-keywords-2', so changing it after you've
1517 entered CPerl mode the first time will have no effect."
1518   :type 'boolean
1519   :group 'cperl)
1520
1521 (defcustom cperl-pod-here-scan t
1522   "*Not-nil means look for POD and here-docs sections during startup.
1523 You can always make lookup from menu or using \\[cperl-find-pods-heres]."
1524   :type 'boolean
1525   :group 'cperl-speed)
1526
1527 (defcustom cperl-regexp-scan t
1528   "*Not-nil means make marking of regular expression more thorough.
1529 Effective only with `cperl-pod-here-scan'.  Not implemented yet."
1530   :type 'boolean
1531   :group 'cperl-speed)
1532
1533 (defcustom cperl-imenu-addback nil
1534   "*Not-nil means add backreferences to generated `imenu's.
1535 May require patched `imenu' and `imenu-go'.  Obsolete."
1536   :type 'boolean
1537   :group 'cperl-help-system)
1538
1539 (defcustom cperl-max-help-size 66
1540   "*Non-nil means shrink-wrapping of info-buffer allowed up to these percents."
1541   :type '(choice integer (const nil))
1542   :group 'cperl-help-system)
1543
1544 (defcustom cperl-shrink-wrap-info-frame t
1545   "*Non-nil means shrink-wrapping of info-buffer-frame allowed."
1546   :type 'boolean
1547   :group 'cperl-help-system)
1548
1549 (defcustom cperl-info-page "perl"
1550   "*Name of the info page containing perl docs.
1551 Older version of this page was called `perl5', newer `perl'."
1552   :type 'string
1553   :group 'cperl-help-system)
1554
1555 (defcustom cperl-use-syntax-table-text-property
1556   (boundp 'parse-sexp-lookup-properties)
1557   "*Non-nil means CPerl sets up and uses `syntax-table' text property."
1558   :type 'boolean
1559   :group 'cperl-speed)
1560
1561 (defcustom cperl-use-syntax-table-text-property-for-tags
1562   cperl-use-syntax-table-text-property
1563   "*Non-nil means: set up and use `syntax-table' text property generating TAGS."
1564   :type 'boolean
1565   :group 'cperl-speed)
1566
1567 (defcustom cperl-scan-files-regexp "\\.\\([pP][Llm]\\|xs\\)$"
1568   "*Regexp to match files to scan when generating TAGS."
1569   :type 'regexp
1570   :group 'cperl)
1571
1572 (defcustom cperl-noscan-files-regexp
1573   "/\\(\\.\\.?\\|SCCS\\|RCS\\|CVS\\|blib\\)$"
1574   "*Regexp to match files/dirs to skip when generating TAGS."
1575   :type 'regexp
1576   :group 'cperl)
1577
1578 (defcustom cperl-regexp-indent-step nil
1579   "*Indentation used when beautifying regexps.
1580 If nil, the value of `cperl-indent-level' will be used."
1581   :type '(choice integer (const nil))
1582   :group 'cperl-indentation-details)
1583
1584 (defcustom cperl-indent-left-aligned-comments t
1585   "*Non-nil means that the comment starting in leftmost column should indent."
1586   :type 'boolean
1587   :group 'cperl-indentation-details)
1588
1589 (defcustom cperl-under-as-char t
1590   "*Non-nil means that the _ (underline) should be treated as word char."
1591   :type 'boolean
1592   :group 'cperl)
1593
1594 (defcustom cperl-extra-perl-args ""
1595   "*Extra arguments to use when starting Perl.
1596 Currently used with `cperl-check-syntax' only."
1597   :type 'string
1598   :group 'cperl)
1599
1600 (defcustom cperl-message-electric-keyword t
1601   "*Non-nil means that the `cperl-electric-keyword' prints a help message."
1602   :type 'boolean
1603   :group 'cperl-help-system)
1604
1605 (defcustom cperl-indent-region-fix-constructs 1
1606   "*Amount of space to insert between `}' and `else' or `elsif'
1607 in `cperl-indent-region'.  Set to nil to leave as is.  Values other
1608 than 1 and nil will probably not work."
1609   :type '(choice (const nil) (const 1))
1610   :group 'cperl-indentation-details)
1611
1612 (defcustom cperl-break-one-line-blocks-when-indent t
1613   "*Non-nil means that one-line if/unless/while/until/for/foreach BLOCKs
1614 need to be reformatted into multiline ones when indenting a region."
1615   :type 'boolean
1616   :group 'cperl-indentation-details)
1617
1618 (defcustom cperl-fix-hanging-brace-when-indent t
1619   "*Non-nil means that BLOCK-end `}' may be put on a separate line
1620 when indenting a region.
1621 Braces followed by else/elsif/while/until are excepted."
1622   :type 'boolean
1623   :group 'cperl-indentation-details)
1624
1625 (defcustom cperl-merge-trailing-else t
1626   "*Non-nil means that BLOCK-end `}' followed by else/elsif/continue
1627 may be merged to be on the same line when indenting a region."
1628   :type 'boolean
1629   :group 'cperl-indentation-details)
1630
1631 (defcustom cperl-indent-parens-as-block nil
1632   "*Non-nil means that non-block ()-, {}- and []-groups are indented as blocks,
1633 but for trailing \",\" inside the group, which won't increase indentation.
1634 One should tune up `cperl-close-paren-offset' as well."
1635   :type 'boolean
1636   :group 'cperl-indentation-details)
1637
1638 (defcustom cperl-syntaxify-by-font-lock
1639   (and cperl-can-font-lock
1640        (boundp 'parse-sexp-lookup-properties))
1641   "*Non-nil means that CPerl uses `font-lock's routines for syntaxification."
1642   :type '(choice (const message) boolean)
1643   :group 'cperl-speed)
1644
1645 (defcustom cperl-syntaxify-unwind
1646   t
1647   "*Non-nil means that CPerl unwinds to a start of a long construction
1648 when syntaxifying a chunk of buffer."
1649   :type 'boolean
1650   :group 'cperl-speed)
1651
1652 (defcustom cperl-ps-print-face-properties
1653   '((font-lock-keyword-face             nil nil         bold shadow)
1654     (font-lock-variable-name-face       nil nil         bold)
1655     (font-lock-function-name-face       nil nil         bold italic box)
1656     (font-lock-constant-face            nil "LightGray" bold)
1657     (cperl-array-face                   nil "LightGray" bold underline)
1658     (cperl-hash-face                    nil "LightGray" bold italic underline)
1659     (font-lock-comment-face             nil "LightGray" italic)
1660     (font-lock-string-face              nil nil         italic underline)
1661     (cperl-nonoverridable-face          nil nil         italic underline)
1662     (font-lock-type-face                nil nil         underline)
1663     (underline                          nil "LightGray" strikeout))
1664   "List given as an argument to `ps-extend-face-list' in `cperl-ps-print'."
1665   :type '(repeat (cons symbol
1666                        (cons (choice (const nil) string)
1667                              (cons (choice (const nil) string)
1668                                    (repeat symbol)))))
1669   :group 'cperl-faces)
1670
1671 (if cperl-can-font-lock
1672     (progn
1673       (defvar cperl-dark-background
1674         (cperl-choose-color "navy" "os2blue" "darkgreen"))
1675       (defvar cperl-dark-foreground
1676         (cperl-choose-color "orchid1" "orange"))
1677
1678       (defface cperl-nonoverridable-face
1679         (` ((((class grayscale) (background light))
1680              (:background "Gray90" :italic t :underline t))
1681             (((class grayscale) (background dark))
1682              (:foreground "Gray80" :italic t :underline t :bold t))
1683             (((class color) (background light))
1684              (:foreground "chartreuse3"))
1685             (((class color) (background dark))
1686              (:foreground (, cperl-dark-foreground)))
1687             (t (:bold t :underline t))))
1688         "Font Lock mode face used to highlight array names."
1689         :group 'cperl-faces)
1690
1691       (defface cperl-array-face
1692         (` ((((class grayscale) (background light))
1693              (:background "Gray90" :bold t))
1694             (((class grayscale) (background dark))
1695              (:foreground "Gray80" :bold t))
1696             (((class color) (background light))
1697              (:foreground "Blue" :background "lightyellow2" :bold t))
1698             (((class color) (background dark))
1699              (:foreground "yellow" :background (, cperl-dark-background) :bold t))
1700             (t (:bold t))))
1701         "Font Lock mode face used to highlight array names."
1702         :group 'cperl-faces)
1703
1704       (defface cperl-hash-face
1705         (` ((((class grayscale) (background light))
1706              (:background "Gray90" :bold t :italic t))
1707             (((class grayscale) (background dark))
1708              (:foreground "Gray80" :bold t :italic t))
1709             (((class color) (background light))
1710              (:foreground "Red" :background "lightyellow2" :bold t :italic t))
1711             (((class color) (background dark))
1712              (:foreground "Red" :background (, cperl-dark-background) :bold t :italic t))
1713             (t (:bold t :italic t))))
1714         "Font Lock mode face used to highlight hash names."
1715         :group 'cperl-faces)))
1716
1717 \f
1718
1719 ;;; Short extra-docs.
1720
1721 (defvar cperl-tips 'please-ignore-this-line
1722   "Get maybe newer version of this package from
1723   ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
1724 and/or
1725   ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
1726 Subdirectory `cperl-mode' may contain yet newer development releases and/or
1727 patches to related files.
1728
1729 For best results apply to an older Emacs the patches from
1730   ftp://ftp.math.ohio-state.edu/pub/users/ilya/cperl-mode/patches
1731 \(this upgrades syntax-parsing abilities of RMS Emaxen v19.34 and 
1732 v20.2 up to the level of RMS Emacs v20.3 - a must for a good Perl
1733 mode.)  As of beginning of 2003, XEmacs may provide a similar ability.
1734
1735 Get support packages choose-color.el (or font-lock-extra.el before
1736 19.30), imenu-go.el from the same place.  \(Look for other files there
1737 too... ;-).  Get a patch for imenu.el in 19.29.  Note that for 19.30 and
1738 later you should use choose-color.el *instead* of font-lock-extra.el
1739 \(and you will not get smart highlighting in C :-().
1740
1741 Note that to enable Compile choices in the menu you need to install
1742 mode-compile.el.
1743
1744 If your Emacs does not default to `cperl-mode' on Perl files, and you
1745 want it to: put the following into your .emacs file:
1746
1747   (autoload 'perl-mode \"cperl-mode\" \"alternate mode for editing Perl programs\" t)
1748
1749 or
1750
1751   (defalias 'perl-mode 'cperl-mode)
1752
1753 Get perl5-info from
1754   $CPAN/doc/manual/info/perl-info.tar.gz
1755 older version was on
1756   http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz
1757
1758 If you use imenu-go, run imenu on perl5-info buffer (you can do it
1759 from Perl menu).  If many files are related, generate TAGS files from
1760 Tools/Tags submenu in Perl menu.
1761
1762 If some class structure is too complicated, use Tools/Hierarchy-view
1763 from Perl menu, or hierarchic view of imenu.  The second one uses the
1764 current buffer only, the first one requires generation of TAGS from
1765 Perl/Tools/Tags menu beforehand.
1766
1767 Run Perl/Tools/Insert-spaces-if-needed to fix your lazy typing.
1768
1769 Switch auto-help on/off with Perl/Tools/Auto-help.
1770
1771 Though with contemporary Emaxen CPerl mode should maintain the correct
1772 parsing of Perl even when editing, sometimes it may be lost.  Fix this by
1773
1774   M-x norm RET
1775
1776 or
1777
1778   \\[normal-mode]
1779
1780 In cases of more severe confusion sometimes it is helpful to do
1781
1782   M-x load-l RET cperl-mode RET
1783   M-x norm RET
1784
1785 or
1786
1787   \\[load-library] cperl-mode RET
1788   \\[normal-mode]
1789
1790 Before reporting (non-)problems look in the problem section of online
1791 micro-docs on what I know about CPerl problems.")
1792
1793 (defvar cperl-problems 'please-ignore-this-line
1794   "Description of problems in CPerl mode.
1795 Some faces will not be shown on some versions of Emacs unless you
1796 install choose-color.el, available from
1797    ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs/
1798
1799 `fill-paragraph' on a comment may leave the point behind the
1800 paragraph.  Parsing of lines with several <<EOF is not implemented
1801 yet.
1802
1803 Emacs had a _very_ restricted syntax parsing engine until RMS's Emacs
1804 20.1.  Most problems below are corrected starting from this version of
1805 Emacs, and all of them should be fixed in RMS's version 20.3.  (Or apply
1806 patches to Emacs 19.33/34 - see tips.)  XEmacs was very backward in
1807 this respect (until 2003).
1808
1809 Note that even with newer Emacsen in some very rare cases the details
1810 of interaction of `font-lock' and syntaxification may be not cleaned
1811 up yet.  You may get slightly different colors basing on the order of
1812 fontification and syntaxification.  Say, the initial faces is correct,
1813 but editing the buffer breaks this.
1814
1815 Even with older Emacsen CPerl mode tries to corrects some Emacs
1816 misunderstandings, however, for efficiency reasons the degree of
1817 correction is different for different operations.  The partially
1818 corrected problems are: POD sections, here-documents, regexps.  The
1819 operations are: highlighting, indentation, electric keywords, electric
1820 braces.
1821
1822 This may be confusing, since the regexp s#//#/#\; may be highlighted
1823 as a comment, but it will be recognized as a regexp by the indentation
1824 code.  Or the opposite case, when a POD section is highlighted, but
1825 may break the indentation of the following code (though indentation
1826 should work if the balance of delimiters is not broken by POD).
1827
1828 The main trick (to make $ a \"backslash\") makes constructions like
1829 ${aaa} look like unbalanced braces.  The only trick I can think of is
1830 to insert it as $ {aaa} (legal in perl5, not in perl4).
1831
1832 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
1833 as /($|\\s)/.  Note that such a transposition is not always possible.
1834
1835 The solution is to upgrade your Emacs or patch an older one.  Note
1836 that RMS's 20.2 has some bugs related to `syntax-table' text
1837 properties.  Patches are available on the main CPerl download site,
1838 and on CPAN.
1839
1840 If these bugs cannot be fixed on your machine (say, you have an inferior
1841 environment and cannot recompile), you may still disable all the fancy stuff
1842 via `cperl-use-syntax-table-text-property'.")
1843
1844 (defvar cperl-non-problems 'please-ignore-this-line
1845 "As you know from `problems' section, Perl syntax is too hard for CPerl on 
1846 older Emacsen.  Here is what you can do if you cannot upgrade, or if
1847 you want to switch off these capabilities on RMS Emacs 20.2 (+patches) or 20.3
1848 or better.  Please skip this docs if you run a capable Emacs already.
1849
1850 Most of the time, if you write your own code, you may find an equivalent
1851 \(and almost as readable) expression (what is discussed below is usually
1852 not relevant on newer Emacsen, since they can do it automatically).
1853
1854 Try to help CPerl: add comments with embedded quotes to fix CPerl
1855 misunderstandings about the end of quotation:
1856
1857 $a='500$';      # ';
1858
1859 You won't need it too often.  The reason: $ \"quotes\" the following
1860 character (this saves a life a lot of times in CPerl), thus due to
1861 Emacs parsing rules it does not consider tick (i.e., ' ) after a
1862 dollar as a closing one, but as a usual character.  This is usually
1863 correct, but not in the above context.
1864
1865 Even with older Emacsen the indentation code is pretty wise.  The only
1866 drawback is that it relied on Emacs parsing to find matching
1867 parentheses.  And Emacs *could not* match parentheses in Perl 100%
1868 correctly.  So
1869         1 if s#//#/#;
1870 would not break indentation, but
1871         1 if ( s#//#/# );
1872 would.  Upgrade.
1873
1874 By similar reasons
1875         s\"abc\"def\";
1876 could confuse CPerl a lot.
1877
1878 If you still get wrong indentation in situation that you think the
1879 code should be able to parse, try:
1880
1881 a) Check what Emacs thinks about balance of your parentheses.
1882 b) Supply the code to me (IZ).
1883
1884 Pods were treated _very_ rudimentally.  Here-documents were not
1885 treated at all (except highlighting and inhibiting indentation).  Upgrade.
1886
1887 To speed up coloring the following compromises exist:
1888    a) sub in $mypackage::sub may be highlighted.
1889    b) -z in [a-z] may be highlighted.
1890    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
1891
1892
1893 Imenu in 19.31 is broken.  Set `imenu-use-keymap-menu' to t, and remove
1894 `car' before `imenu-choose-buffer-index' in `imenu'.
1895 `imenu-add-to-menubar' in 20.2 is broken.  
1896 A lot of things on XEmacs may be broken too, judging by bug reports I
1897 receive.  Note that some releases of XEmacs are better than the others
1898 as far as bugs reports I see are concerned.")
1899
1900 (defvar cperl-praise 'please-ignore-this-line
1901   "Advantages of CPerl mode.
1902
1903 0) It uses the newest `syntax-table' property ;-);
1904
1905 1) It does 99% of Perl syntax correct (as opposed to 80-90% in Perl
1906 mode - but the latter number may have improved too in last years) even
1907 with old Emaxen which do not support `syntax-table' property.
1908
1909 When using `syntax-table' property for syntax assist hints, it should
1910 handle 99.995% of lines correct - or somesuch.  It automatically
1911 updates syntax assist hints when you edit your script.
1912
1913 2) It is generally believed to be \"the most user-friendly Emacs
1914 package\" whatever it may mean (I doubt that the people who say similar
1915 things tried _all_ the rest of Emacs ;-), but this was not a lonely
1916 voice);
1917
1918 3) Everything is customizable, one-by-one or in a big sweep;
1919
1920 4) It has many easily-accessable \"tools\":
1921         a) Can run program, check syntax, start debugger;
1922         b) Can lineup vertically \"middles\" of rows, like `=' in
1923                 a  = b;
1924                 cc = d;
1925         c) Can insert spaces where this impoves readability (in one
1926                 interactive sweep over the buffer);
1927         d) Has support for imenu, including:
1928                 1) Separate unordered list of \"interesting places\";
1929                 2) Separate TOC of POD sections;
1930                 3) Separate list of packages;
1931                 4) Hierarchical view of methods in (sub)packages;
1932                 5) and functions (by the full name - with package);
1933         e) Has an interface to INFO docs for Perl; The interface is
1934                 very flexible, including shrink-wrapping of
1935                 documentation buffer/frame;
1936         f) Has a builtin list of one-line explanations for perl constructs.
1937         g) Can show these explanations if you stay long enough at the
1938                 corresponding place (or on demand);
1939         h) Has an enhanced fontification (using 3 or 4 additional faces
1940                 comparing to font-lock - basically, different
1941                 namespaces in Perl have different colors);
1942         i) Can construct TAGS basing on its knowledge of Perl syntax,
1943                 the standard menu has 6 different way to generate
1944                 TAGS (if \"by directory\", .xs files - with C-language
1945                 bindings - are included in the scan);
1946         j) Can build a hierarchical view of classes (via imenu) basing
1947                 on generated TAGS file;
1948         k) Has electric parentheses, electric newlines, uses Abbrev
1949                 for electric logical constructs
1950                         while () {}
1951                 with different styles of expansion (context sensitive
1952                 to be not so bothering).  Electric parentheses behave
1953                 \"as they should\" in a presence of a visible region.
1954         l) Changes msb.el \"on the fly\" to insert a group \"Perl files\";
1955         m) Can convert from
1956                 if (A) { B }
1957            to
1958                 B if A;
1959
1960         n) Highlights (by user-choice) either 3-delimiters constructs
1961            (such as tr/a/b/), or regular expressions and `y/tr';
1962         o) Highlights trailing whitespace;
1963         p) Is able to manipulate Perl Regular Expressions to ease
1964            conversion to a more readable form.
1965
1966 5) The indentation engine was very smart, but most of tricks may be
1967 not needed anymore with the support for `syntax-table' property.  Has
1968 progress indicator for indentation (with `imenu' loaded).
1969
1970 6) Indent-region improves inline-comments as well; also corrects
1971 whitespace *inside* the conditional/loop constructs.
1972
1973 7) Fill-paragraph correctly handles multi-line comments;
1974
1975 8) Can switch to different indentation styles by one command, and restore
1976 the settings present before the switch.
1977
1978 9) When doing indentation of control constructs, may correct
1979 line-breaks/spacing between elements of the construct.
1980
1981 10) Uses a linear-time algorith for indentation of regions (on Emaxen with
1982 capable syntax engines).")
1983
1984 (defvar cperl-speed 'please-ignore-this-line
1985   "This is an incomplete compendium of what is available in other parts
1986 of CPerl documentation.  (Please inform me if I skept anything.)
1987
1988 There is a perception that CPerl is slower than alternatives.  This part
1989 of documentation is designed to overcome this misconception.
1990
1991 *By default* CPerl tries to enable the most comfortable settings.
1992 From most points of view, correctly working package is infinitely more
1993 comfortable than a non-correctly working one, thus by default CPerl
1994 prefers correctness over speed.  Below is the guide how to change
1995 settings if your preferences are different.
1996
1997 A)  Speed of loading the file.  When loading file, CPerl may perform a
1998 scan which indicates places which cannot be parsed by primitive Emacs
1999 syntax-parsing routines, and marks them up so that either
2000
2001     A1) CPerl may work around these deficiencies (for big chunks, mostly
2002         PODs and HERE-documents), or
2003     A2) On capable Emaxen CPerl will use improved syntax-handlings
2004         which reads mark-up hints directly.
2005
2006     The scan in case A2 is much more comprehensive, thus may be slower.
2007
2008     User can disable syntax-engine-helping scan of A2 by setting
2009        `cperl-use-syntax-table-text-property'
2010     variable to nil (if it is set to t).
2011
2012     One can disable the scan altogether (both A1 and A2) by setting
2013        `cperl-pod-here-scan'
2014     to nil.
2015
2016 B) Speed of editing operations.
2017
2018     One can add a (minor) speedup to editing operations by setting
2019        `cperl-use-syntax-table-text-property'
2020     variable to nil (if it is set to t).  This will disable
2021     syntax-engine-helping scan, thus will make many more Perl
2022     constructs be wrongly recognized by CPerl, thus may lead to
2023     wrongly matched parentheses, wrong indentation, etc.
2024
2025     One can unset `cperl-syntaxify-unwind'.  This might speed up editing
2026     of, say, long POD sections.")
2027
2028 (defvar cperl-tips-faces 'please-ignore-this-line
2029   "CPerl mode uses following faces for highlighting:
2030
2031   `cperl-array-face'            Array names
2032   `cperl-hash-face'             Hash names
2033   `font-lock-comment-face'      Comments, PODs and whatever is considered
2034                                 syntaxically to be not code
2035   `font-lock-constant-face'     HERE-doc delimiters, labels, delimiters of
2036                                 2-arg operators s/y/tr/ or of RExen,
2037   `font-lock-function-name-face' Special-cased m// and s//foo/, _ as
2038                                 a target of a file tests, file tests,
2039                                 subroutine names at the moment of definition
2040                                 (except those conflicting with Perl operators),
2041                                 package names (when recognized), format names
2042   `font-lock-keyword-face'      Control flow switch constructs, declarators
2043   `cperl-nonoverridable-face'   Non-overridable keywords, modifiers of RExen
2044   `font-lock-string-face'       Strings, qw() constructs, RExen, POD sections,
2045                                 literal parts and the terminator of formats
2046                                 and whatever is syntaxically considered
2047                                 as string literals
2048   `font-lock-type-face'         Overridable keywords
2049   `font-lock-variable-name-face' Variable declarations, indirect array and
2050                                 hash names, POD headers/item names
2051   `cperl-invalid-face'          Trailing whitespace
2052
2053 Note that in several situations the highlighting tries to inform about
2054 possible confusion, such as different colors for function names in
2055 declarations depending on what they (do not) override, or special cases
2056 m// and s/// which do not do what one would expect them to do.
2057
2058 Help with best setup of these faces for printout requested (for each of
2059 the faces: please specify bold, italic, underline, shadow and box.)
2060
2061 \(Not finished.)")
2062
2063 \f
2064
2065 ;;; Portability stuff:
2066
2067 (defmacro cperl-define-key (emacs-key definition &optional xemacs-key)
2068   (` (define-key cperl-mode-map
2069        (, (if xemacs-key
2070               (` (if cperl-xemacs-p (, xemacs-key) (, emacs-key)))
2071             emacs-key))
2072        (, definition))))
2073
2074 (defvar cperl-del-back-ch
2075   (car (append (where-is-internal 'delete-backward-char)
2076                (where-is-internal 'backward-delete-char-untabify)))
2077   "Character generated by key bound to `delete-backward-char'.")
2078
2079 (and (vectorp cperl-del-back-ch) (= (length cperl-del-back-ch) 1)
2080      (setq cperl-del-back-ch (aref cperl-del-back-ch 0)))
2081
2082 (defun cperl-mark-active () (mark))     ; Avoid undefined warning
2083 (if cperl-xemacs-p
2084     (progn
2085       ;; "Active regions" are on: use region only if active
2086       ;; "Active regions" are off: use region unconditionally
2087       (defun cperl-use-region-p ()
2088         (if zmacs-regions (mark) t)))
2089   (defun cperl-use-region-p ()
2090     (if transient-mark-mode mark-active t))
2091   (defun cperl-mark-active () mark-active))
2092
2093 (defsubst cperl-enable-font-lock ()
2094   cperl-can-font-lock)
2095
2096 (defun cperl-putback-char (c)           ; Emacs 19
2097   (set 'unread-command-events (list c))) ; Avoid undefined warning
2098
2099 (if (boundp 'unread-command-events)
2100     (if cperl-xemacs-p
2101         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
2102           (setq unread-command-events (list (eval '(character-to-event c))))))
2103   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
2104     (set 'unread-command-event (eval '(character-to-event c))))) ; Avoid warnings
2105
2106 (or (fboundp 'uncomment-region)
2107     (defun uncomment-region (beg end)
2108       (interactive "r")
2109       (comment-region beg end -1)))
2110
2111 (defvar cperl-do-not-fontify
2112   (if (string< emacs-version "19.30")
2113       'fontified
2114     'lazy-lock)
2115   "Text property which inhibits refontification.")
2116
2117 (defsubst cperl-put-do-not-fontify (from to &optional post)
2118   ;; If POST, do not do it with postponed fontification
2119   (if (and post cperl-syntaxify-by-font-lock)
2120       nil
2121     (put-text-property (max (point-min) (1- from))
2122                        to cperl-do-not-fontify t)))
2123
2124 (defcustom cperl-mode-hook nil
2125   "Hook run by CPerl mode."
2126   :type 'hook
2127   :group 'cperl)
2128
2129 (defvar cperl-syntax-state nil)
2130 (defvar cperl-syntax-done-to nil)
2131 (defvar cperl-emacs-can-parse (> (length (save-excursion
2132                                            (parse-partial-sexp (point) (point)))) 9))
2133 \f
2134 ;; Make customization possible "in reverse"
2135 (defsubst cperl-val (symbol &optional default hairy)
2136   (cond
2137    ((eq (symbol-value symbol) 'null) default)
2138    (cperl-hairy (or hairy t))
2139    (t (symbol-value symbol))))
2140 \f
2141 ;;; Probably it is too late to set these guys already, but it can help later:
2142
2143 (and cperl-clobber-mode-lists
2144      (setq auto-mode-alist
2145       (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
2146      (and (boundp 'interpreter-mode-alist)
2147           (setq interpreter-mode-alist (append interpreter-mode-alist
2148                                                '(("miniperl" . perl-mode))))))
2149 (if (fboundp 'eval-when-compile)
2150     (eval-when-compile
2151       (mapcar (lambda (p)
2152                 (condition-case nil
2153                     (require p)
2154                   (error nil)))
2155               '(imenu easymenu etags timer man info))
2156       (if (fboundp 'ps-extend-face-list)
2157           (defmacro cperl-ps-extend-face-list (arg)
2158             (` (ps-extend-face-list (, arg))))
2159         (defmacro cperl-ps-extend-face-list (arg)
2160           (` (error "This version of Emacs has no `ps-extend-face-list'"))))
2161       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
2162       ;; macros instead of defsubsts don't work on Emacs, so we do the
2163       ;; expansion manually.  Any other suggestions?
2164       (if cperl-can-font-lock
2165           (require 'font-lock))
2166       (require 'cl)))
2167
2168 (defvar cperl-mode-abbrev-table nil
2169   "Abbrev table in use in CPerl mode buffers.")
2170
2171 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
2172
2173 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
2174
2175 (if cperl-mode-map nil
2176   (setq cperl-mode-map (make-sparse-keymap))
2177   (cperl-define-key "{" 'cperl-electric-lbrace)
2178   (cperl-define-key "[" 'cperl-electric-paren)
2179   (cperl-define-key "(" 'cperl-electric-paren)
2180   (cperl-define-key "<" 'cperl-electric-paren)
2181   (cperl-define-key "}" 'cperl-electric-brace)
2182   (cperl-define-key "]" 'cperl-electric-rparen)
2183   (cperl-define-key ")" 'cperl-electric-rparen)
2184   (cperl-define-key ";" 'cperl-electric-semi)
2185   (cperl-define-key ":" 'cperl-electric-terminator)
2186   (cperl-define-key "\C-j" 'newline-and-indent)
2187   (cperl-define-key "\C-c\C-j" 'cperl-linefeed)
2188   (cperl-define-key "\C-c\C-t" 'cperl-invert-if-unless)
2189   (cperl-define-key "\C-c\C-a" 'cperl-toggle-auto-newline)
2190   (cperl-define-key "\C-c\C-k" 'cperl-toggle-abbrev)
2191   (cperl-define-key "\C-c\C-w" 'cperl-toggle-construct-fix)
2192   (cperl-define-key "\C-c\C-f" 'auto-fill-mode)
2193   (cperl-define-key "\C-c\C-e" 'cperl-toggle-electric)
2194   (cperl-define-key "\C-c\C-ha" 'cperl-toggle-autohelp)
2195   (cperl-define-key "\e\C-q" 'cperl-indent-exp) ; Usually not bound
2196   (cperl-define-key [?\C-\M-\|] 'cperl-lineup
2197                     [(control meta |)])
2198   ;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
2199   ;;(cperl-define-key "\e;" 'cperl-indent-for-comment)
2200   (cperl-define-key "\177" 'cperl-electric-backspace)
2201   (cperl-define-key "\t" 'cperl-indent-command)
2202   ;; don't clobber the backspace binding:
2203   (cperl-define-key "\C-c\C-hF" 'cperl-info-on-command
2204                     [(control c) (control h) F])
2205   (if (cperl-val 'cperl-clobber-lisp-bindings)
2206       (progn
2207         (cperl-define-key "\C-hf"
2208                           ;;(concat (char-to-string help-char) "f") ; does not work
2209                           'cperl-info-on-command
2210                           [(control h) f])
2211         (cperl-define-key "\C-hv"
2212                           ;;(concat (char-to-string help-char) "v") ; does not work
2213                           'cperl-get-help
2214                           [(control h) v])
2215         (cperl-define-key "\C-c\C-hf"
2216                           ;;(concat (char-to-string help-char) "f") ; does not work
2217                           (key-binding "\C-hf")
2218                           [(control c) (control h) f])
2219         (cperl-define-key "\C-c\C-hv"
2220                           ;;(concat (char-to-string help-char) "v") ; does not work
2221                           (key-binding "\C-hv")
2222                           [(control c) (control h) v]))
2223     (cperl-define-key "\C-c\C-hf" 'cperl-info-on-current-command
2224                       [(control c) (control h) f])
2225     (cperl-define-key "\C-c\C-hv"
2226                       ;;(concat (char-to-string help-char) "v") ; does not work
2227                       'cperl-get-help
2228                       [(control c) (control h) v]))
2229   (if (and cperl-xemacs-p
2230            (<= emacs-minor-version 11) (<= emacs-major-version 19))
2231       (progn
2232         ;; substitute-key-definition is usefulness-deenhanced...
2233         (cperl-define-key "\M-q" 'cperl-fill-paragraph)
2234         (cperl-define-key "\e;" 'cperl-indent-for-comment)
2235         (cperl-define-key "\e\C-\\" 'cperl-indent-region))
2236     (substitute-key-definition
2237      'indent-sexp 'cperl-indent-exp
2238      cperl-mode-map global-map)
2239     (substitute-key-definition
2240      'fill-paragraph 'cperl-fill-paragraph
2241      cperl-mode-map global-map)
2242     (substitute-key-definition
2243      'indent-region 'cperl-indent-region
2244      cperl-mode-map global-map)
2245     (substitute-key-definition
2246      'indent-for-comment 'cperl-indent-for-comment
2247      cperl-mode-map global-map)))
2248
2249 (defvar cperl-menu)
2250 (defvar cperl-lazy-installed)
2251 (defvar cperl-old-style nil)
2252 (condition-case nil
2253     (progn
2254       (require 'easymenu)
2255       (easy-menu-define
2256        cperl-menu cperl-mode-map "Menu for CPerl mode"
2257        '("Perl"
2258          ["Beginning of function" beginning-of-defun t]
2259          ["End of function" end-of-defun t]
2260          ["Mark function" mark-defun t]
2261          ["Indent expression" cperl-indent-exp t]
2262          ["Fill paragraph/comment" cperl-fill-paragraph t]
2263          "----"
2264          ["Line up a construction" cperl-lineup (cperl-use-region-p)]
2265          ["Invert if/unless/while etc" cperl-invert-if-unless t]
2266          ("Regexp"
2267           ["Beautify" cperl-beautify-regexp
2268            cperl-use-syntax-table-text-property]
2269           ["Beautify one level deep" (cperl-beautify-regexp 1)
2270            cperl-use-syntax-table-text-property]
2271           ["Beautify a group" cperl-beautify-level
2272            cperl-use-syntax-table-text-property]
2273           ["Beautify a group one level deep" (cperl-beautify-level 1)
2274            cperl-use-syntax-table-text-property]
2275           ["Contract a group" cperl-contract-level
2276            cperl-use-syntax-table-text-property]
2277           ["Contract groups" cperl-contract-levels
2278            cperl-use-syntax-table-text-property])
2279          ["Refresh \"hard\" constructions" cperl-find-pods-heres t]
2280          "----"
2281          ["Indent region" cperl-indent-region (cperl-use-region-p)]
2282          ["Comment region" cperl-comment-region (cperl-use-region-p)]
2283          ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
2284          "----"
2285          ["Run" mode-compile (fboundp 'mode-compile)]
2286          ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
2287                                         (get-buffer "*compilation*"))]
2288          ["Next error" next-error (get-buffer "*compilation*")]
2289          ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
2290          "----"
2291          ["Debugger" cperl-db t]
2292          "----"
2293          ("Tools"
2294           ["Imenu" imenu (fboundp 'imenu)]
2295           ["Insert spaces if needed" cperl-find-bad-style t]
2296           ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
2297           ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
2298           ["CPerl pretty print (exprmntl)" cperl-ps-print 
2299            (fboundp 'ps-extend-face-list)]
2300           ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
2301           ("Tags"
2302 ;;;          ["Create tags for current file" cperl-etags t]
2303 ;;;          ["Add tags for current file" (cperl-etags t) t]
2304 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
2305 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
2306 ;;;          ["Create tags for Perl files in (sub)directories"
2307 ;;;           (cperl-etags nil 'recursive) t]
2308 ;;;          ["Add tags for Perl files in (sub)directories"
2309 ;;;           (cperl-etags t 'recursive) t])
2310 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
2311            ["Create tags for current file" (cperl-write-tags nil t) t]
2312            ["Add tags for current file" (cperl-write-tags) t]
2313            ["Create tags for Perl files in directory"
2314             (cperl-write-tags nil t nil t) t]
2315            ["Add tags for Perl files in directory"
2316             (cperl-write-tags nil nil nil t) t]
2317            ["Create tags for Perl files in (sub)directories"
2318             (cperl-write-tags nil t t t) t]
2319            ["Add tags for Perl files in (sub)directories"
2320             (cperl-write-tags nil nil t t) t]))
2321          ("Perl docs"
2322           ["Define word at point" imenu-go-find-at-position 
2323            (fboundp 'imenu-go-find-at-position)]
2324           ["Help on function" cperl-info-on-command t]
2325           ["Help on function at point" cperl-info-on-current-command t]
2326           ["Help on symbol at point" cperl-get-help t]
2327           ["Perldoc" cperl-perldoc t]
2328           ["Perldoc on word at point" cperl-perldoc-at-point t]
2329           ["View manpage of POD in this file" cperl-build-manpage t]
2330           ["Auto-help on" cperl-lazy-install 
2331            (and (fboundp 'run-with-idle-timer)
2332                 (not cperl-lazy-installed))]
2333           ["Auto-help off" cperl-lazy-unstall
2334            (and (fboundp 'run-with-idle-timer)
2335                 cperl-lazy-installed)])
2336          ("Toggle..."
2337           ["Auto newline" cperl-toggle-auto-newline t]
2338           ["Electric parens" cperl-toggle-electric t]
2339           ["Electric keywords" cperl-toggle-abbrev t]
2340           ["Fix whitespace on indent" cperl-toggle-construct-fix t]
2341           ["Auto-help on Perl constructs" cperl-toggle-autohelp t]
2342           ["Auto fill" auto-fill-mode t]) 
2343          ("Indent styles..."
2344           ["CPerl" (cperl-set-style "CPerl") t]
2345           ["PerlStyle" (cperl-set-style "PerlStyle") t]
2346           ["GNU" (cperl-set-style "GNU") t]
2347           ["C++" (cperl-set-style "C++") t]
2348           ["FSF" (cperl-set-style "FSF") t]
2349           ["BSD" (cperl-set-style "BSD") t]
2350           ["Whitesmith" (cperl-set-style "Whitesmith") t]
2351           ["Current" (cperl-set-style "Current") t]
2352           ["Memorized" (cperl-set-style-back) cperl-old-style])
2353          ("Micro-docs"
2354           ["Tips" (describe-variable 'cperl-tips) t]
2355           ["Problems" (describe-variable 'cperl-problems) t]
2356           ["Non-problems" (describe-variable 'cperl-non-problems) t]
2357           ["Speed" (describe-variable 'cperl-speed) t]
2358           ["Praise" (describe-variable 'cperl-praise) t]
2359           ["Faces" (describe-variable 'cperl-tips-faces) t]
2360           ["CPerl mode" (describe-function 'cperl-mode) t]
2361           ["CPerl version" 
2362            (message "The version of master-file for this CPerl is %s" 
2363                     cperl-version) t]))))
2364   (error nil))
2365
2366 (autoload 'c-macro-expand "cmacexp"
2367   "Display the result of expanding all C macros occurring in the region.
2368 The expansion is entirely correct because it uses the C preprocessor."
2369   t)
2370
2371 (defvar cperl-imenu--function-name-regexp-perl
2372   (concat
2373    "^\\("
2374         "[ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*\\(([^()]*)[ \t]*\\)?"
2375    "\\|"
2376         "=head\\([12]\\)[ \t]+\\([^\n]+\\)$"
2377    "\\)"))
2378
2379 (defvar cperl-outline-regexp
2380   (concat cperl-imenu--function-name-regexp-perl "\\|" "\\`"))
2381
2382 (defvar cperl-mode-syntax-table nil
2383   "Syntax table in use in CPerl mode buffers.")
2384
2385 (defvar cperl-string-syntax-table nil
2386   "Syntax table in use in CPerl mode string-like chunks.")
2387
2388 (if cperl-mode-syntax-table
2389     ()
2390   (setq cperl-mode-syntax-table (make-syntax-table))
2391   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
2392   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
2393   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
2394   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
2395   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
2396   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
2397   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
2398   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
2399   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
2400   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
2401   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
2402   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
2403   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
2404   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
2405   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
2406   (if cperl-under-as-char
2407       (modify-syntax-entry ?_ "w" cperl-mode-syntax-table))
2408   (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
2409   (modify-syntax-entry ?| "." cperl-mode-syntax-table)
2410   (setq cperl-string-syntax-table (copy-syntax-table cperl-mode-syntax-table))
2411   (modify-syntax-entry ?$ "." cperl-string-syntax-table)
2412   (modify-syntax-entry ?# "." cperl-string-syntax-table)) ; (?# comment )
2413
2414
2415 \f
2416 ;; provide an alias for working with emacs 19.  the perl-mode that comes
2417 ;; with it is really bad, and this lets us seamlessly replace it.
2418 ;;;###autoload
2419 (fset 'perl-mode 'cperl-mode)
2420 (defvar cperl-faces-init nil)
2421 ;; Fix for msb.el
2422 (defvar cperl-msb-fixed nil)
2423 (defvar font-lock-syntactic-keywords)
2424 (defvar perl-font-lock-keywords)
2425 (defvar perl-font-lock-keywords-1)
2426 (defvar perl-font-lock-keywords-2)
2427 (defvar outline-level)
2428 (if (fboundp 'defvaralias)
2429     (let ((f 'defvaralias)) ; Some functions deduce stuff from the mode name...
2430       (funcall f 'cperl-font-lock-keywords   'perl-font-lock-keywords)
2431       (funcall f 'cperl-font-lock-keywords-1 'perl-font-lock-keywords-1)
2432       (funcall f 'cperl-font-lock-keywords-2 'perl-font-lock-keywords-2)))
2433
2434 (defvar cperl-use-major-mode 'perl-mode)
2435
2436 ;;;###autoload
2437 (defun cperl-mode ()
2438   "Major mode for editing Perl code.
2439 Expression and list commands understand all C brackets.
2440 Tab indents for Perl code.
2441 Paragraphs are separated by blank lines only.
2442 Delete converts tabs to spaces as it moves back.
2443
2444 Various characters in Perl almost always come in pairs: {}, (), [],
2445 sometimes <>.  When the user types the first, she gets the second as
2446 well, with optional special formatting done on {}.  (Disabled by
2447 default.)  You can always quote (with \\[quoted-insert]) the left
2448 \"paren\" to avoid the expansion.  The processing of < is special,
2449 since most the time you mean \"less\".  CPerl mode tries to guess
2450 whether you want to type pair <>, and inserts is if it
2451 appropriate.  You can set `cperl-electric-parens-string' to the string that
2452 contains the parenths from the above list you want to be electrical.
2453 Electricity of parenths is controlled by `cperl-electric-parens'.
2454 You may also set `cperl-electric-parens-mark' to have electric parens
2455 look for active mark and \"embrace\" a region if possible.'
2456
2457 CPerl mode provides expansion of the Perl control constructs:
2458
2459    if, else, elsif, unless, while, until, continue, do,
2460    for, foreach, formy and foreachmy.
2461
2462 and POD directives (Disabled by default, see `cperl-electric-keywords'.)
2463
2464 The user types the keyword immediately followed by a space, which
2465 causes the construct to be expanded, and the point is positioned where
2466 she is most likely to want to be.  eg. when the user types a space
2467 following \"if\" the following appears in the buffer: if () { or if ()
2468 } { } and the cursor is between the parentheses.  The user can then
2469 type some boolean expression within the parens.  Having done that,
2470 typing \\[cperl-linefeed] places you - appropriately indented - on a
2471 new line between the braces (if you typed \\[cperl-linefeed] in a POD
2472 directive line, then appropriate number of new lines is inserted).
2473
2474 If CPerl decides that you want to insert \"English\" style construct like
2475
2476             bite if angry;
2477
2478 it will not do any expansion.  See also help on variable
2479 `cperl-extra-newline-before-brace'.  (Note that one can switch the
2480 help message on expansion by setting `cperl-message-electric-keyword'
2481 to nil.)
2482
2483 \\[cperl-linefeed] is a convenience replacement for typing carriage
2484 return.  It places you in the next line with proper indentation, or if
2485 you type it inside the inline block of control construct, like
2486
2487             foreach (@lines) {print; print}
2488
2489 and you are on a boundary of a statement inside braces, it will
2490 transform the construct into a multiline and will place you into an
2491 appropriately indented blank line.  If you need a usual
2492 `newline-and-indent' behaviour, it is on \\[newline-and-indent],
2493 see documentation on `cperl-electric-linefeed'.
2494
2495 Use \\[cperl-invert-if-unless] to change a construction of the form
2496
2497             if (A) { B }
2498
2499 into
2500
2501             B if A;
2502
2503 \\{cperl-mode-map}
2504
2505 Setting the variable `cperl-font-lock' to t switches on font-lock-mode
2506 \(even with older Emacsen), `cperl-electric-lbrace-space' to t switches
2507 on electric space between $ and {, `cperl-electric-parens-string' is
2508 the string that contains parentheses that should be electric in CPerl
2509 \(see also `cperl-electric-parens-mark' and `cperl-electric-parens'),
2510 setting `cperl-electric-keywords' enables electric expansion of
2511 control structures in CPerl.  `cperl-electric-linefeed' governs which
2512 one of two linefeed behavior is preferable.  You can enable all these
2513 options simultaneously (recommended mode of use) by setting
2514 `cperl-hairy' to t.  In this case you can switch separate options off
2515 by setting them to `null'.  Note that one may undo the extra
2516 whitespace inserted by semis and braces in `auto-newline'-mode by
2517 consequent \\[cperl-electric-backspace].
2518
2519 If your site has perl5 documentation in info format, you can use commands
2520 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
2521 These keys run commands `cperl-info-on-current-command' and
2522 `cperl-info-on-command', which one is which is controlled by variable
2523 `cperl-info-on-command-no-prompt' and `cperl-clobber-lisp-bindings'
2524 \(in turn affected by `cperl-hairy').
2525
2526 Even if you have no info-format documentation, short one-liner-style
2527 help is available on \\[cperl-get-help], and one can run perldoc or
2528 man via menu.
2529
2530 It is possible to show this help automatically after some idle time.
2531 This is regulated by variable `cperl-lazy-help-time'.  Default with
2532 `cperl-hairy' (if the value of `cperl-lazy-help-time' is nil) is 5
2533 secs idle time .  It is also possible to switch this on/off from the
2534 menu, or via \\[cperl-toggle-autohelp].  Requires `run-with-idle-timer'.
2535
2536 Use \\[cperl-lineup] to vertically lineup some construction - put the
2537 beginning of the region at the start of construction, and make region
2538 span the needed amount of lines.
2539
2540 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
2541 `cperl-pod-face', `cperl-pod-head-face' control processing of POD and
2542 here-docs sections.  With capable Emaxen results of scan are used
2543 for indentation too, otherwise they are used for highlighting only.
2544
2545 Variables controlling indentation style:
2546  `cperl-tab-always-indent'
2547     Non-nil means TAB in CPerl mode should always reindent the current line,
2548     regardless of where in the line point is when the TAB command is used.
2549  `cperl-indent-left-aligned-comments'
2550     Non-nil means that the comment starting in leftmost column should indent.
2551  `cperl-auto-newline'
2552     Non-nil means automatically newline before and after braces,
2553     and after colons and semicolons, inserted in Perl code.  The following
2554     \\[cperl-electric-backspace] will remove the inserted whitespace.
2555     Insertion after colons requires both this variable and
2556     `cperl-auto-newline-after-colon' set.
2557  `cperl-auto-newline-after-colon'
2558     Non-nil means automatically newline even after colons.
2559     Subject to `cperl-auto-newline' setting.
2560  `cperl-indent-level'
2561     Indentation of Perl statements within surrounding block.
2562     The surrounding block's indentation is the indentation
2563     of the line on which the open-brace appears.
2564  `cperl-continued-statement-offset'
2565     Extra indentation given to a substatement, such as the
2566     then-clause of an if, or body of a while, or just a statement continuation.
2567  `cperl-continued-brace-offset'
2568     Extra indentation given to a brace that starts a substatement.
2569     This is in addition to `cperl-continued-statement-offset'.
2570  `cperl-brace-offset'
2571     Extra indentation for line if it starts with an open brace.
2572  `cperl-brace-imaginary-offset'
2573     An open brace following other text is treated as if it the line started
2574     this far to the right of the actual line indentation.
2575  `cperl-label-offset'
2576     Extra indentation for line that is a label.
2577  `cperl-min-label-indent'
2578     Minimal indentation for line that is a label.
2579
2580 Settings for K&R and BSD indentation styles are
2581   `cperl-indent-level'                5    8
2582   `cperl-continued-statement-offset'  5    8
2583   `cperl-brace-offset'               -5   -8
2584   `cperl-label-offset'               -5   -8
2585
2586 CPerl knows several indentation styles, and may bulk set the
2587 corresponding variables.  Use \\[cperl-set-style] to do this.  Use
2588 \\[cperl-set-style-back] to restore the memorized preexisting values
2589 \(both available from menu).
2590
2591 If `cperl-indent-level' is 0, the statement after opening brace in
2592 column 0 is indented on
2593 `cperl-brace-offset'+`cperl-continued-statement-offset'.
2594
2595 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
2596 with no args.
2597
2598 DO NOT FORGET to read micro-docs (available from `Perl' menu)
2599 or as help on variables `cperl-tips', `cperl-problems',
2600 `cperl-non-problems', `cperl-praise', `cperl-speed'."
2601   (interactive)
2602   (kill-all-local-variables)
2603   (use-local-map cperl-mode-map)
2604   (if (cperl-val 'cperl-electric-linefeed)
2605       (progn
2606         (local-set-key "\C-J" 'cperl-linefeed)
2607         (local-set-key "\C-C\C-J" 'newline-and-indent)))
2608   (if (and
2609        (cperl-val 'cperl-clobber-lisp-bindings)
2610        (cperl-val 'cperl-info-on-command-no-prompt))
2611       (progn
2612         ;; don't clobber the backspace binding:
2613         (cperl-define-key "\C-hf" 'cperl-info-on-current-command [(control h) f])
2614         (cperl-define-key "\C-c\C-hf" 'cperl-info-on-command
2615                           [(control c) (control h) f])))
2616   (setq major-mode cperl-use-major-mode)
2617   (setq mode-name "CPerl")
2618   (if (not cperl-mode-abbrev-table)
2619       (let ((prev-a-c abbrevs-changed))
2620         (define-abbrev-table 'cperl-mode-abbrev-table '(
2621                 ("if" "if" cperl-electric-keyword 0)
2622                 ("elsif" "elsif" cperl-electric-keyword 0)
2623                 ("while" "while" cperl-electric-keyword 0)
2624                 ("until" "until" cperl-electric-keyword 0)
2625                 ("unless" "unless" cperl-electric-keyword 0)
2626                 ("else" "else" cperl-electric-else 0)
2627                 ("continue" "continue" cperl-electric-else 0)
2628                 ("for" "for" cperl-electric-keyword 0)
2629                 ("foreach" "foreach" cperl-electric-keyword 0)
2630                 ("formy" "formy" cperl-electric-keyword 0)
2631                 ("foreachmy" "foreachmy" cperl-electric-keyword 0)
2632                 ("do" "do" cperl-electric-keyword 0)
2633                 ("=pod" "=pod" cperl-electric-pod 0)
2634                 ("=over" "=over" cperl-electric-pod 0)
2635                 ("=head1" "=head1" cperl-electric-pod 0)
2636                 ("=head2" "=head2" cperl-electric-pod 0)
2637                 ("pod" "pod" cperl-electric-pod 0)
2638                 ("over" "over" cperl-electric-pod 0)
2639                 ("head1" "head1" cperl-electric-pod 0)
2640                 ("head2" "head2" cperl-electric-pod 0)))
2641         (setq abbrevs-changed prev-a-c)))
2642   (setq local-abbrev-table cperl-mode-abbrev-table)
2643   (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
2644   (set-syntax-table cperl-mode-syntax-table)
2645   (make-local-variable 'outline-regexp)
2646   ;; (setq outline-regexp imenu-example--function-name-regexp-perl)
2647   (setq outline-regexp cperl-outline-regexp)
2648   (make-local-variable 'outline-level)
2649   (setq outline-level 'cperl-outline-level)
2650   (make-local-variable 'paragraph-start)
2651   (setq paragraph-start (concat "^$\\|" page-delimiter))
2652   (make-local-variable 'paragraph-separate)
2653   (setq paragraph-separate paragraph-start)
2654   (make-local-variable 'paragraph-ignore-fill-prefix)
2655   (setq paragraph-ignore-fill-prefix t)
2656   (make-local-variable 'indent-line-function)
2657   (setq indent-line-function 'cperl-indent-line)
2658   (make-local-variable 'require-final-newline)
2659   (setq require-final-newline t)
2660   (make-local-variable 'comment-start)
2661   (setq comment-start "# ")
2662   (make-local-variable 'comment-end)
2663   (setq comment-end "")
2664   (make-local-variable 'comment-column)
2665   (setq comment-column cperl-comment-column)
2666   (make-local-variable 'comment-start-skip)
2667   (setq comment-start-skip "#+ *")
2668   (make-local-variable 'defun-prompt-regexp)
2669   (setq defun-prompt-regexp "^[ \t]*sub[ \t]+\\([^ \t\n{(;]+\\)\\([ \t]*([^()]*)[ \t]*\\)?[ \t]*")
2670   (make-local-variable 'comment-indent-function)
2671   (setq comment-indent-function 'cperl-comment-indent)
2672   (make-local-variable 'parse-sexp-ignore-comments)
2673   (setq parse-sexp-ignore-comments t)
2674   (make-local-variable 'indent-region-function)
2675   (setq indent-region-function 'cperl-indent-region)
2676   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
2677   (make-local-variable 'imenu-create-index-function)
2678   (setq imenu-create-index-function
2679         (function cperl-imenu--create-perl-index))
2680   (make-local-variable 'imenu-sort-function)
2681   (setq imenu-sort-function nil)
2682   (make-local-variable 'vc-header-alist)
2683   (set 'vc-header-alist cperl-vc-header-alist) ; Avoid warning
2684   (make-local-variable 'font-lock-defaults)
2685   (setq font-lock-defaults
2686         (cond
2687          ((string< emacs-version "19.30")
2688           '(perl-font-lock-keywords-2))
2689          ((string< emacs-version "19.33") ; Which one to use?
2690           '((perl-font-lock-keywords
2691              perl-font-lock-keywords-1
2692              perl-font-lock-keywords-2)))
2693          (t
2694           '((cperl-load-font-lock-keywords
2695              cperl-load-font-lock-keywords-1
2696              cperl-load-font-lock-keywords-2)))))
2697   (make-local-variable 'cperl-syntax-state)
2698   (if cperl-use-syntax-table-text-property
2699       (progn
2700         (make-local-variable 'parse-sexp-lookup-properties)
2701         ;; Do not introduce variable if not needed, we check it!
2702         (set 'parse-sexp-lookup-properties t)
2703         ;; Fix broken font-lock:
2704         (or (boundp 'font-lock-unfontify-region-function)
2705             (set 'font-lock-unfontify-region-function
2706                  'font-lock-default-unfontify-region))
2707         (make-local-variable 'font-lock-unfontify-region-function)
2708         (set 'font-lock-unfontify-region-function ; not present with old Emacs
2709               'cperl-font-lock-unfontify-region-function)
2710         (make-local-variable 'cperl-syntax-done-to)
2711         ;; Another bug: unless font-lock-syntactic-keywords, font-lock
2712         ;;  ignores syntax-table text-property.  (t) is a hack
2713         ;;  to make font-lock think that font-lock-syntactic-keywords
2714         ;;  are defined
2715         (make-local-variable 'font-lock-syntactic-keywords)
2716         (setq font-lock-syntactic-keywords
2717               (if cperl-syntaxify-by-font-lock
2718                   '(t (cperl-fontify-syntaxically))
2719                 '(t)))))
2720   (make-local-variable 'cperl-old-style)
2721   (if (boundp 'normal-auto-fill-function) ; 19.33 and later
2722       (set (make-local-variable 'normal-auto-fill-function)
2723            'cperl-do-auto-fill)       ; RMS has it as #'cperl-do-auto-fill ???
2724     (or (fboundp 'cperl-old-auto-fill-mode)
2725         (progn
2726           (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
2727           (defun auto-fill-mode (&optional arg)
2728             (interactive "P")
2729             (eval '(cperl-old-auto-fill-mode arg)) ; Avoid a warning
2730             (and auto-fill-function (memq major-mode '(perl-mode cperl-mode))
2731                  (setq auto-fill-function 'cperl-do-auto-fill))))))
2732   (if (cperl-enable-font-lock)
2733       (if (cperl-val 'cperl-font-lock)
2734           (progn (or cperl-faces-init (cperl-init-faces))
2735                  (font-lock-mode 1))))
2736   (and (boundp 'msb-menu-cond)
2737        (not cperl-msb-fixed)
2738        (cperl-msb-fix))
2739   (if (featurep 'easymenu)
2740       (easy-menu-add cperl-menu))       ; A NOP in RMS Emacs.
2741   (run-hooks 'cperl-mode-hook)
2742   ;; After hooks since fontification will break this
2743   (if cperl-pod-here-scan
2744       (or cperl-syntaxify-by-font-lock
2745        (progn (or cperl-faces-init (cperl-init-faces-weak))
2746               (cperl-find-pods-heres)))))
2747 \f
2748 ;; Fix for perldb - make default reasonable
2749 (defun cperl-db ()
2750   (interactive)
2751   (require 'gud)
2752   (perldb (read-from-minibuffer "Run perldb (like this): "
2753                                 (if (consp gud-perldb-history)
2754                                     (car gud-perldb-history)
2755                                   (concat "perl " ;;(file-name-nondirectory
2756                                           ;; I have problems
2757                                           ;; in OS/2
2758                                           ;; otherwise
2759                                           (buffer-file-name)))
2760                                 nil nil
2761                                 '(gud-perldb-history . 1))))
2762 \f
2763 (defun cperl-msb-fix ()
2764   ;; Adds perl files to msb menu, supposes that msb is already loaded
2765   (setq cperl-msb-fixed t)
2766   (let* ((l (length msb-menu-cond))
2767          (last (nth (1- l) msb-menu-cond))
2768          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
2769          (handle (1- (nth 1 last))))
2770     (setcdr precdr (list
2771                     (list
2772                      '(memq major-mode '(cperl-mode perl-mode))
2773                      handle
2774                      "Perl Files (%d)")
2775                     last))))
2776 \f
2777 ;; This is used by indent-for-comment
2778 ;; to decide how much to indent a comment in CPerl code
2779 ;; based on its context.  Do fallback if comment is found wrong.
2780
2781 (defvar cperl-wrong-comment)
2782 (defvar cperl-st-cfence '(14))          ; Comment-fence
2783 (defvar cperl-st-sfence '(15))          ; String-fence
2784 (defvar cperl-st-punct '(1))
2785 (defvar cperl-st-word '(2))
2786 (defvar cperl-st-bra '(4 . ?\>))
2787 (defvar cperl-st-ket '(5 . ?\<))
2788
2789
2790 (defun cperl-comment-indent ()
2791   (let ((p (point)) (c (current-column)) was phony)
2792     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
2793       ;; Wrong comment found
2794       (save-excursion
2795         (setq was (cperl-to-comment-or-eol)
2796               phony (eq (get-text-property (point) 'syntax-table)
2797                         cperl-st-cfence))
2798         (if phony
2799             (progn
2800               (re-search-forward "#\\|$") ; Hmm, what about embedded #?
2801               (if (eq (preceding-char) ?\#)
2802                   (forward-char -1))
2803               (setq was nil)))
2804         (if (= (point) p)
2805             (progn
2806               (skip-chars-backward " \t")
2807               (max (1+ (current-column)) ; Else indent at comment column
2808                    comment-column))
2809           (if was nil
2810             (insert comment-start)
2811             (backward-char (length comment-start)))
2812           (setq cperl-wrong-comment t)
2813           (indent-to comment-column 1)  ; Indent minimum 1
2814           c)))))                        ; except leave at least one space.
2815
2816 ;;;(defun cperl-comment-indent-fallback ()
2817 ;;;  "Is called if the standard comment-search procedure fails.
2818 ;;;Point is at start of real comment."
2819 ;;;  (let ((c (current-column)) target cnt prevc)
2820 ;;;    (if (= c comment-column) nil
2821 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
2822 ;;;      (setq target (max (1+ (setq prevc
2823 ;;;                          (current-column))) ; Else indent at comment column
2824 ;;;                comment-column))
2825 ;;;      (if (= c comment-column) nil
2826 ;;;     (delete-backward-char cnt)
2827 ;;;     (while (< prevc target)
2828 ;;;       (insert "\t")
2829 ;;;       (setq prevc (current-column)))
2830 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
2831 ;;;     (while (< prevc target)
2832 ;;;       (insert " ")
2833 ;;;       (setq prevc (current-column)))))))
2834
2835 (defun cperl-indent-for-comment ()
2836   "Substitute for `indent-for-comment' in CPerl."
2837   (interactive)
2838   (let (cperl-wrong-comment)
2839     (indent-for-comment)
2840     (if cperl-wrong-comment
2841         (progn (cperl-to-comment-or-eol)
2842                (forward-char (length comment-start))))))
2843
2844 (defun cperl-comment-region (b e arg)
2845   "Comment or uncomment each line in the region in CPerl mode.
2846 See `comment-region'."
2847   (interactive "r\np")
2848   (let ((comment-start "#"))
2849     (comment-region b e arg)))
2850
2851 (defun cperl-uncomment-region (b e arg)
2852   "Uncomment or comment each line in the region in CPerl mode.
2853 See `comment-region'."
2854   (interactive "r\np")
2855   (let ((comment-start "#"))
2856     (comment-region b e (- arg))))
2857
2858 (defvar cperl-brace-recursing nil)
2859
2860 (defun cperl-electric-brace (arg &optional only-before)
2861   "Insert character and correct line's indentation.
2862 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
2863 place (even in empty line), but not after.  If after \")\" and the inserted
2864 char is \"{\", insert extra newline before only if
2865 `cperl-extra-newline-before-brace'."
2866   (interactive "P")
2867   (let (insertpos
2868         (other-end (if (and cperl-electric-parens-mark
2869                             (cperl-mark-active)
2870                             (< (mark) (point)))
2871                        (mark)
2872                      nil)))
2873     (if (and other-end
2874              (not cperl-brace-recursing)
2875              (cperl-val 'cperl-electric-parens)
2876              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point)))
2877         ;; Need to insert a matching pair
2878         (progn
2879           (save-excursion
2880             (setq insertpos (point-marker))
2881             (goto-char other-end)
2882             (setq last-command-char ?\{)
2883             (cperl-electric-lbrace arg insertpos))
2884           (forward-char 1))
2885       ;; Check whether we close something "usual" with `}'
2886       (if (and (eq last-command-char ?\})
2887                (not
2888                 (condition-case nil
2889                     (save-excursion
2890                       (up-list (- (prefix-numeric-value arg)))
2891                       ;;(cperl-after-block-p (point-min))
2892                       (or (cperl-after-expr-p nil "{;)")
2893                           ;; after sub, else, continue
2894                           (cperl-after-block-p nil 'pre)))
2895                   (error nil))))
2896           ;; Just insert the guy
2897           (self-insert-command (prefix-numeric-value arg))
2898         (if (and (not arg)              ; No args, end (of empty line or auto)
2899                  (eolp)
2900                  (or (and (null only-before)
2901                           (save-excursion
2902                             (skip-chars-backward " \t")
2903                             (bolp)))
2904                      (and (eq last-command-char ?\{) ; Do not insert newline
2905                           ;; if after ")" and `cperl-extra-newline-before-brace'
2906                           ;; is nil, do not insert extra newline.
2907                           (not cperl-extra-newline-before-brace)
2908                           (save-excursion
2909                             (skip-chars-backward " \t")
2910                             (eq (preceding-char) ?\))))
2911                      (if cperl-auto-newline
2912                          (progn (cperl-indent-line) (newline) t) nil)))
2913             (progn
2914               (self-insert-command (prefix-numeric-value arg))
2915               (cperl-indent-line)
2916               (if cperl-auto-newline
2917                   (setq insertpos (1- (point))))
2918               (if (and cperl-auto-newline (null only-before))
2919                   (progn
2920                     (newline)
2921                     (cperl-indent-line)))
2922               (save-excursion
2923                 (if insertpos (progn (goto-char insertpos)
2924                                      (search-forward (make-string
2925                                                       1 last-command-char))
2926                                      (setq insertpos (1- (point)))))
2927                 (delete-char -1))))
2928         (if insertpos
2929             (save-excursion
2930               (goto-char insertpos)
2931               (self-insert-command (prefix-numeric-value arg)))
2932           (self-insert-command (prefix-numeric-value arg)))))))
2933
2934 (defun cperl-electric-lbrace (arg &optional end)
2935   "Insert character, correct line's indentation, correct quoting by space."
2936   (interactive "P")
2937   (let ((cperl-brace-recursing t)
2938         (cperl-auto-newline cperl-auto-newline)
2939         (other-end (or end
2940                        (if (and cperl-electric-parens-mark
2941                                 (cperl-mark-active)
2942                                 (> (mark) (point)))
2943                            (save-excursion
2944                              (goto-char (mark))
2945                              (point-marker))
2946                          nil)))
2947         pos after)
2948     (and (cperl-val 'cperl-electric-lbrace-space)
2949          (eq (preceding-char) ?$)
2950          (save-excursion
2951            (skip-chars-backward "$")
2952            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
2953          (insert ?\ ))
2954     ;; Check whether we are in comment
2955     (if (and
2956          (save-excursion
2957            (beginning-of-line)
2958            (not (looking-at "[ \t]*#")))
2959          (cperl-after-expr-p nil "{;)"))
2960         nil
2961       (setq cperl-auto-newline nil))
2962     (cperl-electric-brace arg)
2963     (and (cperl-val 'cperl-electric-parens)
2964          (eq last-command-char ?{)
2965          (memq last-command-char
2966                (append cperl-electric-parens-string nil))
2967          (or (if other-end (goto-char (marker-position other-end)))
2968              t)
2969          (setq last-command-char ?} pos (point))
2970          (progn (cperl-electric-brace arg t)
2971                 (goto-char pos)))))
2972
2973 (defun cperl-electric-paren (arg)
2974   "Insert an opening parenthesis or a matching pair of parentheses.
2975 See `cperl-electric-parens'."
2976   (interactive "P")
2977   (let ((beg (save-excursion (beginning-of-line) (point)))
2978         (other-end (if (and cperl-electric-parens-mark
2979                             (cperl-mark-active)
2980                             (> (mark) (point)))
2981                        (save-excursion
2982                          (goto-char (mark))
2983                          (point-marker))
2984                      nil)))
2985     (if (and (cperl-val 'cperl-electric-parens)
2986              (memq last-command-char
2987                    (append cperl-electric-parens-string nil))
2988              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
2989              ;;(not (save-excursion (search-backward "#" beg t)))
2990              (if (eq last-command-char ?<)
2991                  (progn
2992                    (and abbrev-mode ; later it is too late, may be after `for'
2993                         (expand-abbrev))
2994                    (cperl-after-expr-p nil "{;(,:="))
2995                1))
2996         (progn
2997           (self-insert-command (prefix-numeric-value arg))
2998           (if other-end (goto-char (marker-position other-end)))
2999           (insert (make-string
3000                    (prefix-numeric-value arg)
3001                    (cdr (assoc last-command-char '((?{ .?})
3002                                                    (?[ . ?])
3003                                                    (?( . ?))
3004                                                    (?< . ?>))))))
3005           (forward-char (- (prefix-numeric-value arg))))
3006       (self-insert-command (prefix-numeric-value arg)))))
3007
3008 (defun cperl-electric-rparen (arg)
3009   "Insert a matching pair of parentheses if marking is active.
3010 If not, or if we are not at the end of marking range, would self-insert.
3011 Affected by `cperl-electric-parens'."
3012   (interactive "P")
3013   (let ((beg (save-excursion (beginning-of-line) (point)))
3014         (other-end (if (and cperl-electric-parens-mark
3015                             (cperl-val 'cperl-electric-parens)
3016                             (memq last-command-char
3017                                   (append cperl-electric-parens-string nil))
3018                             (cperl-mark-active)
3019                             (< (mark) (point)))
3020                        (mark)
3021                      nil))
3022         p)
3023     (if (and other-end
3024              (cperl-val 'cperl-electric-parens)
3025              (memq last-command-char '( ?\) ?\] ?\} ?\> ))
3026              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
3027              ;;(not (save-excursion (search-backward "#" beg t)))
3028              )
3029         (progn
3030           (self-insert-command (prefix-numeric-value arg))
3031           (setq p (point))
3032           (if other-end (goto-char other-end))
3033           (insert (make-string
3034                    (prefix-numeric-value arg)
3035                    (cdr (assoc last-command-char '((?\} . ?\{)
3036                                                    (?\] . ?\[)
3037                                                    (?\) . ?\()
3038                                                    (?\> . ?\<))))))
3039           (goto-char (1+ p)))
3040       (self-insert-command (prefix-numeric-value arg)))))
3041
3042 (defun cperl-electric-keyword ()
3043   "Insert a construction appropriate after a keyword.
3044 Help message may be switched off by setting `cperl-message-electric-keyword'
3045 to nil."
3046   (let ((beg (save-excursion (beginning-of-line) (point)))
3047         (dollar (and (eq last-command-char ?$)
3048                      (eq this-command 'self-insert-command)))
3049         (delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3050                      (memq this-command '(self-insert-command newline))))
3051         my do)
3052     (and (save-excursion
3053            (condition-case nil
3054                (progn
3055                  (backward-sexp 1)
3056                  (setq do (looking-at "do\\>")))
3057              (error nil))
3058            (cperl-after-expr-p nil "{;:"))
3059          (save-excursion
3060            (not
3061             (re-search-backward
3062              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3063              beg t)))
3064          (save-excursion (or (not (re-search-backward "^=" nil t))
3065                              (or
3066                               (looking-at "=cut")
3067                               (and cperl-use-syntax-table-text-property
3068                                    (not (eq (get-text-property (point)
3069                                                                'syntax-type)
3070                                             'pod))))))
3071          (save-excursion (forward-sexp -1) 
3072                          (not (memq (following-char) (append "$@%&*" nil))))
3073          (progn
3074            (and (eq (preceding-char) ?y)
3075                 (progn                  ; "foreachmy"
3076                   (forward-char -2)
3077                   (insert " ")
3078                   (forward-char 2)
3079                   (setq my t dollar t
3080                         delete
3081                         (memq this-command '(self-insert-command newline)))))
3082            (and dollar (insert " $"))
3083            (cperl-indent-line)
3084            ;;(insert " () {\n}")
3085            (cond
3086             (cperl-extra-newline-before-brace
3087              (insert (if do "\n" " ()\n"))
3088              (insert "{")
3089              (cperl-indent-line)
3090              (insert "\n")
3091              (cperl-indent-line)
3092              (insert "\n}")
3093              (and do (insert " while ();")))
3094             (t
3095              (insert (if do " {\n} while ();" " () {\n}"))))
3096            (or (looking-at "[ \t]\\|$") (insert " "))
3097            (cperl-indent-line)
3098            (if dollar (progn (search-backward "$")
3099                              (if my
3100                                  (forward-char 1)
3101                                (delete-char 1)))
3102              (search-backward ")")
3103              (if (eq last-command-char ?\()
3104                  (progn                 ; Avoid "if (())"
3105                    (delete-backward-char 1)
3106                    (delete-backward-char -1))))
3107            (if delete
3108                (cperl-putback-char cperl-del-back-ch))
3109            (if cperl-message-electric-keyword
3110                (message "Precede char by C-q to avoid expansion"))))))
3111
3112 (defun cperl-ensure-newlines (n &optional pos)
3113   "Make sure there are N newlines after the point."
3114   (or pos (setq pos (point)))
3115   (if (looking-at "\n")
3116       (forward-char 1)
3117     (insert "\n"))
3118   (if (> n 1)
3119       (cperl-ensure-newlines (1- n) pos)
3120     (goto-char pos)))
3121
3122 (defun cperl-electric-pod ()
3123   "Insert a POD chunk appropriate after a =POD directive."
3124   (let ((delete (and (memq last-command-char '(?\ ?\n ?\t ?\f))
3125                      (memq this-command '(self-insert-command newline))))
3126         head1 notlast name p really-delete over)
3127     (and (save-excursion
3128            (forward-word -1)
3129            (and
3130             (eq (preceding-char) ?=)
3131             (progn
3132               (setq head1 (looking-at "head1\\>[ \t]*$"))
3133               (setq over (and (looking-at "over\\>[ \t]*$")
3134                               (not (looking-at "over[ \t]*\n\n\n*=item\\>"))))
3135               (forward-char -1)
3136               (bolp))
3137             (or
3138              (get-text-property (point) 'in-pod)
3139              (cperl-after-expr-p nil "{;:")
3140              (and (re-search-backward
3141                    ;; "\\(\\`\n?\\|\n\n\\)=\\sw+"
3142                    "\\(\\`\n?\\|^\n\\)=\\sw+"
3143                    (point-min) t)
3144                   (not (or
3145                         (looking-at "=cut")
3146                         (and cperl-use-syntax-table-text-property
3147                              (not (eq (get-text-property (point) 'syntax-type)
3148                                       'pod)))))))))
3149          (progn
3150            (save-excursion
3151              (setq notlast (re-search-forward "^\n=" nil t)))
3152            (or notlast
3153                (progn
3154                  (insert "\n\n=cut")
3155                  (cperl-ensure-newlines 2)
3156                  (forward-word -2)
3157                  (if (and head1
3158                           (not
3159                            (save-excursion
3160                              (forward-char -1)
3161                              (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\>"
3162                                                  nil t)))) ; Only one
3163                      (progn
3164                        (forward-word 1)
3165                        (setq name (file-name-sans-extension
3166                                    (file-name-nondirectory (buffer-file-name)))
3167                              p (point))
3168                        (insert " NAME\n\n" name
3169                                " - \n\n=head1 SYNOPSIS\n\n\n\n"
3170                                "=head1 DESCRIPTION")
3171                        (cperl-ensure-newlines 4)
3172                        (goto-char p)
3173                        (forward-word 2)
3174                        (end-of-line)
3175                        (setq really-delete t))
3176                    (forward-word 1))))
3177            (if over
3178                (progn
3179                  (setq p (point))
3180                  (insert "\n\n=item \n\n\n\n"
3181                          "=back")
3182                  (cperl-ensure-newlines 2)
3183                  (goto-char p)
3184                  (forward-word 1)
3185                  (end-of-line)
3186                  (setq really-delete t)))
3187            (if (and delete really-delete)
3188                (cperl-putback-char cperl-del-back-ch))))))
3189
3190 (defun cperl-electric-else ()
3191   "Insert a construction appropriate after a keyword.
3192 Help message may be switched off by setting `cperl-message-electric-keyword'
3193 to nil."
3194   (let ((beg (save-excursion (beginning-of-line) (point))))
3195     (and (save-excursion
3196            (backward-sexp 1)
3197            (cperl-after-expr-p nil "{;:"))
3198          (save-excursion
3199            (not
3200             (re-search-backward
3201              "[#\"'`]\\|\\<q\\(\\|[wqxr]\\)\\>"
3202              beg t)))
3203          (save-excursion (or (not (re-search-backward "^=" nil t))
3204                              (looking-at "=cut")
3205                              (and cperl-use-syntax-table-text-property
3206                                   (not (eq (get-text-property (point)
3207                                                               'syntax-type)
3208                                            'pod)))))
3209          (progn
3210            (cperl-indent-line)
3211            ;;(insert " {\n\n}")
3212            (cond
3213             (cperl-extra-newline-before-brace
3214              (insert "\n")
3215              (insert "{")
3216              (cperl-indent-line)
3217              (insert "\n\n}"))
3218             (t
3219              (insert " {\n\n}")))
3220            (or (looking-at "[ \t]\\|$") (insert " "))
3221            (cperl-indent-line)
3222            (forward-line -1)
3223            (cperl-indent-line)
3224            (cperl-putback-char cperl-del-back-ch)
3225            (setq this-command 'cperl-electric-else)
3226            (if cperl-message-electric-keyword
3227                (message "Precede char by C-q to avoid expansion"))))))
3228
3229 (defun cperl-linefeed ()
3230   "Go to end of line, open a new line and indent appropriately.
3231 If in POD, insert appropriate lines."
3232   (interactive)
3233   (let ((beg (save-excursion (beginning-of-line) (point)))
3234         (end (save-excursion (end-of-line) (point)))
3235         (pos (point)) start over cut res)
3236     (if (and                            ; Check if we need to split:
3237                                         ; i.e., on a boundary and inside "{...}"
3238          (save-excursion (cperl-to-comment-or-eol)
3239                          (>= (point) pos)) ; Not in a comment
3240          (or (save-excursion
3241                (skip-chars-backward " \t" beg)
3242                (forward-char -1)
3243                (looking-at "[;{]"))     ; After { or ; + spaces
3244              (looking-at "[ \t]*}")     ; Before }
3245              (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
3246          (save-excursion
3247            (and
3248             (eq (car (parse-partial-sexp pos end -1)) -1)
3249                                         ; Leave the level of parens
3250             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
3251                                         ; Are at end
3252             (cperl-after-block-p (point-min))
3253             (progn
3254               (backward-sexp 1)
3255               (setq start (point-marker))
3256               (<= start pos)))))        ; Redundant?  Are after the
3257                                         ; start of parens group.
3258         (progn
3259           (skip-chars-backward " \t")
3260           (or (memq (preceding-char) (append ";{" nil))
3261               (insert ";"))
3262           (insert "\n")
3263           (forward-line -1)
3264           (cperl-indent-line)
3265           (goto-char start)
3266           (or (looking-at "{[ \t]*$")   ; If there is a statement
3267                                         ; before, move it to separate line
3268               (progn
3269                 (forward-char 1)
3270                 (insert "\n")
3271                 (cperl-indent-line)))
3272           (forward-line 1)              ; We are on the target line
3273           (cperl-indent-line)
3274           (beginning-of-line)
3275           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
3276                                         ; after, move it to separate line
3277               (progn
3278                 (end-of-line)
3279                 (search-backward "}" beg)
3280                 (skip-chars-backward " \t")
3281                 (or (memq (preceding-char) (append ";{" nil))
3282                     (insert ";"))
3283                 (insert "\n")
3284                 (cperl-indent-line)
3285                 (forward-line -1)))
3286           (forward-line -1)             ; We are on the line before target
3287           (end-of-line)
3288           (newline-and-indent))
3289       (end-of-line)                     ; else - no splitting
3290       (cond
3291        ((and (looking-at "\n[ \t]*{$")
3292              (save-excursion
3293                (skip-chars-backward " \t")
3294                (eq (preceding-char) ?\)))) ; Probably if () {} group
3295                                         ; with an extra newline.
3296         (forward-line 2)
3297         (cperl-indent-line))
3298        ((save-excursion                 ; In POD header
3299           (forward-paragraph -1)
3300           ;; (re-search-backward "\\(\\`\n?\\|\n\n\\)=head1\\b")
3301           ;; We are after \n now, so look for the rest
3302           (if (looking-at "\\(\\`\n?\\|\n\\)=\\sw+")
3303               (progn
3304                 (setq cut (looking-at "\\(\\`\n?\\|\n\\)=cut\\>"))
3305                 (setq over (looking-at "\\(\\`\n?\\|\n\\)=over\\>"))
3306                 t)))
3307         (if (and over
3308                  (progn
3309                    (forward-paragraph -1)
3310                    (forward-word 1)
3311                    (setq pos (point))
3312                    (setq cut (buffer-substring (point)
3313                                                (save-excursion
3314                                                  (end-of-line)
3315                                                  (point))))
3316                    (delete-char (- (save-excursion (end-of-line) (point))
3317                                    (point)))
3318                    (setq res (expand-abbrev))
3319                    (save-excursion
3320                      (goto-char pos)
3321                      (insert cut))
3322                    res))
3323             nil
3324           (cperl-ensure-newlines (if cut 2 4))
3325           (forward-line 2)))
3326        ((get-text-property (point) 'in-pod) ; In POD section
3327         (cperl-ensure-newlines 4)
3328         (forward-line 2))
3329        ((looking-at "\n[ \t]*$")        ; Next line is empty - use it.
3330         (forward-line 1)
3331         (cperl-indent-line))
3332        (t
3333         (newline-and-indent))))))
3334
3335 (defun cperl-electric-semi (arg)
3336   "Insert character and correct line's indentation."
3337   (interactive "P")
3338   (if cperl-auto-newline
3339       (cperl-electric-terminator arg)
3340     (self-insert-command (prefix-numeric-value arg))
3341     (if cperl-autoindent-on-semi
3342         (cperl-indent-line))))
3343
3344 (defun cperl-electric-terminator (arg)
3345   "Insert character and correct line's indentation."
3346   (interactive "P")
3347   (let ((end (point))
3348         (auto (and cperl-auto-newline
3349                    (or (not (eq last-command-char ?:))
3350                        cperl-auto-newline-after-colon)))
3351         insertpos)
3352     (if (and ;;(not arg)
3353              (eolp)
3354              (not (save-excursion
3355                     (beginning-of-line)
3356                     (skip-chars-forward " \t")
3357                     (or
3358                      ;; Ignore in comment lines
3359                      (= (following-char) ?#)
3360                      ;; Colon is special only after a label
3361                      ;; So quickly rule out most other uses of colon
3362                      ;; and do no indentation for them.
3363                      (and (eq last-command-char ?:)
3364                           (save-excursion
3365                             (forward-word 1)
3366                             (skip-chars-forward " \t")
3367                             (and (< (point) end)
3368                                  (progn (goto-char (- end 1))
3369                                         (not (looking-at ":"))))))
3370                      (progn
3371                        (beginning-of-defun)
3372                        (let ((pps (parse-partial-sexp (point) end)))
3373                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
3374         (progn
3375           (self-insert-command (prefix-numeric-value arg))
3376           ;;(forward-char -1)
3377           (if auto (setq insertpos (point-marker)))
3378           ;;(forward-char 1)
3379           (cperl-indent-line)
3380           (if auto
3381               (progn
3382                 (newline)
3383                 (cperl-indent-line)))
3384           (save-excursion
3385             (if insertpos (goto-char (1- (marker-position insertpos)))
3386               (forward-char -1))
3387             (delete-char 1))))
3388     (if insertpos
3389         (save-excursion
3390           (goto-char insertpos)
3391           (self-insert-command (prefix-numeric-value arg)))
3392       (self-insert-command (prefix-numeric-value arg)))))
3393
3394 (defun cperl-electric-backspace (arg)
3395   "Backspace, or remove the whitespace around the point inserted by an electric
3396 key.  Will untabivy if `cperl-electric-backspace-untabify' is non-nil."
3397   (interactive "p")
3398   (if (and cperl-auto-newline
3399            (memq last-command '(cperl-electric-semi
3400                                 cperl-electric-terminator
3401                                 cperl-electric-lbrace))
3402            (memq (preceding-char) '(?\  ?\t ?\n)))
3403       (let (p)
3404         (if (eq last-command 'cperl-electric-lbrace)
3405             (skip-chars-forward " \t\n"))
3406         (setq p (point))
3407         (skip-chars-backward " \t\n")
3408         (delete-region (point) p))
3409     (and (eq last-command 'cperl-electric-else)
3410          ;; We are removing the whitespace *inside* cperl-electric-else
3411          (setq this-command 'cperl-electric-else-really))
3412     (if (and cperl-auto-newline
3413              (eq last-command 'cperl-electric-else-really)
3414              (memq (preceding-char) '(?\  ?\t ?\n)))
3415         (let (p)
3416           (skip-chars-forward " \t\n")
3417           (setq p (point))
3418           (skip-chars-backward " \t\n")
3419           (delete-region (point) p))
3420       (if cperl-electric-backspace-untabify
3421           (backward-delete-char-untabify arg)
3422         (delete-backward-char arg)))))
3423
3424 (defun cperl-inside-parens-p ()
3425   (condition-case ()
3426       (save-excursion
3427         (save-restriction
3428           (narrow-to-region (point)
3429                             (progn (beginning-of-defun) (point)))
3430           (goto-char (point-max))
3431           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
3432     (error nil)))
3433 \f
3434 (defun cperl-indent-command (&optional whole-exp)
3435   "Indent current line as Perl code, or in some cases insert a tab character.
3436 If `cperl-tab-always-indent' is non-nil (the default), always indent current
3437 line.  Otherwise, indent the current line only if point is at the left margin
3438 or in the line's indentation; otherwise insert a tab.
3439
3440 A numeric argument, regardless of its value,
3441 means indent rigidly all the lines of the expression starting after point
3442 so that this line becomes properly indented.
3443 The relative indentation among the lines of the expression are preserved."
3444   (interactive "P")
3445   (cperl-update-syntaxification (point) (point))
3446   (if whole-exp
3447       ;; If arg, always indent this line as Perl
3448       ;; and shift remaining lines of expression the same amount.
3449       (let ((shift-amt (cperl-indent-line))
3450             beg end)
3451         (save-excursion
3452           (if cperl-tab-always-indent
3453               (beginning-of-line))
3454           (setq beg (point))
3455           (forward-sexp 1)
3456           (setq end (point))
3457           (goto-char beg)
3458           (forward-line 1)
3459           (setq beg (point)))
3460         (if (and shift-amt (> end beg))
3461             (indent-code-rigidly beg end shift-amt "#")))
3462     (if (and (not cperl-tab-always-indent)
3463              (save-excursion
3464                (skip-chars-backward " \t")
3465                (not (bolp))))
3466         (insert-tab)
3467       (cperl-indent-line))))
3468
3469 (defun cperl-indent-line (&optional parse-data)
3470   "Indent current line as Perl code.
3471 Return the amount the indentation changed by."
3472   (let ((case-fold-search nil)
3473         (pos (- (point-max) (point)))
3474         indent i beg shift-amt)
3475     (setq indent (cperl-calculate-indent parse-data)
3476           i indent)
3477     (beginning-of-line)
3478     (setq beg (point))
3479     (cond ((or (eq indent nil) (eq indent t))
3480            (setq indent (current-indentation) i nil))
3481           ;;((eq indent t)    ; Never?
3482           ;; (setq indent (cperl-calculate-indent-within-comment)))
3483           ;;((looking-at "[ \t]*#")
3484           ;; (setq indent 0))
3485           (t
3486            (skip-chars-forward " \t")
3487            (if (listp indent) (setq indent (car indent)))
3488            (cond ((looking-at "[A-Za-z_][A-Za-z_0-9]*:[^:]")
3489                   (and (> indent 0)
3490                        (setq indent (max cperl-min-label-indent
3491                                          (+ indent cperl-label-offset)))))
3492                  ((= (following-char) ?})
3493                   (setq indent (- indent cperl-indent-level)))
3494                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
3495                   (setq indent (+ indent cperl-close-paren-offset)))
3496                  ((= (following-char) ?{)
3497                   (setq indent (+ indent cperl-brace-offset))))))
3498     (skip-chars-forward " \t")
3499     (setq shift-amt (and i (- indent (current-column))))
3500     (if (or (not shift-amt)
3501             (zerop shift-amt))
3502         (if (> (- (point-max) pos) (point))
3503             (goto-char (- (point-max) pos)))
3504       (delete-region beg (point))
3505       (indent-to indent)
3506       ;; If initial point was within line's indentation,
3507       ;; position after the indentation.  Else stay at same point in text.
3508       (if (> (- (point-max) pos) (point))
3509           (goto-char (- (point-max) pos))))
3510     shift-amt))
3511
3512 (defun cperl-after-label ()
3513   ;; Returns true if the point is after label.  Does not do save-excursion.
3514   (and (eq (preceding-char) ?:)
3515        (memq (char-syntax (char-after (- (point) 2)))
3516              '(?w ?_))
3517        (progn
3518          (backward-sexp)
3519          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))
3520
3521 (defun cperl-get-state (&optional parse-start start-state)
3522   ;; returns list (START STATE DEPTH PRESTART),
3523   ;; START is a good place to start parsing, or equal to
3524   ;; PARSE-START if preset,
3525   ;; STATE is what is returned by `parse-partial-sexp'.
3526   ;; DEPTH is true is we are immediately after end of block
3527   ;; which contains START.
3528   ;; PRESTART is the position basing on which START was found.
3529   (save-excursion
3530     (let ((start-point (point)) depth state start prestart)
3531       (if (and parse-start
3532                (<= parse-start start-point))
3533           (goto-char parse-start)
3534         (beginning-of-defun)
3535         (setq start-state nil))
3536       (setq prestart (point))
3537       (if start-state nil
3538         ;; Try to go out, if sub is not on the outermost level
3539         (while (< (point) start-point)
3540           (setq start (point) parse-start start depth nil
3541                 state (parse-partial-sexp start start-point -1))
3542           (if (> (car state) -1) nil
3543             ;; The current line could start like }}}, so the indentation
3544             ;; corresponds to a different level than what we reached
3545             (setq depth t)
3546             (beginning-of-line 2)))     ; Go to the next line.
3547         (if start (goto-char start)))   ; Not at the start of file
3548       (setq start (point))
3549       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
3550       (list start state depth prestart))))
3551
3552 (defun cperl-block-p ()            ; Do not C-M-q !  One string contains ";" !
3553   ;; Positions is before ?\{.  Checks whether it starts a block.
3554   ;; No save-excursion!
3555   (cperl-backward-to-noncomment (point-min))
3556   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label!  \C-@ at bobp
3557                                         ; Label may be mixed up with `$blah :'
3558       (save-excursion (cperl-after-label))
3559       (and (memq (char-syntax (preceding-char)) '(?w ?_))
3560            (progn
3561              (backward-sexp)
3562              ;; Need take into account `bless', `return', `tr',...
3563              (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
3564                       (not (looking-at "\\(bless\\|return\\|q[wqrx]?\\|tr\\|[smy]\\)\\>")))
3565                  (progn
3566                    (skip-chars-backward " \t\n\f")
3567                    (and (memq (char-syntax (preceding-char)) '(?w ?_))
3568                         (progn
3569                           (backward-sexp)
3570                           (looking-at
3571                            "sub[ \t]+[a-zA-Z0-9_:]+[ \t\n\f]*\\(([^()]*)[ \t\n\f]*\\)?[#{]")))))))))
3572
3573 (defvar cperl-look-for-prop '((pod in-pod) (here-doc-delim here-doc-group)))
3574
3575 (defun cperl-calculate-indent (&optional parse-data) ; was parse-start
3576   "Return appropriate indentation for current line as Perl code.
3577 In usual case returns an integer: the column to indent to.
3578 Returns nil if line starts inside a string, t if in a comment.
3579
3580 Will not correct the indentation for labels, but will correct it for braces
3581 and closing parentheses and brackets."
3582   (cperl-update-syntaxification (point) (point))
3583   (save-excursion
3584     (if (or
3585          (and (memq (get-text-property (point) 'syntax-type)
3586                     '(pod here-doc here-doc-delim format))
3587               (not (get-text-property (point) 'indentable)))
3588          ;; before start of POD - whitespace found since do not have 'pod!
3589          (and (looking-at "[ \t]*\n=")
3590               (error "Spaces before POD section!"))
3591          (and (not cperl-indent-left-aligned-comments)
3592               (looking-at "^#")))
3593         nil
3594       (beginning-of-line)
3595       (let ((indent-point (point))
3596             (char-after (save-excursion
3597                           (skip-chars-forward " \t")
3598                           (following-char)))
3599             (in-pod (get-text-property (point) 'in-pod))
3600             (pre-indent-point (point))
3601             p prop look-prop is-block delim)
3602         (cond
3603          (in-pod
3604           ;; In the verbatim part, probably code example.  What to do???
3605           )
3606          (t
3607           (save-excursion
3608             ;; Not in POD
3609             (cperl-backward-to-noncomment nil)
3610             (setq p (max (point-min) (1- (point)))
3611                   prop (get-text-property p 'syntax-type)
3612                   look-prop (or (nth 1 (assoc prop cperl-look-for-prop))
3613                                 'syntax-type))
3614             (if (memq prop '(pod here-doc format here-doc-delim))
3615                 (progn
3616                   (goto-char (or (previous-single-property-change p look-prop)
3617                                  (point-min)))
3618                   (beginning-of-line)
3619                   (setq pre-indent-point (point)))))))
3620         (goto-char pre-indent-point)
3621         (let* ((case-fold-search nil)
3622                (s-s (cperl-get-state (car parse-data) (nth 1 parse-data)))
3623                (start (or (nth 2 parse-data)
3624                           (nth 0 s-s)))
3625                (state (nth 1 s-s))
3626                (containing-sexp (car (cdr state)))
3627                old-indent)
3628           (if (and
3629                ;;containing-sexp                ;; We are buggy at toplevel :-(
3630                parse-data)
3631               (progn
3632                 (setcar parse-data pre-indent-point)
3633                 (setcar (cdr parse-data) state)
3634                 (or (nth 2 parse-data)
3635                     (setcar (cddr parse-data) start))
3636                 ;; Before this point: end of statement
3637                 (setq old-indent (nth 3 parse-data))))
3638           (cond ((get-text-property (point) 'indentable)
3639                  ;; indent to just after the surrounding open,
3640                  ;; skip blanks if we do not close the expression.
3641                  (goto-char (1+ (previous-single-property-change (point) 'indentable)))
3642                  (or (memq char-after (append ")]}" nil))
3643                      (looking-at "[ \t]*\\(#\\|$\\)")
3644                      (skip-chars-forward " \t"))
3645                  (current-column))
3646                 ((or (nth 3 state) (nth 4 state))
3647                  ;; return nil or t if should not change this line
3648                  (nth 4 state))
3649                 ;; XXXX Do we need to special-case this?
3650                 ((null containing-sexp)
3651                  ;; Line is at top level.  May be data or function definition,
3652                  ;; or may be function argument declaration.
3653                  ;; Indent like the previous top level line
3654                  ;; unless that ends in a closeparen without semicolon,
3655                  ;; in which case this line is the first argument decl.
3656                  (skip-chars-forward " \t")
3657                  (+ (save-excursion
3658                       (goto-char start)
3659                       (- (current-indentation)
3660                          (if (nth 2 s-s) cperl-indent-level 0)))
3661                     (if (= char-after ?{) cperl-continued-brace-offset 0)
3662                     (progn
3663                       (cperl-backward-to-noncomment (or old-indent (point-min)))
3664                       ;; Look at previous line that's at column 0
3665                       ;; to determine whether we are in top-level decls
3666                       ;; or function's arg decls.  Set basic-indent accordingly.
3667                       ;; Now add a little if this is a continuation line.
3668                       (if (or (bobp)
3669                               (eq (point) old-indent) ; old-indent was at comment
3670                               (eq (preceding-char) ?\;)
3671                               ;;  Had ?\) too
3672                               (and (eq (preceding-char) ?\})
3673                                    (cperl-after-block-and-statement-beg
3674                                     (point-min))) ; Was start - too close
3675                               (memq char-after (append ")]}" nil))
3676                               (and (eq (preceding-char) ?\:) ; label
3677                                    (progn
3678                                      (forward-sexp -1)
3679                                      (skip-chars-backward " \t")
3680                                      (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*[ \t]*:")))
3681                               (get-text-property (point) 'first-format-line))
3682                           (progn
3683                             (if (and parse-data
3684                                      (not (eq char-after ?\C-j)))
3685                                 (setcdr (cddr parse-data)
3686                                         (list pre-indent-point)))
3687                             0)
3688                         cperl-continued-statement-offset))))
3689                 ((not
3690                   (or (setq is-block
3691                             (and (setq delim (= (char-after containing-sexp) ?{))
3692                                  (save-excursion ; Is it a hash?
3693                                    (goto-char containing-sexp)
3694                                    (cperl-block-p))))
3695                       cperl-indent-parens-as-block))
3696                  ;; group is an expression, not a block:
3697                  ;; indent to just after the surrounding open parens,
3698                  ;; skip blanks if we do not close the expression.
3699                  (goto-char (1+ containing-sexp))
3700                  (or (memq char-after
3701                            (append (if delim "}" ")]}") nil))
3702                      (looking-at "[ \t]*\\(#\\|$\\)")
3703                      (skip-chars-forward " \t"))
3704                  (+ (current-column)
3705                     (if (and delim
3706                              (eq char-after ?\}))
3707                         ;; Correct indentation of trailing ?\}
3708                         (+ cperl-indent-level cperl-close-paren-offset)
3709                       0)))
3710 ;;;           ((and (/= (char-after containing-sexp) ?{)
3711 ;;;                 (not cperl-indent-parens-as-block))
3712 ;;;            ;; line is expression, not statement:
3713 ;;;            ;; indent to just after the surrounding open,
3714 ;;;            ;; skip blanks if we do not close the expression.
3715 ;;;            (goto-char (1+ containing-sexp))
3716 ;;;            (or (memq char-after (append ")]}" nil))
3717 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
3718 ;;;                (skip-chars-forward " \t"))
3719 ;;;            (current-column))
3720 ;;;           ((progn
3721 ;;;              ;; Containing-expr starts with \{.  Check whether it is a hash.
3722 ;;;              (goto-char containing-sexp)
3723 ;;;              (and (not (cperl-block-p))
3724 ;;;                   (not cperl-indent-parens-as-block)))
3725 ;;;            (goto-char (1+ containing-sexp))
3726 ;;;            (or (eq char-after ?\})
3727 ;;;                (looking-at "[ \t]*\\(#\\|$\\)")
3728 ;;;                (skip-chars-forward " \t"))
3729 ;;;            (+ (current-column)      ; Correct indentation of trailing ?\}
3730 ;;;               (if (eq char-after ?\}) (+ cperl-indent-level
3731 ;;;                                          cperl-close-paren-offset)
3732 ;;;                 0)))
3733                 (t
3734                  ;; Statement level.  Is it a continuation or a new statement?
3735                  ;; Find previous non-comment character.
3736                  (goto-char pre-indent-point)
3737                  (cperl-backward-to-noncomment containing-sexp)
3738                  ;; Back up over label lines, since they don't
3739                  ;; affect whether our line is a continuation.
3740                  ;; (Had \, too)
3741                  (while ;;(or (eq (preceding-char) ?\,)
3742                      (and (eq (preceding-char) ?:)
3743                           (or ;;(eq (char-after (- (point) 2)) ?\') ; ????
3744                            (memq (char-syntax (char-after (- (point) 2)))
3745                                  '(?w ?_))))
3746                    ;;)
3747                    (if (eq (preceding-char) ?\,)
3748                        ;; Will go to beginning of line, essentially.
3749                        ;; Will ignore embedded sexpr XXXX.
3750                        (cperl-backward-to-start-of-continued-exp containing-sexp))
3751                    (beginning-of-line)
3752                    (cperl-backward-to-noncomment containing-sexp))
3753                  ;; Now we get the answer.
3754                  (if (not (or (eq (1- (point)) containing-sexp)
3755                               (memq (preceding-char)
3756                                     (append (if is-block " ;{" " ,;{") '(nil)))
3757                               (and (eq (preceding-char) ?\})
3758                                    (cperl-after-block-and-statement-beg
3759                                     containing-sexp))
3760                               (get-text-property (point) 'first-format-line)))
3761                      ;; This line is continuation of preceding line's statement;
3762                      ;; indent  `cperl-continued-statement-offset'  more than the
3763                      ;; previous line of the statement.
3764                      ;;
3765                      ;; There might be a label on this line, just
3766                      ;; consider it bad style and ignore it.
3767                      (progn
3768                        (cperl-backward-to-start-of-continued-exp containing-sexp)
3769                        (+ (if (memq char-after (append "}])" nil))
3770                               0         ; Closing parenth
3771                             cperl-continued-statement-offset)
3772                           (if (or is-block
3773                                   (not delim)
3774                                   (not (eq char-after ?\})))
3775                               0
3776                             ;; Now it is a hash reference
3777                             (+ cperl-indent-level cperl-close-paren-offset))
3778                           (if (looking-at "\\w+[ \t]*:")
3779                               (if (> (current-indentation) cperl-min-label-indent)
3780                                   (- (current-indentation) cperl-label-offset)
3781                                 ;; Do not move `parse-data', this should
3782                                 ;; be quick anyway (this comment comes
3783                                 ;; from different location):
3784                                 (cperl-calculate-indent))
3785                             (current-column))
3786                           (if (eq char-after ?\{)
3787                               cperl-continued-brace-offset 0)))
3788                    ;; This line starts a new statement.
3789                    ;; Position following last unclosed open.
3790                    (goto-char containing-sexp)
3791                    ;; Is line first statement after an open-brace?
3792                    (or
3793                     ;; If no, find that first statement and indent like
3794                     ;; it.  If the first statement begins with label, do
3795                     ;; not believe when the indentation of the label is too
3796                     ;; small.
3797                     (save-excursion
3798                       (forward-char 1)
3799                       (setq old-indent (current-indentation))
3800                       (let ((colon-line-end 0))
3801                         (while
3802                             (progn (skip-chars-forward " \t\n")
3803                                    (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]\\|=[a-zA-Z]"))
3804                           ;; Skip over comments and labels following openbrace.
3805                           (cond ((= (following-char) ?\#)
3806                                  (forward-line 1))
3807                                 ((= (following-char) ?\=)
3808                                  (goto-char
3809                                   (or (next-single-property-change (point) 'in-pod)
3810                                       (point-max)))) ; do not loop if no syntaxification
3811                                 ;; label:
3812                                 (t
3813                                  (save-excursion (end-of-line)
3814                                                  (setq colon-line-end (point)))
3815                                  (search-forward ":"))))
3816                         ;; The first following code counts
3817                         ;; if it is before the line we want to indent.
3818                         (and (< (point) indent-point)
3819                              (if (> colon-line-end (point)) ; After label
3820                                  (if (> (current-indentation)
3821                                         cperl-min-label-indent)
3822                                      (- (current-indentation) cperl-label-offset)
3823                                    ;; Do not believe: `max' is involved
3824                                    (+ old-indent cperl-indent-level))
3825                                (current-column)))))
3826                     ;; If no previous statement,
3827                     ;; indent it relative to line brace is on.
3828                     ;; For open brace in column zero, don't let statement
3829                     ;; start there too.  If cperl-indent-level is zero,
3830                     ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
3831                     ;; For open-braces not the first thing in a line,
3832                     ;; add in cperl-brace-imaginary-offset.
3833
3834                     ;; If first thing on a line:  ?????
3835                     (+ (if (and (bolp) (zerop cperl-indent-level))
3836                            (+ cperl-brace-offset cperl-continued-statement-offset)
3837                          cperl-indent-level)
3838                        (if (or is-block
3839                                (not delim)
3840                                (not (eq char-after ?\})))
3841                            0
3842                          ;; Now it is a hash reference
3843                          (+ cperl-indent-level cperl-close-paren-offset))
3844                        ;; Move back over whitespace before the openbrace.
3845                        ;; If openbrace is not first nonwhite thing on the line,
3846                        ;; add the cperl-brace-imaginary-offset.
3847                        (progn (skip-chars-backward " \t")
3848                               (if (bolp) 0 cperl-brace-imaginary-offset))
3849                        ;; If the openbrace is preceded by a parenthesized exp,
3850                        ;; move to the beginning of that;
3851                        ;; possibly a different line
3852                        (progn
3853                          (if (eq (preceding-char) ?\))
3854                              (forward-sexp -1))
3855                          ;; In the case it starts a subroutine, indent with
3856                          ;; respect to `sub', not with respect to the
3857                          ;; first thing on the line, say in the case of
3858                          ;; anonymous sub in a hash.
3859                          ;;
3860                          (skip-chars-backward " \t")
3861                          (if (and (eq (preceding-char) ?b)
3862                                   (progn
3863                                     (forward-sexp -1)
3864                                     (looking-at "sub\\>"))
3865                                   (setq old-indent
3866                                         (nth 1
3867                                              (parse-partial-sexp
3868                                               (save-excursion (beginning-of-line) (point))
3869                                               (point)))))
3870                              (progn (goto-char (1+ old-indent))
3871                                     (skip-chars-forward " \t")
3872                                     (current-column))
3873                            ;; Get initial indentation of the line we are on.
3874                            ;; If line starts with label, calculate label indentation
3875                            (if (save-excursion
3876                                  (beginning-of-line)
3877                                  (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
3878                                (if (> (current-indentation) cperl-min-label-indent)
3879                                    (- (current-indentation) cperl-label-offset)
3880                                  ;; Do not move `parse-data', this should
3881                                  ;; be quick anyway:
3882                                  (cperl-calculate-indent))
3883                              (current-indentation))))))))))))))
3884
3885 (defvar cperl-indent-alist
3886   '((string nil)
3887     (comment nil)
3888     (toplevel 0)
3889     (toplevel-after-parenth 2)
3890     (toplevel-continued 2)
3891     (expression 1))
3892   "Alist of indentation rules for CPerl mode.
3893 The values mean:
3894   nil: do not indent;
3895   number: add this amount of indentation.
3896
3897 Not finished, not used.")
3898
3899 (defun cperl-where-am-i (&optional parse-start start-state)
3900   ;; Unfinished
3901   "Return a list of lists ((TYPE POS)...) of good points before the point.
3902 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'.
3903
3904 Not finished, not used."
3905   (save-excursion
3906     (let* ((start-point (point))
3907            (s-s (cperl-get-state))
3908            (start (nth 0 s-s))
3909            (state (nth 1 s-s))
3910            (prestart (nth 3 s-s))
3911            (containing-sexp (car (cdr state)))
3912            (case-fold-search nil)
3913            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
3914       (cond ((nth 3 state)              ; In string
3915              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
3916             ((nth 4 state)              ; In comment
3917              (setq res (cons '(comment) res)))
3918             ((null containing-sexp)
3919              ;; Line is at top level.
3920              ;; Indent like the previous top level line
3921              ;; unless that ends in a closeparen without semicolon,
3922              ;; in which case this line is the first argument decl.
3923              (cperl-backward-to-noncomment (or parse-start (point-min)))
3924              ;;(skip-chars-backward " \t\f\n")
3925              (cond
3926               ((or (bobp)
3927                    (memq (preceding-char) (append ";}" nil)))
3928                (setq res (cons (list 'toplevel start) res)))
3929               ((eq (preceding-char) ?\) )
3930                (setq res (cons (list 'toplevel-after-parenth start) res)))
3931               (t
3932                (setq res (cons (list 'toplevel-continued start) res)))))
3933             ((/= (char-after containing-sexp) ?{)
3934              ;; line is expression, not statement:
3935              ;; indent to just after the surrounding open.
3936              ;; skip blanks if we do not close the expression.
3937              (setq res (cons (list 'expression-blanks
3938                                    (progn
3939                                      (goto-char (1+ containing-sexp))
3940                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
3941                                          (skip-chars-forward " \t"))
3942                                      (point)))
3943                              (cons (list 'expression containing-sexp) res))))
3944             ((progn
3945                ;; Containing-expr starts with \{.  Check whether it is a hash.
3946                (goto-char containing-sexp)
3947                (not (cperl-block-p)))
3948              (setq res (cons (list 'expression-blanks
3949                                    (progn
3950                                      (goto-char (1+ containing-sexp))
3951                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
3952                                          (skip-chars-forward " \t"))
3953                                      (point)))
3954                              (cons (list 'expression containing-sexp) res))))
3955             (t
3956              ;; Statement level.
3957              (setq res (cons (list 'in-block containing-sexp) res))
3958              ;; Is it a continuation or a new statement?
3959              ;; Find previous non-comment character.
3960              (cperl-backward-to-noncomment containing-sexp)
3961              ;; Back up over label lines, since they don't
3962              ;; affect whether our line is a continuation.
3963              ;; Back up comma-delimited lines too ?????
3964              (while (or (eq (preceding-char) ?\,)
3965                         (save-excursion (cperl-after-label)))
3966                (if (eq (preceding-char) ?\,)
3967                    ;; Will go to beginning of line, essentially
3968                    ;; Will ignore embedded sexpr XXXX.
3969                    (cperl-backward-to-start-of-continued-exp containing-sexp))
3970                (beginning-of-line)
3971                (cperl-backward-to-noncomment containing-sexp))
3972              ;; Now we get the answer.
3973              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
3974                  ;; This line is continuation of preceding line's statement.
3975                  (list (list 'statement-continued containing-sexp))
3976                ;; This line starts a new statement.
3977                ;; Position following last unclosed open.
3978                (goto-char containing-sexp)
3979                ;; Is line first statement after an open-brace?
3980                (or
3981                 ;; If no, find that first statement and indent like
3982                 ;; it.  If the first statement begins with label, do
3983                 ;; not believe when the indentation of the label is too
3984                 ;; small.
3985                 (save-excursion
3986                   (forward-char 1)
3987                   (let ((colon-line-end 0))
3988                     (while (progn (skip-chars-forward " \t\n" start-point)
3989                                   (and (< (point) start-point)
3990                                        (looking-at
3991                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
3992                       ;; Skip over comments and labels following openbrace.
3993                       (cond ((= (following-char) ?\#)
3994                              ;;(forward-line 1)
3995                              (end-of-line))
3996                             ;; label:
3997                             (t
3998                              (save-excursion (end-of-line)
3999                                              (setq colon-line-end (point)))
4000                              (search-forward ":"))))
4001                     ;; Now at the point, after label, or at start
4002                     ;; of first statement in the block.
4003                     (and (< (point) start-point)
4004                          (if (> colon-line-end (point))
4005                              ;; Before statement after label
4006                              (if (> (current-indentation)
4007                                     cperl-min-label-indent)
4008                                  (list (list 'label-in-block (point)))
4009                                ;; Do not believe: `max' is involved
4010                                (list
4011                                 (list 'label-in-block-min-indent (point))))
4012                            ;; Before statement
4013                            (list 'statement-in-block (point))))))
4014                 ;; If no previous statement,
4015                 ;; indent it relative to line brace is on.
4016                 ;; For open brace in column zero, don't let statement
4017                 ;; start there too.  If cperl-indent-level is zero,
4018                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
4019                 ;; For open-braces not the first thing in a line,
4020                 ;; add in cperl-brace-imaginary-offset.
4021
4022                 ;; If first thing on a line:  ?????
4023                 (+ (if (and (bolp) (zerop cperl-indent-level))
4024                        (+ cperl-brace-offset cperl-continued-statement-offset)
4025                      cperl-indent-level)
4026                    ;; Move back over whitespace before the openbrace.
4027                    ;; If openbrace is not first nonwhite thing on the line,
4028                    ;; add the cperl-brace-imaginary-offset.
4029                    (progn (skip-chars-backward " \t")
4030                           (if (bolp) 0 cperl-brace-imaginary-offset))
4031                    ;; If the openbrace is preceded by a parenthesized exp,
4032                    ;; move to the beginning of that;
4033                    ;; possibly a different line
4034                    (progn
4035                      (if (eq (preceding-char) ?\))
4036                          (forward-sexp -1))
4037                      ;; Get initial indentation of the line we are on.
4038                      ;; If line starts with label, calculate label indentation
4039                      (if (save-excursion
4040                            (beginning-of-line)
4041                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
4042                          (if (> (current-indentation) cperl-min-label-indent)
4043                              (- (current-indentation) cperl-label-offset)
4044                            (cperl-calculate-indent))
4045                        (current-indentation))))))))
4046       res)))
4047
4048 (defun cperl-calculate-indent-within-comment ()
4049   "Return the indentation amount for line, assuming that
4050 the current line is to be regarded as part of a block comment."
4051   (let (end star-start)
4052     (save-excursion
4053       (beginning-of-line)
4054       (skip-chars-forward " \t")
4055       (setq end (point))
4056       (and (= (following-char) ?#)
4057            (forward-line -1)
4058            (cperl-to-comment-or-eol)
4059            (setq end (point)))
4060       (goto-char end)
4061       (current-column))))
4062
4063
4064 (defun cperl-to-comment-or-eol ()
4065   "Go to position before comment on the current line, or to end of line.
4066 Returns true if comment is found."
4067   (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
4068     (beginning-of-line)
4069     (if (or
4070          (eq (get-text-property (point) 'syntax-type) 'pod)
4071          (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t))
4072         (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
4073       ;; Else
4074       (while (not stop-in)
4075         (setq state (parse-partial-sexp (point) lim nil nil nil t))
4076                                         ; stop at comment
4077         ;; If fails (beginning-of-line inside sexp), then contains not-comment
4078         (if (nth 4 state)               ; After `#';
4079                                         ; (nth 2 state) can be
4080                                         ; beginning of m,s,qq and so
4081                                         ; on
4082             (if (nth 2 state)
4083                 (progn
4084                   (setq cpoint (point))
4085                   (goto-char (nth 2 state))
4086                   (cond
4087                    ((looking-at "\\(s\\|tr\\)\\>")
4088                     (or (re-search-forward
4089                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
4090                          lim 'move)
4091                         (setq stop-in t)))
4092                    ((looking-at "\\(m\\|q\\([qxwr]\\)?\\)\\>")
4093                     (or (re-search-forward
4094                          "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
4095                          lim 'move)
4096                         (setq stop-in t)))
4097                    (t                   ; It was fair comment
4098                     (setq stop-in t)    ; Finish
4099                     (goto-char (1- cpoint)))))
4100               (setq stop-in t)          ; Finish
4101               (forward-char -1))
4102           (setq stop-in t)))            ; Finish 
4103       (nth 4 state))))
4104
4105 (defsubst cperl-1- (p)
4106   (max (point-min) (1- p)))
4107
4108 (defsubst cperl-1+ (p)
4109   (min (point-max) (1+ p)))
4110
4111 (defsubst cperl-modify-syntax-type (at how)
4112   (if (< at (point-max))
4113       (progn
4114         (put-text-property at (1+ at) 'syntax-table how)
4115         (put-text-property at (1+ at) 'rear-nonsticky t))))
4116
4117 (defun cperl-protect-defun-start (s e)
4118   ;; C code looks for "^\\s(" to skip comment backward in "hard" situations
4119   (save-excursion
4120     (goto-char s)
4121     (while (re-search-forward "^\\s(" e 'to-end)
4122       (put-text-property (1- (point)) (point) 'syntax-table cperl-st-punct))))
4123
4124 (defun cperl-commentify (bb e string &optional noface)
4125   (if cperl-use-syntax-table-text-property
4126       (if (eq noface 'n)                ; Only immediate
4127           nil
4128         ;; We suppose that e is _after_ the end of construction, as after eol.
4129         (setq string (if string cperl-st-sfence cperl-st-cfence))
4130         (if (> bb (- e 2))
4131             ;; one-char string/comment?!
4132             (cperl-modify-syntax-type bb cperl-st-punct)
4133           (cperl-modify-syntax-type bb string)
4134           (cperl-modify-syntax-type (1- e) string))
4135         (if (and (eq string cperl-st-sfence) (> (- e 2) bb))
4136             (put-text-property (1+ bb) (1- e)
4137                                'syntax-table cperl-string-syntax-table))
4138         (cperl-protect-defun-start bb e))
4139     ;; Fontify
4140     (or noface
4141         (not cperl-pod-here-fontify)
4142         (put-text-property bb e 'face (if string 'font-lock-string-face
4143                                         'font-lock-comment-face)))))
4144
4145 (defvar cperl-starters '(( ?\( . ?\) )
4146                          ( ?\[ . ?\] )
4147                          ( ?\{ . ?\} )
4148                          ( ?\< . ?\> )))
4149
4150 (defun cperl-forward-re (lim end is-2arg set-st st-l err-l argument
4151                              &optional ostart oend)
4152   ;; Works *before* syntax recognition is done
4153   ;; May modify syntax-type text property if the situation is too hard
4154   (let (b starter ender st i i2 go-forward reset-st)
4155     (skip-chars-forward " \t")
4156     ;; ender means matching-char matcher.
4157     (setq b (point)
4158           starter (if (eobp) 0 (char-after b))
4159           ender (cdr (assoc starter cperl-starters)))
4160     ;; What if starter == ?\\  ????
4161     (if set-st
4162         (if (car st-l)
4163             (setq st (car st-l))
4164           (setcar st-l (make-syntax-table))
4165           (setq i 0 st (car st-l))
4166           (while (< i 256)
4167             (modify-syntax-entry i "." st)
4168             (setq i (1+ i)))
4169           (modify-syntax-entry ?\\ "\\" st)))
4170     (setq set-st t)
4171     ;; Whether we have an intermediate point
4172     (setq i nil)
4173     ;; Prepare the syntax table:
4174     (and set-st
4175          (if (not ender)                ; m/blah/, s/x//, s/x/y/
4176              (modify-syntax-entry starter "$" st)
4177            (modify-syntax-entry starter (concat "(" (list ender)) st)
4178            (modify-syntax-entry ender  (concat ")" (list starter)) st)))
4179     (condition-case bb
4180         (progn
4181           ;; We use `$' syntax class to find matching stuff, but $$
4182           ;; is recognized the same as $, so we need to check this manually.
4183           (if (and (eq starter (char-after (cperl-1+ b)))
4184                    (not ender))
4185               ;; $ has TeXish matching rules, so $$ equiv $...
4186               (forward-char 2)
4187             (setq reset-st (syntax-table))
4188             (set-syntax-table st)
4189             (forward-sexp 1)
4190             (if (<= (point) (1+ b))
4191                 (error "Unfinished regular expression"))
4192             (set-syntax-table reset-st)
4193             (setq reset-st nil)
4194             ;; Now the problem is with m;blah;;
4195             (and (not ender)
4196                  (eq (preceding-char)
4197                      (char-after (- (point) 2)))
4198                  (save-excursion
4199                    (forward-char -2)
4200                    (= 0 (% (skip-chars-backward "\\\\") 2)))
4201                  (forward-char -1)))
4202           ;; Now we are after the first part.
4203           (and is-2arg                  ; Have trailing part
4204                (not ender)
4205                (eq (following-char) starter) ; Empty trailing part
4206                (progn
4207                  (or (eq (char-syntax (following-char)) ?.)
4208                      ;; Make trailing letter into punctuation
4209                      (cperl-modify-syntax-type (point) cperl-st-punct))
4210                  (setq is-2arg nil go-forward t))) ; Ignore the tail
4211           (if is-2arg                   ; Not number => have second part
4212               (progn
4213                 (setq i (point) i2 i)
4214                 (if ender
4215                     (if (memq (following-char) '(?\  ?\t ?\n ?\f))
4216                         (progn
4217                           (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4218                               (goto-char (match-end 0))
4219                             (skip-chars-forward " \t\n\f"))
4220                           (setq i2 (point))))
4221                   (forward-char -1))
4222                 (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4223                 (if ender (modify-syntax-entry ender "." st))
4224                 (setq set-st nil)
4225                 (setq ender (cperl-forward-re lim end nil t st-l err-l
4226                                               argument starter ender)
4227                       ender (nth 2 ender)))))
4228       (error (goto-char lim)
4229              (setq set-st nil)
4230              (if reset-st
4231                  (set-syntax-table reset-st))
4232              (or end
4233                  (message
4234                   "End of `%s%s%c ... %c' string/RE not found: %s"
4235                   argument
4236                   (if ostart (format "%c ... %c" ostart (or oend ostart)) "")
4237                   starter (or ender starter) bb)
4238                  (or (car err-l) (setcar err-l b)))))
4239     (if set-st
4240         (progn
4241           (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
4242           (if ender (modify-syntax-entry ender "." st))))
4243     ;; i: have 2 args, after end of the first arg
4244     ;; i2: start of the second arg, if any (before delim iff `ender').
4245     ;; ender: the last arg bounded by parens-like chars, the second one of them
4246     ;; starter: the starting delimiter of the first arg
4247     ;; go-forward: has 2 args, and the second part is empty
4248     (list i i2 ender starter go-forward)))
4249
4250 (defvar font-lock-string-face)
4251 ;;(defvar font-lock-reference-face)
4252 (defvar font-lock-constant-face)
4253 (defsubst cperl-postpone-fontification (b e type val &optional now)
4254   ;; Do after syntactic fontification?
4255   (if cperl-syntaxify-by-font-lock
4256       (or now (put-text-property b e 'cperl-postpone (cons type val)))
4257     (put-text-property b e type val)))
4258
4259 ;;; Here is how the global structures (those which cannot be
4260 ;;; recognized locally) are marked:
4261 ;;      a) PODs:
4262 ;;              Start-to-end is marked `in-pod' ==> t
4263 ;;              Each non-literal part is marked `syntax-type' ==> `pod'
4264 ;;              Each literal part is marked `syntax-type' ==> `in-pod'
4265 ;;      b) HEREs:
4266 ;;              Start-to-end is marked `here-doc-group' ==> t
4267 ;;              The body is marked `syntax-type' ==> `here-doc'
4268 ;;              The delimiter is marked `syntax-type' ==> `here-doc-delim'
4269 ;;      c) FORMATs:
4270 ;;              First line (to =) marked `first-format-line' ==> t
4271 ;;              After-this--to-end is marked `syntax-type' ==> `format'
4272 ;;      d) 'Q'uoted string:
4273 ;;              part between markers inclusive is marked `syntax-type' ==> `string'
4274 ;;              part between `q' and the first marker is marked `syntax-type' ==> `prestring'
4275
4276 (defun cperl-unwind-to-safe (before &optional end)
4277   ;; if BEFORE, go to the previous start-of-line on each step of unwinding
4278   (let ((pos (point)) opos)
4279     (setq opos pos)
4280     (while (and pos (get-text-property pos 'syntax-type))
4281       (setq pos (previous-single-property-change pos 'syntax-type))
4282       (if pos
4283           (if before
4284               (progn
4285                 (goto-char (cperl-1- pos))
4286                 (beginning-of-line)
4287                 (setq pos (point)))
4288             (goto-char (setq pos (cperl-1- pos))))
4289         ;; Up to the start
4290         (goto-char (point-min))))
4291     ;; Skip empty lines
4292     (and (looking-at "\n*=")
4293          (/= 0 (skip-chars-backward "\n"))
4294          (forward-char))
4295     (setq pos (point))
4296     (if end
4297         ;; Do the same for end, going small steps
4298         (progn
4299           (while (and end (get-text-property end 'syntax-type))
4300             (setq pos end
4301                   end (next-single-property-change end 'syntax-type)))
4302           (or end pos)))))
4303
4304 (defvar cperl-nonoverridable-face)
4305 (defvar font-lock-function-name-face)
4306 (defvar font-lock-comment-face)
4307
4308 (defun cperl-find-pods-heres (&optional min max non-inter end ignore-max)
4309   "Scans the buffer for hard-to-parse Perl constructions.
4310 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify
4311 the sections using `cperl-pod-head-face', `cperl-pod-face',
4312 `cperl-here-face'."
4313   (interactive)
4314   (or min (setq min (point-min)
4315                 cperl-syntax-state nil
4316                 cperl-syntax-done-to min))
4317   (or max (setq max (point-max)))
4318   (let* ((cperl-pod-here-fontify (eval cperl-pod-here-fontify)) go tmpend
4319          face head-face here-face b e bb tag qtag b1 e1 argument i c tail tb
4320          is-REx is-x-REx REx-comment-start REx-comment-end was-comment i2
4321          (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
4322          (modified (buffer-modified-p))
4323          (after-change-functions nil)
4324          (use-syntax-state (and cperl-syntax-state
4325                                 (>= min (car cperl-syntax-state))))
4326          (state-point (if use-syntax-state
4327                           (car cperl-syntax-state)
4328                         (point-min)))
4329          (state (if use-syntax-state
4330                     (cdr cperl-syntax-state)))
4331          ;; (st-l '(nil)) (err-l '(nil)) ; Would overwrite - propagates from a function call to a function call!
4332          (st-l (list nil)) (err-l (list nil))
4333          ;; Somehow font-lock may be not loaded yet...
4334          (font-lock-string-face (if (boundp 'font-lock-string-face)
4335                                     font-lock-string-face
4336                                   'font-lock-string-face))
4337          (font-lock-constant-face (if (boundp 'font-lock-constant-face)
4338                                       font-lock-constant-face
4339                                     'font-lock-constant-face))
4340          (font-lock-function-name-face
4341           (if (boundp 'font-lock-function-name-face)
4342               font-lock-function-name-face
4343             'font-lock-function-name-face))
4344          (font-lock-comment-face
4345           (if (boundp 'font-lock-comment-face)
4346               font-lock-comment-face
4347             'font-lock-comment-face))
4348          (cperl-nonoverridable-face
4349           (if (boundp 'cperl-nonoverridable-face)
4350               cperl-nonoverridable-face
4351             'cperl-nonoverridable-face))
4352          (stop-point (if ignore-max
4353                          (point-max)
4354                        max))
4355          (search
4356           (concat
4357            "\\(\\`\n?\\|^\n\\)="
4358            "\\|"
4359            ;; One extra () before this:
4360            "<<"
4361            "\\("                        ; 1 + 1
4362            ;; First variant "BLAH" or just ``.
4363            "[ \t]*"                     ; Yes, whitespace is allowed!
4364            "\\([\"'`]\\)"               ; 2 + 1 = 3
4365            "\\([^\"'`\n]*\\)"           ; 3 + 1
4366            "\\3"
4367            "\\|"
4368            ;; Second variant: Identifier or \ID (same as 'ID') or empty
4369            "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
4370            ;; Do not have <<= or << 30 or <<30 or << $blah.
4371            ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
4372            "\\(\\)"             ; To preserve count of pars :-( 6 + 1
4373            "\\)"
4374            "\\|"
4375            ;; 1+6 extra () before this:
4376            "^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
4377            (if cperl-use-syntax-table-text-property
4378                (concat
4379                 "\\|"
4380                 ;; 1+6+2=9 extra () before this:
4381                 "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>"
4382                 "\\|"
4383                 ;; 1+6+2+1=10 extra () before this:
4384                 "\\([?/<]\\)"   ; /blah/ or ?blah? or <file*glob>
4385                 "\\|"
4386                 ;; 1+6+2+1+1=11 extra () before this:
4387                 "\\<sub\\>[ \t]*\\([a-zA-Z_:'0-9]+[ \t]*\\)?\\(([^()]*)\\)"
4388                 "\\|"
4389                 ;; 1+6+2+1+1+2=13 extra () before this:
4390                 "\\$\\(['{]\\)"
4391                 "\\|"
4392                 ;; 1+6+2+1+1+2+1=14 extra () before this:
4393                 "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'"
4394                 ;; 1+6+2+1+1+2+1+1=15 extra () before this:
4395                 "\\|"
4396                 "__\\(END\\|DATA\\)__"
4397                 ;; 1+6+2+1+1+2+1+1+1=16 extra () before this:
4398                 "\\|"
4399                 "\\\\\\(['`\"($]\\)")
4400              ""))))
4401     (unwind-protect
4402         (progn
4403           (save-excursion
4404             (or non-inter
4405                 (message "Scanning for \"hard\" Perl constructions..."))
4406             (and cperl-pod-here-fontify
4407                  ;; We had evals here, do not know why...
4408                  (setq face cperl-pod-face
4409                        head-face cperl-pod-head-face
4410                        here-face cperl-here-face))
4411             (remove-text-properties min max
4412                                     '(syntax-type t in-pod t syntax-table t
4413                                                   cperl-postpone t
4414                                                   syntax-subtype t
4415                                                   rear-nonsticky t
4416                                                   here-doc-group t
4417                                                   first-format-line t
4418                                                   indentable t))
4419             ;; Need to remove face as well...
4420             (goto-char min)
4421             (and (eq system-type 'emx)
4422                  (looking-at "extproc[ \t]") ; Analogue of #!
4423                  (cperl-commentify min
4424                                    (save-excursion (end-of-line) (point))
4425                                    nil))
4426             (while (and
4427                     (< (point) max)
4428                     (re-search-forward search max t))
4429               (setq tmpend nil)         ; Valid for most cases
4430               (cond
4431                ((match-beginning 1)     ; POD section
4432                 ;;  "\\(\\`\n?\\|^\n\\)="
4433                 (if (looking-at "cut\\>")
4434                     (if ignore-max
4435                         nil             ; Doing a chunk only
4436                       (message "=cut is not preceded by a POD section")
4437                       (or (car err-l) (setcar err-l (point))))
4438                   (beginning-of-line)
4439
4440                   (setq b (point)
4441                         bb b
4442                         tb (match-beginning 0)
4443                         b1 nil)         ; error condition
4444                   ;; We do not search to max, since we may be called from
4445                   ;; some hook of fontification, and max is random
4446                   (or (re-search-forward "^\n=cut\\>" stop-point 'toend)
4447                       (progn
4448                         (goto-char b)
4449                         (if (re-search-forward "\n=cut\\>" stop-point 'toend)
4450                             (progn
4451                               (message "=cut is not preceded by an empty line")
4452                               (setq b1 t)
4453                               (or (car err-l) (setcar err-l b))))))
4454                   (beginning-of-line 2) ; An empty line after =cut is not POD!
4455                   (setq e (point))
4456                   (and (> e max)
4457                        (progn
4458                          (remove-text-properties
4459                           max e '(syntax-type t in-pod t syntax-table t
4460                                               cperl-postpone t
4461                                               syntax-subtype t
4462                                               here-doc-group t
4463                                               rear-nonsticky t
4464                                               first-format-line t
4465                                               indentable t))
4466                          (setq tmpend tb)))
4467                   (put-text-property b e 'in-pod t)
4468                   (put-text-property b e 'syntax-type 'in-pod)
4469                   (goto-char b)
4470                   (while (re-search-forward "\n\n[ \t]" e t)
4471                     ;; We start 'pod 1 char earlier to include the preceding line
4472                     (beginning-of-line)
4473                     (put-text-property (cperl-1- b) (point) 'syntax-type 'pod)
4474                     (cperl-put-do-not-fontify b (point) t)
4475                     ;; mark the non-literal parts as PODs
4476                     (if cperl-pod-here-fontify
4477                         (cperl-postpone-fontification b (point) 'face face t))
4478                     (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
4479                     (beginning-of-line)
4480                     (setq b (point)))
4481                   (put-text-property (cperl-1- (point)) e 'syntax-type 'pod)
4482                   (cperl-put-do-not-fontify (point) e t)
4483                   (if cperl-pod-here-fontify
4484                       (progn
4485                         ;; mark the non-literal parts as PODs
4486                         (cperl-postpone-fontification (point) e 'face face t)
4487                         (goto-char bb)
4488                         (if (looking-at
4489                              "=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
4490                             ;; mark the headers
4491                             (cperl-postpone-fontification
4492                              (match-beginning 1) (match-end 1)
4493                              'face head-face))
4494                         (while (re-search-forward
4495                                 ;; One paragraph
4496                                 "^\n=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
4497                                 e 'toend)
4498                           ;; mark the headers
4499                           (cperl-postpone-fontification
4500                            (match-beginning 1) (match-end 1)
4501                            'face head-face))))
4502                   (cperl-commentify bb e nil)
4503                   (goto-char e)
4504                   (or (eq e (point-max))
4505                       (forward-char -1)))) ; Prepare for immediate POD start.
4506                ;; Here document
4507                ;; We do only one here-per-line
4508                ;; ;; One extra () before this:
4509                ;;"<<"
4510                ;;  "\\("                        ; 1 + 1
4511                ;;  ;; First variant "BLAH" or just ``.
4512                ;;     "[ \t]*"                  ; Yes, whitespace is allowed!
4513                ;;     "\\([\"'`]\\)"    ; 2 + 1
4514                ;;     "\\([^\"'`\n]*\\)"        ; 3 + 1
4515                ;;     "\\3"
4516                ;;  "\\|"
4517                ;;  ;; Second variant: Identifier or \ID or empty
4518                ;;    "\\\\?\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)" ; 4 + 1, 5 + 1
4519                ;;    ;; Do not have <<= or << 30 or <<30 or << $blah.
4520                ;;    ;; "\\([^= \t0-9$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)" ; 6 + 1
4521                ;;    "\\(\\)"           ; To preserve count of pars :-( 6 + 1
4522                ;;  "\\)"
4523                ((match-beginning 2)     ; 1 + 1
4524                 ;; Abort in comment:
4525                 (setq b (point))
4526                 (setq state (parse-partial-sexp state-point b nil nil state)
4527                       state-point b
4528                       tb (match-beginning 0)
4529                       i (or (nth 3 state) (nth 4 state)))
4530                 (if i
4531                     (setq c t)
4532                   (setq c (and
4533                            (match-beginning 5)
4534                            (not (match-beginning 6)) ; Empty
4535                            (looking-at
4536                             "[ \t]*[=0-9$@%&(]"))))
4537                 (if c                   ; Not here-doc
4538                     nil                 ; Skip it.
4539                   (if (match-beginning 5) ;4 + 1
4540                       (setq b1 (match-beginning 5) ; 4 + 1
4541                             e1 (match-end 5)) ; 4 + 1
4542                     (setq b1 (match-beginning 4) ; 3 + 1
4543                           e1 (match-end 4))) ; 3 + 1
4544                   (setq tag (buffer-substring b1 e1)
4545                         qtag (regexp-quote tag))
4546                   (cond (cperl-pod-here-fontify
4547                          ;; Highlight the starting delimiter
4548                          (cperl-postpone-fontification b1 e1 'face font-lock-constant-face)
4549                          (cperl-put-do-not-fontify b1 e1 t)))
4550                   (forward-line)
4551                   (setq b (point))
4552                   ;; We do not search to max, since we may be called from
4553                   ;; some hook of fontification, and max is random
4554                   (or (and (re-search-forward (concat "^" qtag "$")
4555                                               stop-point 'toend)
4556                            (eq (following-char) ?\n))
4557                     (progn              ; Pretend we matched at the end
4558                       (goto-char (point-max))
4559                       (re-search-forward "\\'")
4560                       (message "End of here-document `%s' not found." tag)
4561                       (or (car err-l) (setcar err-l b))))
4562                   (if cperl-pod-here-fontify
4563                       (progn
4564                         ;; Highlight the ending delimiter
4565                         (cperl-postpone-fontification (match-beginning 0) (match-end 0)
4566                                                       'face font-lock-constant-face)
4567                         (cperl-put-do-not-fontify b (match-end 0) t)
4568                         ;; Highlight the HERE-DOC
4569                         (cperl-postpone-fontification b (match-beginning 0)
4570                                                       'face here-face)))
4571                   (setq e1 (cperl-1+ (match-end 0)))
4572                   (put-text-property b (match-beginning 0)
4573                                      'syntax-type 'here-doc)
4574                   (put-text-property (match-beginning 0) e1
4575                                      'syntax-type 'here-doc-delim)
4576                   (put-text-property b e1
4577                                      'here-doc-group t)
4578                   (cperl-commentify b e1 nil)
4579                   (cperl-put-do-not-fontify b (match-end 0) t)
4580                   (if (> e1 max)
4581                       (setq tmpend tb))))
4582                ;; format
4583                ((match-beginning 8)
4584                 ;; 1+6=7 extra () before this:
4585                 ;;"^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
4586                 (setq b (point)
4587                       name (if (match-beginning 8) ; 7 + 1
4588                                (buffer-substring (match-beginning 8) ; 7 + 1
4589                                                  (match-end 8)) ; 7 + 1
4590                              "")
4591                       tb (match-beginning 0))
4592                 (setq argument nil)
4593                 (put-text-property (save-excursion
4594                                      (beginning-of-line)
4595                                      (point))
4596                                    b 'first-format-line 't)
4597                 (if cperl-pod-here-fontify
4598                     (while (and (eq (forward-line) 0)
4599                                 (not (looking-at "^[.;]$")))
4600                       (cond
4601                        ((looking-at "^#")) ; Skip comments
4602                        ((and argument   ; Skip argument multi-lines
4603                              (looking-at "^[ \t]*{"))
4604                         (forward-sexp 1)
4605                         (setq argument nil))
4606                        (argument        ; Skip argument lines
4607                         (setq argument nil))
4608                        (t               ; Format line
4609                         (setq b1 (point))
4610                         (setq argument (looking-at "^[^\n]*[@^]"))
4611                         (end-of-line)
4612                         ;; Highlight the format line
4613                         (cperl-postpone-fontification b1 (point)
4614                                                       'face font-lock-string-face)
4615                         (cperl-commentify b1 (point) nil)
4616                         (cperl-put-do-not-fontify b1 (point) t))))
4617                   ;; We do not search to max, since we may be called from
4618                   ;; some hook of fontification, and max is random
4619                   (re-search-forward "^[.;]$" stop-point 'toend))
4620                 (beginning-of-line)
4621                 (if (looking-at "^\\.$") ; ";" is not supported yet
4622                     (progn
4623                       ;; Highlight the ending delimiter
4624                       (cperl-postpone-fontification (point) (+ (point) 2)
4625                                                     'face font-lock-string-face)
4626                       (cperl-commentify (point) (+ (point) 2) nil)
4627                       (cperl-put-do-not-fontify (point) (+ (point) 2) t))
4628                   (message "End of format `%s' not found." name)
4629                   (or (car err-l) (setcar err-l b)))
4630                 (forward-line)
4631                 (if (> (point) max)
4632                     (setq tmpend tb))
4633                 (put-text-property b (point) 'syntax-type 'format))
4634                ;; Regexp:
4635                ((or (match-beginning 10) (match-beginning 11))
4636                 ;; 1+6+2=9 extra () before this:
4637                 ;; "\\<\\(q[wxqr]?\\|[msy]\\|tr\\)\\>"
4638                 ;; "\\|"
4639                 ;; "\\([?/<]\\)"        ; /blah/ or ?blah? or <file*glob>
4640                 (setq b1 (if (match-beginning 10) 10 11)
4641                       argument (buffer-substring
4642                                 (match-beginning b1) (match-end b1))
4643                       b (point)
4644                       i b
4645                       c (char-after (match-beginning b1))
4646                       bb (char-after (1- (match-beginning b1))) ; tmp holder
4647                       ;; bb == "Not a stringy"
4648                       bb (if (eq b1 10) ; user variables/whatever
4649                              (and (memq bb (append "$@%*#_:-&>" nil)) ; $#y)
4650                                   (cond ((eq bb ?-) (eq c ?s)) ; -s file test
4651                                         ((eq bb ?\:) ; $opt::s
4652                                          (eq (char-after
4653                                               (- (match-beginning b1) 2))
4654                                              ?\:))
4655                                         ((eq bb ?\>) ; $foo->s
4656                                          (eq (char-after
4657                                               (- (match-beginning b1) 2))
4658                                              ?\-))
4659                                         ((eq bb ?\&)
4660                                          (not (eq (char-after   ; &&m/blah/
4661                                                    (- (match-beginning b1) 2))
4662                                                   ?\&)))
4663                                         (t t)))
4664                            ;; <file> or <$file>
4665                            (and (eq c ?\<)
4666                                 ;; Do not stringify <FH>, <$fh> :
4667                                 (save-match-data
4668                                   (looking-at
4669                                    "\\$?\\([_a-zA-Z:][_a-zA-Z0-9:]*\\)?>"))))
4670                       tb (match-beginning 0))
4671                 (goto-char (match-beginning b1))
4672                 (cperl-backward-to-noncomment (point-min))
4673                 (or bb
4674                     (if (eq b1 11)      ; bare /blah/ or ?blah? or <foo>
4675                         (setq argument ""
4676                               b1 nil
4677                               bb        ; Not a regexp?
4678                               (progn
4679                                 (not
4680                                  ;; What is below: regexp-p?
4681                                  (and
4682                                   (or (memq (preceding-char)
4683                                             (append (if (memq c '(?\? ?\<))
4684                                                         ;; $a++ ? 1 : 2
4685                                                         "~{(=|&*!,;:"
4686                                                       "~{(=|&+-*!,;:") nil))
4687                                       (and (eq (preceding-char) ?\})
4688                                            (cperl-after-block-p (point-min)))
4689                                       (and (eq (char-syntax (preceding-char)) ?w)
4690                                            (progn
4691                                              (forward-sexp -1)
4692 ;;; After these keywords `/' starts a RE.  One should add all the
4693 ;;; functions/builtins which expect an argument, but ...
4694                                              (if (eq (preceding-char) ?-)
4695                                                  ;; -d ?foo? is a RE
4696                                                  (looking-at "[a-zA-Z]\\>")
4697                                                (and
4698                                                 (not (memq (preceding-char)
4699                                                            '(?$ ?@ ?& ?%)))
4700                                                 (looking-at
4701                                                  "\\(while\\|if\\|unless\\|until\\|and\\|or\\|not\\|xor\\|split\\|grep\\|map\\|print\\)\\>")))))
4702                                       (and (eq (preceding-char) ?.)
4703                                            (eq (char-after (- (point) 2)) ?.))
4704                                       (bobp))
4705                                   ;;  m|blah| ? foo : bar;
4706                                   (not
4707                                    (and (eq c ?\?)
4708                                         cperl-use-syntax-table-text-property
4709                                         (not (bobp))
4710                                         (progn
4711                                           (forward-char -1)
4712                                           (looking-at "\\s|")))))))
4713                               b (1- b))
4714                       ;; s y tr m
4715                       ;; Check for $a -> y
4716                       (setq b1 (preceding-char)
4717                             go (point))
4718                       (if (and (eq b1 ?>)
4719                                (eq (char-after (- go 2)) ?-))
4720                           ;; Not a regexp
4721                           (setq bb t))))
4722                 (or bb (setq state (parse-partial-sexp
4723                                     state-point b nil nil state)
4724                              state-point b))
4725                 (setq bb (or bb (nth 3 state) (nth 4 state)))
4726                 (goto-char b)
4727                 (or bb
4728                     (progn
4729                       (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4730                           (goto-char (match-end 0))
4731                         (skip-chars-forward " \t\n\f"))
4732                       (cond ((and (eq (following-char) ?\})
4733                                   (eq b1 ?\{))
4734                              ;; Check for $a[23]->{ s }, @{s} and *{s::foo}
4735                              (goto-char (1- go))
4736                              (skip-chars-backward " \t\n\f")
4737                              (if (memq (preceding-char) (append "$@%&*" nil))
4738                                  (setq bb t) ; @{y}
4739                                (condition-case nil
4740                                    (forward-sexp -1)
4741                                  (error nil)))
4742                              (if (or bb
4743                                      (looking-at ; $foo -> {s}
4744                                       "[$@]\\$*\\([a-zA-Z0-9_:]+\\|[^{]\\)\\([ \t\n]*->\\)?[ \t\n]*{")
4745                                      (and ; $foo[12] -> {s}
4746                                       (memq (following-char) '(?\{ ?\[))
4747                                       (progn
4748                                         (forward-sexp 1)
4749                                         (looking-at "\\([ \t\n]*->\\)?[ \t\n]*{"))))
4750                                  (setq bb t)
4751                                (goto-char b)))
4752                             ((and (eq (following-char) ?=)
4753                                   (eq (char-after (1+ (point))) ?\>))
4754                              ;; Check for { foo => 1, s => 2 }
4755                              ;; Apparently s=> is never a substitution...
4756                              (setq bb t))
4757                             ((and (eq (following-char) ?:)
4758                                   (eq b1 ?\{) ; Check for $ { s::bar }
4759                                   (looking-at "::[a-zA-Z0-9_:]*[ \t\n\f]*}")
4760                                   (progn 
4761                                     (goto-char (1- go))
4762                                     (skip-chars-backward " \t\n\f")
4763                                     (memq (preceding-char)
4764                                           (append "$@%&*" nil))))
4765                              (setq bb t)))))
4766                 (if bb
4767                     (goto-char i)
4768                   ;; Skip whitespace and comments...
4769                   (if (looking-at "[ \t\n\f]+\\(#[^\n]*\n[ \t\n\f]*\\)+")
4770                       (goto-char (match-end 0))
4771                     (skip-chars-forward " \t\n\f"))
4772                   (if (> (point) b)
4773                       (put-text-property b (point) 'syntax-type 'prestring))
4774                   ;; qtag means two-arg matcher, may be reset to
4775                   ;;   2 or 3 later if some special quoting is needed.
4776                   ;; e1 means matching-char matcher.
4777                   (setq b (point)
4778                         ;; has 2 args
4779                         i2 (string-match "^\\([sy]\\|tr\\)$" argument)
4780                         ;; We do not search to max, since we may be called from
4781                         ;; some hook of fontification, and max is random
4782                         i (cperl-forward-re stop-point end
4783                                             i2
4784                                             t st-l err-l argument)
4785                         ;; Note that if `go', then it is considered as 1-arg
4786                         b1 (nth 1 i)    ; start of the second part
4787                         tag (nth 2 i)   ; ender-char, true if second part
4788                                         ; is with matching chars []
4789                         go (nth 4 i)    ; There is a 1-char part after the end
4790                         i (car i)       ; intermediate point
4791                         e1 (point)      ; end
4792                         ;; Before end of the second part if non-matching: ///
4793                         tail (if (and i (not tag))
4794                                  (1- e1))
4795                         e (if i i e1)   ; end of the first part
4796                         qtag nil        ; need to preserve backslashitis
4797                         is-x-REx nil)   ; REx has //x modifier
4798                   ;; Commenting \\ is dangerous, what about ( ?
4799                   (and i tail
4800                        (eq (char-after i) ?\\)
4801                        (setq qtag t))
4802                   (if (looking-at "\\sw*x") ; qr//x
4803                       (setq is-x-REx t))
4804                   (if (null i)
4805                       ;; Considered as 1arg form
4806                       (progn
4807                         (cperl-commentify b (point) t)
4808                         (put-text-property b (point) 'syntax-type 'string)
4809                         (if (or is-x-REx
4810                                 ;; ignore other text properties:
4811                                 (string-match "^qw$" argument))
4812                             (put-text-property b (point) 'indentable t))
4813                         (and go
4814                              (setq e1 (cperl-1+ e1))
4815                              (or (eobp)
4816                                  (forward-char 1))))
4817                     (cperl-commentify b i t)
4818                     (if (looking-at "\\sw*e") ; s///e
4819                         (progn
4820                           (and
4821                            ;; silent:
4822                            (cperl-find-pods-heres b1 (1- (point)) t end)
4823                            ;; Error
4824                            (goto-char (1+ max)))
4825                           (if (and tag (eq (preceding-char) ?\>))
4826                               (progn
4827                                 (cperl-modify-syntax-type (1- (point)) cperl-st-ket)
4828                                 (cperl-modify-syntax-type i cperl-st-bra)))
4829                           (put-text-property b i 'syntax-type 'string)
4830                           (if is-x-REx
4831                               (put-text-property b i 'indentable t)))
4832                       (cperl-commentify b1 (point) t)
4833                       (put-text-property b (point) 'syntax-type 'string)
4834                       (if is-x-REx
4835                           (put-text-property b i 'indentable t))
4836                       (if qtag
4837                           (cperl-modify-syntax-type (1+ i) cperl-st-punct))
4838                       (setq tail nil)))
4839                   ;; Now: tail: if the second part is non-matching without ///e
4840                   (if (eq (char-syntax (following-char)) ?w)
4841                       (progn
4842                         (forward-word 1) ; skip modifiers s///s
4843                         (if tail (cperl-commentify tail (point) t))
4844                         (cperl-postpone-fontification
4845                          e1 (point) 'face 'cperl-nonoverridable-face)))
4846                   ;; Check whether it is m// which means "previous match"
4847                   ;; and highlight differently
4848                   (setq is-REx
4849                         (and (string-match "^\\([sm]?\\|qr\\)$" argument)
4850                              (or (not (= (length argument) 0))
4851                                  (not (eq c ?\<)))))
4852                   (if (and is-REx
4853                            (eq e (+ 2 b))
4854                            ;; split // *is* using zero-pattern
4855                            (save-excursion
4856                              (condition-case nil
4857                                  (progn
4858                                    (goto-char tb)
4859                                    (forward-sexp -1)
4860                                    (not (looking-at "split\\>")))
4861                                (error t))))
4862                       (cperl-postpone-fontification
4863                        b e 'face font-lock-function-name-face)
4864                     (if (or i2          ; Has 2 args
4865                             (and cperl-fontify-m-as-s
4866                                  (or
4867                                   (string-match "^\\(m\\|qr\\)$" argument)
4868                                   (and (eq 0 (length argument))
4869                                        (not (eq ?\< (char-after b)))))))
4870                         (progn
4871                           (cperl-postpone-fontification
4872                            b (cperl-1+ b) 'face font-lock-constant-face)
4873                           (cperl-postpone-fontification
4874                            (1- e) e 'face font-lock-constant-face)))
4875                     (if (and is-REx cperl-regexp-scan)
4876                         ;; Process RExen better
4877                         (save-excursion
4878                           (goto-char (1+ b))
4879                           (while
4880                               (and (< (point) e)
4881                                    (re-search-forward
4882                                     (if is-x-REx
4883                                         (if (eq (char-after b) ?\#)
4884                                             "\\((\\?\\\\#\\)\\|\\(\\\\#\\)"
4885                                           "\\((\\?#\\)\\|\\(#\\)")
4886                                       (if (eq (char-after b) ?\#)
4887                                           "\\((\\?\\\\#\\)"
4888                                         "\\((\\?#\\)"))
4889                                     (1- e) 'to-end))
4890                             (goto-char (match-beginning 0))
4891                             (setq REx-comment-start (point)
4892                                   was-comment t)
4893                             (if (save-excursion
4894                                   (and
4895                                    ;; XXX not working if outside delimiter is #
4896                                    (eq (preceding-char) ?\\)
4897                                    (= (% (skip-chars-backward "$\\\\") 2) -1)))
4898                                 ;; Not a comment, avoid loop:
4899                                 (progn (setq was-comment nil)
4900                                        (forward-char 1))
4901                               (if (match-beginning 2)
4902                                   (progn
4903                                     (beginning-of-line 2)
4904                                     (if (> (point) e)
4905                                         (goto-char (1- e))))
4906                                 ;; Works also if the outside delimiters are ().
4907                                 (or (search-forward ")" (1- e) 'toend)
4908                                     (message
4909                                      "Couldn't find end of (?#...)-comment in a REx, pos=%s"
4910                                      REx-comment-start))))
4911                             (if (>= (point) e)
4912                                 (goto-char (1- e)))
4913                             (if was-comment
4914                                 (progn
4915                                   (setq REx-comment-end (point))
4916                                   (cperl-commentify
4917                                    REx-comment-start REx-comment-end nil)
4918                                   (cperl-postpone-fontification
4919                                    REx-comment-start REx-comment-end
4920                                    'face font-lock-comment-face))))))
4921                     (if (and is-REx is-x-REx)
4922                         (put-text-property (1+ b) (1- e)
4923                                            'syntax-subtype 'x-REx)))
4924                   (if i2
4925                       (progn
4926                         (cperl-postpone-fontification
4927                          (1- e1) e1 'face font-lock-constant-face)
4928                         (if (assoc (char-after b) cperl-starters)
4929                             (cperl-postpone-fontification
4930                              b1 (1+ b1) 'face font-lock-constant-face))))
4931                   (if (> (point) max)
4932                       (setq tmpend tb))))
4933                ((match-beginning 13)    ; sub with prototypes
4934                 (setq b (match-beginning 0))
4935                 (if (memq (char-after (1- b))
4936                           '(?\$ ?\@ ?\% ?\& ?\*))
4937                     nil
4938                   (setq state (parse-partial-sexp
4939                                state-point b nil nil state)
4940                         state-point b)
4941                   (if (or (nth 3 state) (nth 4 state))
4942                       nil
4943                     ;; Mark as string
4944                     (cperl-commentify (match-beginning 13) (match-end 13) t))
4945                   (goto-char (match-end 0))))
4946                ;; 1+6+2+1+1+2=13 extra () before this:
4947                ;;    "\\$\\(['{]\\)"
4948                ((and (match-beginning 14)
4949                      (eq (preceding-char) ?\')) ; $'
4950                 (setq b (1- (point))
4951                       state (parse-partial-sexp
4952                              state-point (1- b) nil nil state)
4953                       state-point (1- b))
4954                 (if (nth 3 state)       ; in string
4955                     (cperl-modify-syntax-type (1- b) cperl-st-punct))
4956                 (goto-char (1+ b)))
4957                ;; 1+6+2+1+1+2=13 extra () before this:
4958                ;;    "\\$\\(['{]\\)"
4959                ((match-beginning 14)    ; ${
4960                 (setq bb (match-beginning 0))
4961                 (cperl-modify-syntax-type bb cperl-st-punct))
4962                ;; 1+6+2+1+1+2+1=14 extra () before this:
4963                ;;    "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'")
4964                ((match-beginning 15)    ; old $abc'efg syntax
4965                 (setq bb (match-end 0)
4966                       b (match-beginning 0)
4967                       state (parse-partial-sexp
4968                              state-point b nil nil state)
4969                       state-point b)
4970                 (if (nth 3 state)       ; in string
4971                     nil
4972                   (put-text-property (1- bb) bb 'syntax-table cperl-st-word))
4973                 (goto-char bb))
4974                ;; 1+6+2+1+1+2+1+1=15 extra () before this:
4975                ;; "__\\(END\\|DATA\\)__"
4976                ((match-beginning 16)    ; __END__, __DATA__
4977                 (setq bb (match-end 0)
4978                       b (match-beginning 0)
4979                       state (parse-partial-sexp
4980                              state-point b nil nil state)
4981                       state-point b)
4982                 (if (or (nth 3 state) (nth 4 state))
4983                     nil
4984                   ;; (put-text-property b (1+ bb) 'syntax-type 'pod) ; Cheat
4985                   (cperl-commentify b bb nil)
4986                   (setq end t))
4987                 (goto-char bb))
4988                ((match-beginning 17)    ; "\\\\\\(['`\"($]\\)"
4989                 ;; Trailing backslash ==> non-quoting outside string/comment
4990                 (setq bb (match-end 0)
4991                       b (match-beginning 0))
4992                 (goto-char b)
4993                 (skip-chars-backward "\\\\")
4994                 ;;;(setq i2 (= (% (skip-chars-backward "\\\\") 2) -1))
4995                 (setq state (parse-partial-sexp
4996                              state-point b nil nil state)
4997                       state-point b)
4998                 (if (or (nth 3 state) (nth 4 state) )
4999                     nil
5000                   (cperl-modify-syntax-type b cperl-st-punct))
5001                 (goto-char bb))
5002                (t (error "Error in regexp of the sniffer")))
5003               (if (> (point) stop-point)
5004                   (progn
5005                     (if end
5006                         (message "Garbage after __END__/__DATA__ ignored")
5007                       (message "Unbalanced syntax found while scanning")
5008                       (or (car err-l) (setcar err-l b)))
5009                     (goto-char stop-point))))
5010             (setq cperl-syntax-state (cons state-point state)
5011                   cperl-syntax-done-to (or tmpend (max (point) max))))
5012           (if (car err-l) (goto-char (car err-l))
5013             (or non-inter
5014                 (message "Scanning for \"hard\" Perl constructions... done"))))
5015       (and (buffer-modified-p)
5016            (not modified)
5017            (set-buffer-modified-p nil))
5018       (set-syntax-table cperl-mode-syntax-table))
5019     (car err-l)))
5020
5021 (defun cperl-backward-to-noncomment (lim)
5022   ;; Stops at lim or after non-whitespace that is not in comment
5023   (let (stop p pr)
5024     (while (and (not stop) (> (point) (or lim 1)))
5025       (skip-chars-backward " \t\n\f" lim)
5026       (setq p (point))
5027       (beginning-of-line)
5028       (if (memq (setq pr (get-text-property (point) 'syntax-type))
5029                 '(pod here-doc here-doc-delim))
5030           (cperl-unwind-to-safe nil)
5031       (or (looking-at "^[ \t]*\\(#\\|$\\)")
5032           (progn (cperl-to-comment-or-eol) (bolp))
5033           (progn
5034             (skip-chars-backward " \t")
5035             (if (< p (point)) (goto-char p))
5036             (setq stop t)))))))
5037
5038 (defun cperl-after-block-p (lim &optional pre-block)
5039   "Return true if the preceeding } ends a block or a following { starts one.
5040 Would not look before LIM.  If PRE-BLOCK is nil checks preceeding }.
5041 otherwise following {."
5042   ;; We suppose that the preceding char is }.
5043   (save-excursion
5044     (condition-case nil
5045         (progn
5046           (or pre-block (forward-sexp -1))
5047           (cperl-backward-to-noncomment lim)
5048           (or (eq (point) lim)
5049               (eq (preceding-char) ?\) ) ; if () {}    sub f () {}
5050               (if (eq (char-syntax (preceding-char)) ?w) ; else {}
5051                   (save-excursion
5052                     (forward-sexp -1)
5053                     (or (looking-at "\\(else\\|continue\\|grep\\|map\\|BEGIN\\|END\\|CHECK\\|INIT\\)\\>")
5054                         ;; sub f {}
5055                         (progn
5056                           (cperl-backward-to-noncomment lim)
5057                           (and (eq (char-syntax (preceding-char)) ?w)
5058                                (progn
5059                                  (forward-sexp -1)
5060                                  (looking-at "sub\\>"))))))
5061                 (cperl-after-expr-p lim))))
5062       (error nil))))
5063
5064 (defun cperl-after-expr-p (&optional lim chars test)
5065   "Return true if the position is good for start of expression.
5066 TEST is the expression to evaluate at the found position.  If absent,
5067 CHARS is a string that contains good characters to have before us (however,
5068 `}' is treated \"smartly\" if it is not in the list)."
5069   (let ((lim (or lim (point-min)))
5070         stop p pr)
5071     (cperl-update-syntaxification (point) (point))
5072     (save-excursion
5073       (while (and (not stop) (> (point) lim))
5074         (skip-chars-backward " \t\n\f" lim)
5075         (setq p (point))
5076         (beginning-of-line)
5077         ;;(memq (setq pr (get-text-property (point) 'syntax-type))
5078         ;;      '(pod here-doc here-doc-delim))
5079         (if (get-text-property (point) 'here-doc-group)
5080             (progn
5081               (goto-char
5082                (previous-single-property-change (point) 'here-doc-group))
5083               (beginning-of-line 0)))
5084         (if (get-text-property (point) 'in-pod)
5085             (progn
5086               (goto-char
5087                (previous-single-property-change (point) 'in-pod))
5088               (beginning-of-line 0)))
5089         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
5090           ;; Else: last iteration, or a label
5091           (cperl-to-comment-or-eol)     ; Will not move past "." after a format
5092           (skip-chars-backward " \t")
5093           (if (< p (point)) (goto-char p))
5094           (setq p (point))
5095           (if (and (eq (preceding-char) ?:)
5096                    (progn
5097                      (forward-char -1)
5098                      (skip-chars-backward " \t\n\f" lim)
5099                      (eq (char-syntax (preceding-char)) ?w)))
5100               (forward-sexp -1)         ; Possibly label.  Skip it
5101             (goto-char p)
5102             (setq stop t))))
5103       (or (bobp)                        ; ???? Needed
5104           (eq (point) lim)
5105           (looking-at "[ \t]*__\\(END\\|DATA\\)__") ; After this anything goes
5106           (progn
5107             (if test (eval test)
5108               (or (memq (preceding-char) (append (or chars "{;") nil))
5109                   (and (eq (preceding-char) ?\})
5110                        (cperl-after-block-p lim))
5111                   (and (eq (following-char) ?.) ; in format: see comment above
5112                        (eq (get-text-property (point) 'syntax-type)
5113                            'format)))))))))
5114
5115 (defun cperl-backward-to-start-of-continued-exp (lim)
5116   (if (memq (preceding-char) (append ")]}\"'`" nil))
5117       (forward-sexp -1))
5118   (beginning-of-line)
5119   (if (<= (point) lim)
5120       (goto-char (1+ lim)))
5121   (skip-chars-forward " \t"))
5122
5123 (defun cperl-after-block-and-statement-beg (lim)
5124   ;; We assume that we are after ?\}
5125   (and
5126    (cperl-after-block-p lim)
5127    (save-excursion
5128      (forward-sexp -1)
5129      (cperl-backward-to-noncomment (point-min))
5130      (or (bobp)
5131          (eq (point) lim)
5132          (not (= (char-syntax (preceding-char)) ?w))
5133          (progn
5134            (forward-sexp -1)
5135            (not
5136             (looking-at
5137              "\\(map\\|grep\\|printf?\\|system\\|exec\\|tr\\|s\\)\\>")))))))
5138
5139 \f
5140 (defvar innerloop-done nil)
5141 (defvar last-depth nil)
5142
5143 (defun cperl-indent-exp ()
5144   "Simple variant of indentation of continued-sexp.
5145
5146 Will not indent comment if it starts at `comment-indent' or looks like
5147 continuation of the comment on the previous line.
5148
5149 If `cperl-indent-region-fix-constructs', will improve spacing on
5150 conditional/loop constructs."
5151   (interactive)
5152   (save-excursion
5153     (let ((tmp-end (progn (end-of-line) (point))) top done)
5154       (save-excursion
5155         (beginning-of-line)
5156         (while (null done)
5157           (setq top (point))
5158           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
5159                                                -1)) -1)
5160             (setq top (point)))         ; Get the outermost parenths in line
5161           (goto-char top)
5162           (while (< (point) tmp-end)
5163             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
5164             (or (eolp) (forward-sexp 1)))
5165           (if (> (point) tmp-end)
5166               (save-excursion
5167                 (end-of-line)
5168                 (setq tmp-end (point)))
5169             (setq done t)))
5170         (goto-char tmp-end)
5171         (setq tmp-end (point-marker)))
5172       (if cperl-indent-region-fix-constructs
5173           (cperl-fix-line-spacing tmp-end))
5174       (cperl-indent-region (point) tmp-end))))
5175
5176 (defun cperl-fix-line-spacing (&optional end parse-data)
5177   "Improve whitespace in a conditional/loop construct.
5178 Returns some position at the last line."
5179   (interactive)
5180   (or end
5181       (setq end (point-max)))
5182   (let ((ee (save-excursion (end-of-line) (point)))
5183         (cperl-indent-region-fix-constructs
5184          (or cperl-indent-region-fix-constructs 1))
5185         p pp ml have-brace ret)
5186     (save-excursion
5187       (beginning-of-line)
5188       (setq ret (point))
5189       ;;  }? continue
5190       ;;  blah; }
5191       (if (not
5192            (or (looking-at "[ \t]*\\(els\\(e\\|if\\)\\|continue\\|if\\|while\\|for\\(each\\)?\\|until\\)")
5193                (setq have-brace (save-excursion (search-forward "}" ee t)))))
5194           nil                           ; Do not need to do anything
5195         ;; Looking at:
5196         ;; }
5197         ;; else
5198         (if (and cperl-merge-trailing-else
5199                  (looking-at
5200                   "[ \t]*}[ \t]*\n[ \t\n]*\\(els\\(e\\|if\\)\\|continue\\)\\>"))
5201             (progn
5202               (search-forward "}")
5203               (setq p (point))
5204               (skip-chars-forward " \t\n")
5205               (delete-region p (point))
5206               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5207               (beginning-of-line)))
5208         ;; Looking at:
5209         ;; }     else
5210         (if (looking-at "[ \t]*}\\(\t*\\|[ \t][ \t]+\\)\\<\\(els\\(e\\|if\\)\\|continue\\)\\>")
5211             (progn
5212               (search-forward "}")
5213               (delete-horizontal-space)
5214               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5215               (beginning-of-line)))
5216         ;; Looking at:
5217         ;; else   {
5218         (if (looking-at
5219              "[ \t]*}?[ \t]*\\<\\(\\els\\(e\\|if\\)\\|continue\\|unless\\|if\\|while\\|for\\(each\\)?\\|until\\)\\>\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
5220             (progn
5221               (forward-word 1)
5222               (delete-horizontal-space)
5223               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5224               (beginning-of-line)))
5225         ;; Looking at:
5226         ;; foreach my    $var
5227         (if (looking-at
5228              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)\\(\t*\\|[ \t][ \t]+\\)[^ \t\n]")
5229             (progn
5230               (forward-word 2)
5231               (delete-horizontal-space)
5232               (insert (make-string cperl-indent-region-fix-constructs ?\ ))
5233               (beginning-of-line)))
5234         ;; Looking at:
5235         ;; foreach my $var     (
5236         (if (looking-at
5237              "[ \t]*\\<for\\(each\\)?[ \t]+\\(my\\|local\\|our\\)[ \t]*\\$[_a-zA-Z0-9]+\\(\t*\\|[ \t][ \t]+\\)[^ \t\n#]")
5238             (progn
5239               (forward-sexp 3)
5240               (delete-horizontal-space)
5241               (insert
5242                (make-string cperl-indent-region-fix-constructs ?\ ))
5243               (beginning-of-line)))
5244         ;; Looking at:
5245         ;; } foreach my $var ()    {
5246         (if (looking-at
5247              "[ \t]*\\(}[ \t]*\\)?\\<\\(\\els\\(e\\|if\\)\\|continue\\|if\\|unless\\|while\\|for\\(each\\)?\\(\\([ \t]+\\(my\\|local\\|our\\)\\)?[ \t]*\\$[_a-zA-Z0-9]+\\)?\\|until\\)\\>\\([ \t]*(\\|[ \t\n]*{\\)\\|[ \t]*{")
5248             (progn
5249               (setq ml (match-beginning 8))
5250               (re-search-forward "[({]")
5251               (forward-char -1)
5252               (setq p (point))
5253               (if (eq (following-char) ?\( )
5254                   (progn
5255                     (forward-sexp 1)
5256                     (setq pp (point)))
5257                 ;; after `else' or nothing
5258                 (if ml                  ; after `else'
5259                     (skip-chars-backward " \t\n")
5260                   (beginning-of-line))
5261                 (setq pp nil))
5262               ;; Now after the sexp before the brace
5263               ;; Multiline expr should be special
5264               (setq ml (and pp (save-excursion (goto-char p)
5265                                                (search-forward "\n" pp t))))
5266               (if (and (or (not pp) (< pp end))
5267                        (looking-at "[ \t\n]*{"))
5268                   (progn
5269                     (cond
5270                      ((bolp)            ; Were before `{', no if/else/etc
5271                       nil)
5272                      ((looking-at "\\(\t*\\| [ \t]+\\){")
5273                       (delete-horizontal-space)
5274                       (if (if ml
5275                               cperl-extra-newline-before-brace-multiline
5276                             cperl-extra-newline-before-brace)
5277                           (progn
5278                             (delete-horizontal-space)
5279                             (insert "\n")
5280                             (setq ret (point))
5281                             (if (cperl-indent-line parse-data)
5282                                 (progn
5283                                   (cperl-fix-line-spacing end parse-data)
5284                                   (setq ret (point)))))
5285                         (insert
5286                          (make-string cperl-indent-region-fix-constructs ?\ ))))
5287                      ((and (looking-at "[ \t]*\n")
5288                            (not (if ml
5289                                     cperl-extra-newline-before-brace-multiline
5290                                   cperl-extra-newline-before-brace)))
5291                       (setq pp (point))
5292                       (skip-chars-forward " \t\n")
5293                       (delete-region pp (point))
5294                       (insert
5295                        (make-string cperl-indent-region-fix-constructs ?\ ))))
5296                     ;; Now we are before `{'
5297                     (if (looking-at "[ \t\n]*{[ \t]*[^ \t\n#]")
5298                         (progn
5299                           (skip-chars-forward " \t\n")
5300                           (setq pp (point))
5301                           (forward-sexp 1)
5302                           (setq p (point))
5303                           (goto-char pp)
5304                           (setq ml (search-forward "\n" p t))
5305                           (if (or cperl-break-one-line-blocks-when-indent ml)
5306                               ;; not good: multi-line BLOCK
5307                               (progn
5308                                 (goto-char (1+ pp))
5309                                 (delete-horizontal-space)
5310                                 (insert "\n")
5311                                 (setq ret (point))
5312                                 (if (cperl-indent-line parse-data)
5313                                     (setq ret (cperl-fix-line-spacing end parse-data)))))))))))
5314         (beginning-of-line)
5315         (setq p (point) pp (save-excursion (end-of-line) (point))) ; May be different from ee.
5316         ;; Now check whether there is a hanging `}'
5317         ;; Looking at:
5318         ;; } blah
5319         (if (and
5320              cperl-fix-hanging-brace-when-indent
5321              have-brace
5322              (not (looking-at "[ \t]*}[ \t]*\\(\\<\\(els\\(if\\|e\\)\\|continue\\|while\\|until\\)\\>\\|$\\|#\\)"))
5323              (condition-case nil
5324                  (progn
5325                    (up-list 1)
5326                    (if (and (<= (point) pp)
5327                             (eq (preceding-char) ?\} )
5328                             (cperl-after-block-and-statement-beg (point-min)))
5329                        t
5330                      (goto-char p)
5331                      nil))
5332                (error nil)))
5333             (progn
5334               (forward-char -1)
5335               (skip-chars-backward " \t")
5336               (if (bolp)
5337                   ;; `}' was the first thing on the line, insert NL *after* it.
5338                   (progn
5339                     (cperl-indent-line parse-data)
5340                     (search-forward "}")
5341                     (delete-horizontal-space)
5342                     (insert "\n"))
5343                 (delete-horizontal-space)
5344                 (or (eq (preceding-char) ?\;)
5345                     (bolp)
5346                     (and (eq (preceding-char) ?\} )
5347                          (cperl-after-block-p (point-min)))
5348                     (insert ";"))
5349                 (insert "\n")
5350                 (setq ret (point)))
5351               (if (cperl-indent-line parse-data)
5352                   (setq ret (cperl-fix-line-spacing end parse-data)))
5353               (beginning-of-line)))))
5354     ret))
5355
5356 (defvar cperl-update-start)             ; Do not need to make them local
5357 (defvar cperl-update-end)
5358 (defun cperl-delay-update-hook (beg end old-len)
5359   (setq cperl-update-start (min beg (or cperl-update-start (point-max))))
5360   (setq cperl-update-end (max end (or cperl-update-end (point-min)))))
5361
5362 (defun cperl-indent-region (start end)
5363   "Simple variant of indentation of region in CPerl mode.
5364 Should be slow.  Will not indent comment if it starts at `comment-indent'
5365 or looks like continuation of the comment on the previous line.
5366 Indents all the lines whose first character is between START and END
5367 inclusive.
5368
5369 If `cperl-indent-region-fix-constructs', will improve spacing on
5370 conditional/loop constructs."
5371   (interactive "r")
5372   (cperl-update-syntaxification end end)
5373   (save-excursion
5374     (let (cperl-update-start cperl-update-end (h-a-c after-change-functions))
5375       (let ((indent-info (if cperl-emacs-can-parse
5376                              (list nil nil nil) ; Cannot use '(), since will modify
5377                            nil))
5378             (pm 0) (imenu-scanning-message "Indenting... (%3d%%)")
5379             after-change-functions      ; Speed it up!
5380             st comm old-comm-indent new-comm-indent p pp i empty)
5381         (if h-a-c (add-hook 'after-change-functions 'cperl-delay-update-hook))
5382         (goto-char start)
5383         (setq old-comm-indent (and (cperl-to-comment-or-eol)
5384                                    (current-column))
5385               new-comm-indent old-comm-indent)
5386         (goto-char start)
5387         (setq end (set-marker (make-marker) end)) ; indentation changes pos
5388         (or (bolp) (beginning-of-line 2))
5389         (or (fboundp 'imenu-progress-message)
5390             (message "Indenting... For feedback load `imenu'..."))
5391         (while (and (<= (point) end) (not (eobp))) ; bol to check start
5392           (and (fboundp 'imenu-progress-message)
5393                (imenu-progress-message
5394                 pm (/ (* 100 (- (point) start)) (- end start -1))))
5395           (setq st (point))
5396           (if (or
5397                (setq empty (looking-at "[ \t]*\n"))
5398                (and (setq comm (looking-at "[ \t]*#"))
5399                     (or (eq (current-indentation) (or old-comm-indent
5400                                                       comment-column))
5401                         (setq old-comm-indent nil))))
5402               (if (and old-comm-indent
5403                        (not empty)
5404                        (= (current-indentation) old-comm-indent)
5405                        (not (eq (get-text-property (point) 'syntax-type) 'pod))
5406                        (not (eq (get-text-property (point) 'syntax-table)
5407                                 cperl-st-cfence)))
5408                   (let ((comment-column new-comm-indent))
5409                     (indent-for-comment)))
5410             (progn
5411               (setq i (cperl-indent-line indent-info))
5412               (or comm
5413                   (not i)
5414                   (progn
5415                     (if cperl-indent-region-fix-constructs
5416                         (goto-char (cperl-fix-line-spacing end indent-info)))
5417                     (if (setq old-comm-indent
5418                               (and (cperl-to-comment-or-eol)
5419                                    (not (memq (get-text-property (point)
5420                                                                  'syntax-type)
5421                                               '(pod here-doc)))
5422                                    (not (eq (get-text-property (point)
5423                                                                'syntax-table)
5424                                             cperl-st-cfence))
5425                                    (current-column)))
5426                         (progn (indent-for-comment)
5427                                (skip-chars-backward " \t")
5428                                (skip-chars-backward "#")
5429                                (setq new-comm-indent (current-column))))))))
5430           (beginning-of-line 2))
5431         (if (fboundp 'imenu-progress-message)
5432             (imenu-progress-message pm 100)
5433           (message nil)))
5434       ;; Now run the update hooks
5435       (and after-change-functions
5436            cperl-update-end
5437            (save-excursion
5438              (goto-char cperl-update-end)
5439              (insert " ")
5440              (delete-char -1)
5441              (goto-char cperl-update-start)
5442              (insert " ")
5443              (delete-char -1))))))
5444
5445 ;; Stolen from lisp-mode with a lot of improvements
5446
5447 (defun cperl-fill-paragraph (&optional justify iteration)
5448   "Like \\[fill-paragraph], but handle CPerl comments.
5449 If any of the current line is a comment, fill the comment or the
5450 block of it that point is in, preserving the comment's initial
5451 indentation and initial hashes.  Behaves usually outside of comment."
5452   (interactive "P")
5453   (let (;; Non-nil if the current line contains a comment.
5454         has-comment
5455
5456         ;; If has-comment, the appropriate fill-prefix for the comment.
5457         comment-fill-prefix
5458         ;; Line that contains code and comment (or nil)
5459         start
5460         c spaces len dc (comment-column comment-column))
5461     ;; Figure out what kind of comment we are looking at.
5462     (save-excursion
5463       (beginning-of-line)
5464       (cond
5465
5466        ;; A line with nothing but a comment on it?
5467        ((looking-at "[ \t]*#[# \t]*")
5468         (setq has-comment t
5469               comment-fill-prefix (buffer-substring (match-beginning 0)
5470                                                     (match-end 0))))
5471
5472        ;; A line with some code, followed by a comment?  Remember that the
5473        ;; semi which starts the comment shouldn't be part of a string or
5474        ;; character.
5475        ((cperl-to-comment-or-eol)
5476         (setq has-comment t)
5477         (looking-at "#+[ \t]*")
5478         (setq start (point) c (current-column)
5479               comment-fill-prefix
5480               (concat (make-string (current-column) ?\ )
5481                       (buffer-substring (match-beginning 0) (match-end 0)))
5482               spaces (progn (skip-chars-backward " \t")
5483                             (buffer-substring (point) start))
5484               dc (- c (current-column)) len (- start (point))
5485               start (point-marker))
5486         (delete-char len)
5487         (insert (make-string dc ?-)))))
5488     (if (not has-comment)
5489         (fill-paragraph justify)       ; Do the usual thing outside of comment
5490       ;; Narrow to include only the comment, and then fill the region.
5491       (save-restriction
5492         (narrow-to-region
5493          ;; Find the first line we should include in the region to fill.
5494          (if start (progn (beginning-of-line) (point))
5495            (save-excursion
5496              (while (and (zerop (forward-line -1))
5497                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
5498              ;; We may have gone to far.  Go forward again.
5499              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
5500                  (forward-line 1))
5501              (point)))
5502          ;; Find the beginning of the first line past the region to fill.
5503          (save-excursion
5504            (while (progn (forward-line 1)
5505                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
5506            (point)))
5507         ;; Remove existing hashes
5508         (goto-char (point-min))
5509         (while (progn (forward-line 1) (< (point) (point-max)))
5510           (skip-chars-forward " \t")
5511           (and (looking-at "#+")
5512                (delete-char (- (match-end 0) (match-beginning 0)))))
5513
5514         ;; Lines with only hashes on them can be paragraph boundaries.
5515         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
5516               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
5517               (fill-prefix comment-fill-prefix))
5518           (fill-paragraph justify)))
5519       (if (and start)
5520           (progn
5521             (goto-char start)
5522             (if (> dc 0)
5523                 (progn (delete-char dc) (insert spaces)))
5524             (if (or (= (current-column) c) iteration) nil
5525               (setq comment-column c)
5526               (indent-for-comment)
5527               ;; Repeat once more, flagging as iteration
5528               (cperl-fill-paragraph justify t)))))))
5529
5530 (defun cperl-do-auto-fill ()
5531   ;; Break out if the line is short enough
5532   (if (> (save-excursion
5533            (end-of-line)
5534            (current-column))
5535          fill-column)
5536       (let ((c (save-excursion (beginning-of-line)
5537                                (cperl-to-comment-or-eol) (point)))
5538             (s (memq (following-char) '(?\ ?\t))) marker)
5539         (if (>= c (point)) nil
5540           (setq marker (point-marker))
5541           (cperl-fill-paragraph)
5542           (goto-char marker)
5543           ;; Is not enough, sometimes marker is a start of line
5544           (if (bolp) (progn (re-search-forward "#+[ \t]*")
5545                             (goto-char (match-end 0))))
5546           ;; Following space could have gone:
5547           (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
5548             (insert " ")
5549             (backward-char 1))
5550           ;; Previous space could have gone:
5551           (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
5552
5553 (defun cperl-imenu-addback (lst &optional isback name)
5554   ;; We suppose that the lst is a DAG, unless the first element only
5555   ;; loops back, and ISBACK is set.  Thus this function cannot be
5556   ;; applied twice without ISBACK set.
5557   (cond ((not cperl-imenu-addback) lst)
5558         (t
5559          (or name
5560              (setq name "+++BACK+++"))
5561          (mapcar (lambda (elt)
5562                    (if (and (listp elt) (listp (cdr elt)))
5563                        (progn
5564                          ;; In the other order it goes up
5565                          ;; one level only ;-(
5566                          (setcdr elt (cons (cons name lst)
5567                                            (cdr elt)))
5568                          (cperl-imenu-addback (cdr elt) t name))))
5569                  (if isback (cdr lst) lst))
5570          lst)))
5571
5572 (defun cperl-imenu--create-perl-index (&optional regexp)
5573   (require 'cl)
5574   (require 'imenu)                      ; May be called from TAGS creator
5575   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '())
5576         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
5577         (index-meth-alist '()) meth
5578         packages ends-ranges p marker
5579         (prev-pos 0) char fchar index index1 name (end-range 0) package)
5580     (goto-char (point-min))
5581     (if noninteractive
5582         (message "Scanning Perl for index")
5583       (imenu-progress-message prev-pos 0))
5584     (cperl-update-syntaxification (point-max) (point-max))
5585     ;; Search for the function
5586     (progn ;;save-match-data
5587       (while (re-search-forward
5588               (or regexp cperl-imenu--function-name-regexp-perl)
5589               nil t)
5590         (or noninteractive
5591             (imenu-progress-message prev-pos))
5592         (cond
5593          ((and                          ; Skip some noise if building tags
5594            (match-beginning 2)          ; package or sub
5595            (eq (char-after (match-beginning 2)) ?p) ; package
5596            (not (save-match-data
5597                   (looking-at "[ \t\n]*;")))) ; Plain text word 'package'
5598           nil)
5599          ((and
5600            (match-beginning 2)          ; package or sub
5601            ;; Skip if quoted (will not skip multi-line ''-strings :-():
5602            (null (get-text-property (match-beginning 1) 'syntax-table))
5603            (null (get-text-property (match-beginning 1) 'syntax-type))
5604            (null (get-text-property (match-beginning 1) 'in-pod)))
5605           (save-excursion
5606             (goto-char (match-beginning 2))
5607             (setq fchar (following-char)))
5608           ;; (if (looking-at "([^()]*)[ \t\n\f]*")
5609           ;;    (goto-char (match-end 0)))      ; Messes what follows
5610           (setq char (following-char)   ; ?\; for "sub foo () ;"
5611                 meth nil
5612                 p (point))
5613           (while (and ends-ranges (>= p (car ends-ranges)))
5614             ;; delete obsolete entries
5615             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
5616           (setq package (or (car packages) "")
5617                 end-range (or (car ends-ranges) 0))
5618           (if (eq fchar ?p)
5619               (setq name (buffer-substring (match-beginning 3) (match-end 3))
5620                     name (progn
5621                            (set-text-properties 0 (length name) nil name)
5622                            name)
5623                     package (concat name "::")
5624                     name (concat "package " name)
5625                     end-range
5626                     (save-excursion
5627                       (parse-partial-sexp (point) (point-max) -1) (point))
5628                     ends-ranges (cons end-range ends-ranges)
5629                     packages (cons package packages)))
5630           ;;   )
5631           ;; Skip this function name if it is a prototype declaration.
5632           (if (and (eq fchar ?s) (eq char ?\;)) nil
5633             (setq name (buffer-substring (match-beginning 3) (match-end 3))
5634                   marker (make-marker))
5635             (set-text-properties 0 (length name) nil name)
5636             (set-marker marker (match-end 3))
5637             (if (eq fchar ?p)
5638                 (setq name (concat "package " name))
5639               (cond ((string-match "[:']" name)
5640                      (setq meth t))
5641                     ((> p end-range) nil)
5642                     (t
5643                      (setq name (concat package name) meth t))))
5644             (setq index (cons name marker))
5645             (if (eq fchar ?p)
5646                 (push index index-pack-alist)
5647               (push index index-alist))
5648             (if meth (push index index-meth-alist))
5649             (push index index-unsorted-alist)))
5650          ((match-beginning 5)           ; POD section
5651           ;; (beginning-of-line)
5652           (setq index (imenu-example--name-and-position)
5653                 name (buffer-substring (match-beginning 6) (match-end 6)))
5654           (set-text-properties 0 (length name) nil name)
5655           (if (eq (char-after (match-beginning 5)) ?2)
5656               (setq name (concat "   " name)))
5657           (setcar index name)
5658           (setq index1 (cons (concat "=" name) (cdr index)))
5659           (push index index-pod-alist)
5660           (push index1 index-unsorted-alist)))))
5661     (or noninteractive
5662         (imenu-progress-message prev-pos 100))
5663     (setq index-alist
5664           (if (default-value 'imenu-sort-function)
5665               (sort index-alist (default-value 'imenu-sort-function))
5666             (nreverse index-alist)))
5667     (and index-pod-alist
5668          (push (cons "+POD headers+..."
5669                      (nreverse index-pod-alist))
5670                index-alist))
5671     (and (or index-pack-alist index-meth-alist)
5672          (let ((lst index-pack-alist) hier-list pack elt group name)
5673            ;; Remove "package ", reverse and uniquify.
5674            (while lst
5675              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
5676              (if (assoc name hier-list) nil
5677                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
5678            (setq lst index-meth-alist)
5679            (while lst
5680              (setq elt (car lst) lst (cdr lst))
5681              (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
5682                     (setq pack (substring (car elt) 0 (match-beginning 0)))
5683                     (if (setq group (assoc pack hier-list))
5684                         (if (listp (cdr group))
5685                             ;; Have some functions already
5686                             (setcdr group
5687                                     (cons (cons (substring
5688                                                  (car elt)
5689                                                  (+ 2 (match-beginning 0)))
5690                                                 (cdr elt))
5691                                           (cdr group)))
5692                           (setcdr group (list (cons (substring
5693                                                      (car elt)
5694                                                      (+ 2 (match-beginning 0)))
5695                                                     (cdr elt)))))
5696                       (setq hier-list
5697                             (cons (cons pack
5698                                         (list (cons (substring
5699                                                      (car elt)
5700                                                      (+ 2 (match-beginning 0)))
5701                                                     (cdr elt))))
5702                                   hier-list))))))
5703            (push (cons "+Hierarchy+..."
5704                        hier-list)
5705                  index-alist)))
5706     (and index-pack-alist
5707          (push (cons "+Packages+..."
5708                      (nreverse index-pack-alist))
5709                index-alist))
5710     (and (or index-pack-alist index-pod-alist
5711              (default-value 'imenu-sort-function))
5712          index-unsorted-alist
5713          (push (cons "+Unsorted List+..."
5714                      (nreverse index-unsorted-alist))
5715                index-alist))
5716     (cperl-imenu-addback index-alist)))
5717
5718 \f
5719 ;; Suggested by Mark A. Hershberger
5720 (defun cperl-outline-level ()
5721   (looking-at outline-regexp)
5722   (cond ((not (match-beginning 1)) 0)   ; beginning-of-file
5723         ((match-beginning 2)
5724          (if (eq (char-after (match-beginning 2)) ?p)
5725              0                          ; package
5726            1))                          ; sub
5727         ((match-beginning 5)
5728          (if (eq (char-after (match-beginning 5)) ?1)
5729              1                          ; head1
5730            2))                          ; head2
5731         (t 3)))                         ; should not happen
5732
5733 \f
5734 (defvar cperl-compilation-error-regexp-alist
5735   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
5736   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
5737      2 3))
5738   "Alist that specifies how to match errors in perl output.")
5739
5740 (if (fboundp 'eval-after-load)
5741     (eval-after-load
5742         "mode-compile"
5743       '(setq perl-compilation-error-regexp-alist
5744              cperl-compilation-error-regexp-alist)))
5745
5746
5747 (defun cperl-windowed-init ()
5748   "Initialization under windowed version."
5749   (if (or (featurep 'ps-print) cperl-faces-init)
5750       ;; Need to init anyway:
5751       (or cperl-faces-init (cperl-init-faces))
5752     (add-hook 'font-lock-mode-hook
5753               (function
5754                (lambda ()
5755                  (if (memq major-mode '(perl-mode cperl-mode))
5756                      (progn
5757                        (or cperl-faces-init (cperl-init-faces)))))))
5758     (if (fboundp 'eval-after-load)
5759         (eval-after-load
5760             "ps-print"
5761           '(or cperl-faces-init (cperl-init-faces))))))
5762
5763 (defun cperl-load-font-lock-keywords ()
5764   (or cperl-faces-init (cperl-init-faces))
5765   perl-font-lock-keywords)
5766
5767 (defun cperl-load-font-lock-keywords-1 ()
5768   (or cperl-faces-init (cperl-init-faces))
5769   perl-font-lock-keywords-1)
5770
5771 (defun cperl-load-font-lock-keywords-2 ()
5772   (or cperl-faces-init (cperl-init-faces))
5773   perl-font-lock-keywords-2)
5774
5775 (defvar perl-font-lock-keywords-1 nil
5776   "Additional expressions to highlight in Perl mode.  Minimal set.")
5777 (defvar perl-font-lock-keywords nil
5778   "Additional expressions to highlight in Perl mode.  Default set.")
5779 (defvar perl-font-lock-keywords-2 nil
5780   "Additional expressions to highlight in Perl mode.  Maximal set")
5781
5782 (defvar font-lock-background-mode)
5783 (defvar font-lock-display-type)
5784 (defun cperl-init-faces-weak ()
5785   ;; Allow `cperl-find-pods-heres' to run.
5786   (or (boundp 'font-lock-constant-face)
5787       (cperl-force-face font-lock-constant-face
5788                         "Face for constant and label names")
5789       ;;(setq font-lock-constant-face 'font-lock-constant-face)
5790       ))
5791
5792 (defun cperl-init-faces ()
5793   (condition-case errs
5794       (progn
5795         (require 'font-lock)
5796         (and (fboundp 'font-lock-fontify-anchored-keywords)
5797              (featurep 'font-lock-extra)
5798              (message "You have an obsolete package `font-lock-extra'.  Install `choose-color'."))
5799         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
5800           (if (fboundp 'font-lock-fontify-anchored-keywords)
5801               (setq font-lock-anchored t))
5802           (setq
5803            t-font-lock-keywords
5804            (list
5805             (list "[ \t]+$" 0 cperl-invalid-face t)
5806             (cons
5807              (concat
5808               "\\(^\\|[^$@%&\\]\\)\\<\\("
5809               (mapconcat
5810                'identity
5811                '("if" "until" "while" "elsif" "else" "unless" "for"
5812                  "foreach" "continue" "exit" "die" "last" "goto" "next"
5813                  "redo" "return" "local" "exec" "sub" "do" "dump" "use"
5814                  "require" "package" "eval" "my" "BEGIN" "END" "CHECK" "INIT")
5815                "\\|")                   ; Flow control
5816               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
5817                                         ; In what follows we use `type' style
5818                                         ; for overwritable builtins
5819             (list
5820              (concat
5821               "\\(^\\|[^$@%&\\]\\)\\<\\("
5822               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm"
5823               ;; "and" "atan2" "bind" "binmode" "bless" "caller"
5824               ;; "chdir" "chmod" "chown" "chr" "chroot" "close"
5825               ;; "closedir" "cmp" "connect" "continue" "cos" "crypt"
5826               ;; "dbmclose" "dbmopen" "die" "dump" "endgrent"
5827               ;; "endhostent" "endnetent" "endprotoent" "endpwent"
5828               ;; "endservent" "eof" "eq" "exec" "exit" "exp" "fcntl"
5829               ;; "fileno" "flock" "fork" "formline" "ge" "getc"
5830               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr"
5831               ;; "gethostbyname" "gethostent" "getlogin"
5832               ;; "getnetbyaddr" "getnetbyname" "getnetent"
5833               ;; "getpeername" "getpgrp" "getppid" "getpriority"
5834               ;; "getprotobyname" "getprotobynumber" "getprotoent"
5835               ;; "getpwent" "getpwnam" "getpwuid" "getservbyname"
5836               ;; "getservbyport" "getservent" "getsockname"
5837               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int"
5838               ;; "ioctl" "join" "kill" "lc" "lcfirst" "le" "length"
5839               ;; "link" "listen" "localtime" "lock" "log" "lstat" "lt"
5840               ;; "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd" "ne"
5841               ;; "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
5842               ;; "quotemeta" "rand" "read" "readdir" "readline"
5843               ;; "readlink" "readpipe" "recv" "ref" "rename" "require"
5844               ;; "reset" "reverse" "rewinddir" "rindex" "rmdir" "seek"
5845               ;; "seekdir" "select" "semctl" "semget" "semop" "send"
5846               ;; "setgrent" "sethostent" "setnetent" "setpgrp"
5847               ;; "setpriority" "setprotoent" "setpwent" "setservent"
5848               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite"
5849               ;; "shutdown" "sin" "sleep" "socket" "socketpair"
5850               ;; "sprintf" "sqrt" "srand" "stat" "substr" "symlink"
5851               ;; "syscall" "sysopen" "sysread" "system" "syswrite" "tell"
5852               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst"
5853               ;; "umask" "unlink" "unpack" "utime" "values" "vec"
5854               ;; "wait" "waitpid" "wantarray" "warn" "write" "x" "xor"
5855               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|"
5856               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
5857               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
5858               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
5859               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
5860               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
5861               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
5862               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
5863               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
5864               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
5865               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
5866               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
5867               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
5868               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
5869               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
5870               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
5871               "\\(\\|ngth\\)\\|o\\(c\\(altime\\|k\\)\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
5872               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
5873               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
5874               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
5875               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
5876               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
5877               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
5878               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
5879               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
5880               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|open\\|tem\\|write\\)\\|"
5881               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
5882               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
5883               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
5884               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
5885               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\|PACKAGE__\\)"
5886               "\\)\\>") 2 'font-lock-type-face)
5887             ;; In what follows we use `other' style
5888             ;; for nonoverwritable builtins
5889             ;; Somehow 's', 'm' are not auto-generated???
5890             (list
5891              (concat
5892               "\\(^\\|[^$@%&\\]\\)\\<\\("
5893               ;; "AUTOLOAD" "BEGIN" "CHECK" "DESTROY" "END" "INIT" "__END__" "chomp"
5894               ;; "chop" "defined" "delete" "do" "each" "else" "elsif"
5895               ;; "eval" "exists" "for" "foreach" "format" "goto"
5896               ;; "grep" "if" "keys" "last" "local" "map" "my" "next"
5897               ;; "no" "package" "pop" "pos" "print" "printf" "push"
5898               ;; "q" "qq" "qw" "qx" "redo" "return" "scalar" "shift"
5899               ;; "sort" "splice" "split" "study" "sub" "tie" "tr"
5900               ;; "undef" "unless" "unshift" "untie" "until" "use"
5901               ;; "while" "y"
5902               "AUTOLOAD\\|BEGIN\\|CHECK\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
5903               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
5904               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|INIT\\|if\\|keys\\|"
5905               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|our\\|"
5906               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
5907               "q\\(\\|q\\|w\\|x\\|r\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
5908               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
5909               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
5910               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
5911               "\\|[sm]"                 ; Added manually
5912               "\\)\\>") 2 'cperl-nonoverridable-face)
5913             ;;          (mapconcat 'identity
5914             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
5915             ;;                       "#include" "#define" "#undef")
5916             ;;                     "\\|")
5917             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
5918               font-lock-function-name-face keep) ; Not very good, triggers at "[a-z]"
5919             '("\\<sub[ \t]+\\([^ \t{;()]+\\)[ \t]*\\(([^()]*)[ \t]*\\)?[#{\n]" 1
5920               font-lock-function-name-face)
5921             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
5922               2 font-lock-function-name-face)
5923             '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
5924               1 font-lock-function-name-face)
5925             (cond ((featurep 'font-lock-extra)
5926                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5927                      (2 font-lock-string-face t)
5928                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
5929                   (font-lock-anchored
5930                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5931                      (2 font-lock-string-face t)
5932                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5933                       nil nil
5934                       (1 font-lock-string-face t))))
5935                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
5936                        2 font-lock-string-face t)))
5937             '("[\[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
5938               font-lock-string-face t)
5939             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1
5940               font-lock-constant-face)  ; labels
5941             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
5942               2 font-lock-constant-face)
5943             ;; Uncomment to get perl-mode-like vars
5944             ;;; '("[$*]{?\\(\\sw+\\)" 1 font-lock-variable-name-face)
5945             ;;; '("\\([@%]\\|\\$#\\)\\(\\sw+\\)"
5946             ;;;  (2 (cons font-lock-variable-name-face '(underline))))
5947             (cond ((featurep 'font-lock-extra)
5948                    '("^[ \t]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
5949                      (3 font-lock-variable-name-face)
5950                      (4 '(another 4 nil
5951                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
5952                                    (1 font-lock-variable-name-face)
5953                                    (2 '(restart 2 nil) nil t)))
5954                         nil t)))        ; local variables, multiple
5955                   (font-lock-anchored
5956                    '("^[ \t{}]*\\(my\\|local\\|our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
5957                      (3 font-lock-variable-name-face)
5958                      ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)"
5959                       nil nil
5960                       (1 font-lock-variable-name-face))))
5961                   (t '("^[ \t{}]*\\(my\\|local\\our\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
5962                        3 font-lock-variable-name-face)))
5963             '("\\<for\\(each\\)?\\([ \t]+\\(my\\|local\\|our\\)\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
5964               4 font-lock-variable-name-face)))
5965           (setq
5966            t-font-lock-keywords-1
5967            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
5968                 (not cperl-xemacs-p)    ; not yet as of XEmacs 19.12
5969                 '(
5970                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
5971                    (if (eq (char-after (match-beginning 2)) ?%)
5972                        cperl-hash-face
5973                      cperl-array-face)
5974                    t)                   ; arrays and hashes
5975                   ("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
5976                    1
5977                    (if (= (- (match-end 2) (match-beginning 2)) 1)
5978                        (if (eq (char-after (match-beginning 3)) ?{)
5979                            cperl-hash-face
5980                          cperl-array-face) ; arrays and hashes
5981                      font-lock-variable-name-face) ; Just to put something
5982                    t)
5983                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
5984                        ;;; Too much noise from \s* @s[ and friends
5985                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)"
5986                   ;;(3 font-lock-function-name-face t t)
5987                   ;;(4
5988                   ;; (if (cperl-slash-is-regexp)
5989                   ;;    font-lock-function-name-face 'default) nil t))
5990                   )))
5991           (if cperl-highlight-variables-indiscriminately
5992               (setq t-font-lock-keywords-1
5993                     (append t-font-lock-keywords-1
5994                             (list '("[$*]{?\\(\\sw+\\)" 1
5995                                     font-lock-variable-name-face)))))
5996           (setq perl-font-lock-keywords-1 
5997                 (if cperl-syntaxify-by-font-lock
5998                     (cons 'cperl-fontify-update
5999                           t-font-lock-keywords)
6000                   t-font-lock-keywords)
6001                 perl-font-lock-keywords perl-font-lock-keywords-1
6002                 perl-font-lock-keywords-2 (append
6003                                            perl-font-lock-keywords-1
6004                                            t-font-lock-keywords-1)))
6005         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
6006         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
6007             (eval                       ; Avoid a warning
6008              '(font-lock-require-faces
6009                (list
6010                 ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
6011                 (list 'font-lock-comment-face
6012                       ["Firebrick"      "OrangeRed"     "DimGray"       "Gray80"]
6013                       nil
6014                       [nil              nil             t               t       t]
6015                       [nil              nil             t               t       t]
6016                       nil)
6017                 (list 'font-lock-string-face
6018                       ["RosyBrown"      "LightSalmon"   "Gray50"        "LightGray"]
6019                       nil
6020                       nil
6021                       [nil              nil             t               t       t]
6022                       nil)
6023                 (list 'font-lock-function-name-face
6024                       (vector
6025                        "Blue"           "LightSkyBlue"  "Gray50"        "LightGray"
6026                        (cdr (assq 'background-color ; if mono
6027                                   (frame-parameters))))
6028                       (vector
6029                        nil              nil             nil             nil
6030                        (cdr (assq 'foreground-color ; if mono
6031                                   (frame-parameters))))
6032                       [nil              nil             t               t       t]
6033                       nil
6034                       nil)
6035                 (list 'font-lock-variable-name-face
6036                       ["DarkGoldenrod"  "LightGoldenrod" "DimGray"      "Gray90"]
6037                       nil
6038                       [nil              nil             t               t       t]
6039                       [nil              nil             t               t       t]
6040                       nil)
6041                 (list 'font-lock-type-face
6042                       ["DarkOliveGreen" "PaleGreen"     "DimGray"       "Gray80"]
6043                       nil
6044                       [nil              nil             t               t       t]
6045                       nil
6046                       [nil              nil             t               t       t])
6047                 (list 'font-lock-constant-face
6048                       ["CadetBlue"      "Aquamarine"    "Gray50"        "LightGray"]
6049                       nil
6050                       [nil              nil             t               t       t]
6051                       nil
6052                       [nil              nil             t               t       t])
6053                 (list 'cperl-nonoverridable-face
6054                       ["chartreuse3"    ("orchid1" "orange")
6055                        nil              "Gray80"]
6056                       [nil              nil             "gray90"]
6057                       [nil              nil             nil             t       t]
6058                       [nil              nil             t               t]
6059                       [nil              nil             t               t       t])
6060                 (list 'cperl-array-face
6061                       ["blue"           "yellow"        nil             "Gray80"]
6062                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
6063                        "gray90"]
6064                       t
6065                       nil
6066                       nil)
6067                 (list 'cperl-hash-face
6068                       ["red"            "red"           nil             "Gray80"]
6069                       ["lightyellow2"   ("navy" "os2blue" "darkgreen")
6070                        "gray90"]
6071                       t
6072                       t
6073                       nil))))
6074           ;; Do it the dull way, without choose-color
6075           (defvar cperl-guessed-background nil
6076             "Display characteristics as guessed by cperl.")
6077           ;;      (or (fboundp 'x-color-defined-p)
6078           ;;          (defalias 'x-color-defined-p 
6079           ;;            (cond ((fboundp 'color-defined-p) 'color-defined-p)
6080           ;;                  ;; XEmacs >= 19.12
6081           ;;                  ((fboundp 'valid-color-name-p) 'valid-color-name-p)
6082           ;;                  ;; XEmacs 19.11
6083           ;;                  (t 'x-valid-color-name-p))))
6084           (cperl-force-face font-lock-constant-face
6085                             "Face for constant and label names")
6086           (cperl-force-face font-lock-variable-name-face
6087                             "Face for variable names")
6088           (cperl-force-face font-lock-type-face
6089                             "Face for data types")
6090           (cperl-force-face cperl-nonoverridable-face
6091                             "Face for data types from another group")
6092           (cperl-force-face font-lock-comment-face
6093                             "Face for comments")
6094           (cperl-force-face font-lock-function-name-face
6095                             "Face for function names")
6096           (cperl-force-face cperl-hash-face
6097                             "Face for hashes")
6098           (cperl-force-face cperl-array-face
6099                             "Face for arrays")
6100           ;;(defvar font-lock-constant-face 'font-lock-constant-face)
6101           ;;(defvar font-lock-variable-name-face 'font-lock-variable-name-face)
6102           ;;(or (boundp 'font-lock-type-face)
6103           ;;    (defconst font-lock-type-face
6104           ;;    'font-lock-type-face
6105           ;;    "Face to use for data types."))
6106           ;;(or (boundp 'cperl-nonoverridable-face)
6107           ;;    (defconst cperl-nonoverridable-face
6108           ;;    'cperl-nonoverridable-face
6109           ;;    "Face to use for data types from another group."))
6110           ;;(if (not cperl-xemacs-p) nil
6111           ;;  (or (boundp 'font-lock-comment-face)
6112           ;;    (defconst font-lock-comment-face
6113           ;;      'font-lock-comment-face
6114           ;;      "Face to use for comments."))
6115           ;;  (or (boundp 'font-lock-keyword-face)
6116           ;;    (defconst font-lock-keyword-face
6117           ;;      'font-lock-keyword-face
6118           ;;      "Face to use for keywords."))
6119           ;;  (or (boundp 'font-lock-function-name-face)
6120           ;;    (defconst font-lock-function-name-face
6121           ;;      'font-lock-function-name-face
6122           ;;      "Face to use for function names.")))
6123           (if (and
6124                (not (cperl-is-face 'cperl-array-face))
6125                (cperl-is-face 'font-lock-emphasized-face))
6126               (copy-face 'font-lock-emphasized-face 'cperl-array-face))
6127           (if (and
6128                (not (cperl-is-face 'cperl-hash-face))
6129                (cperl-is-face 'font-lock-other-emphasized-face))
6130               (copy-face 'font-lock-other-emphasized-face
6131                          'cperl-hash-face))
6132           (if (and
6133                (not (cperl-is-face 'cperl-nonoverridable-face))
6134                (cperl-is-face 'font-lock-other-type-face))
6135               (copy-face 'font-lock-other-type-face
6136                          'cperl-nonoverridable-face))
6137           ;;(or (boundp 'cperl-hash-face)
6138           ;;    (defconst cperl-hash-face
6139           ;;    'cperl-hash-face
6140           ;;    "Face to use for hashes."))
6141           ;;(or (boundp 'cperl-array-face)
6142           ;;    (defconst cperl-array-face
6143           ;;    'cperl-array-face
6144           ;;    "Face to use for arrays."))
6145           ;; Here we try to guess background
6146           (let ((background
6147                  (if (boundp 'font-lock-background-mode)
6148                      font-lock-background-mode
6149                    'light))
6150                 (face-list (and (fboundp 'face-list) (face-list))))
6151 ;;;;        (fset 'cperl-is-face
6152 ;;;;              (cond ((fboundp 'find-face)
6153 ;;;;                     (symbol-function 'find-face))
6154 ;;;;                    (face-list
6155 ;;;;                     (function (lambda (face) (member face face-list))))
6156 ;;;;                    (t
6157 ;;;;                     (function (lambda (face) (boundp face))))))
6158             (defvar cperl-guessed-background
6159               (if (and (boundp 'font-lock-display-type)
6160                        (eq font-lock-display-type 'grayscale))
6161                   'gray
6162                 background)
6163               "Background as guessed by CPerl mode")
6164             (and (not (cperl-is-face 'font-lock-constant-face))
6165                  (cperl-is-face 'font-lock-reference-face)
6166                  (copy-face 'font-lock-reference-face 'font-lock-constant-face))
6167             (if (cperl-is-face 'font-lock-type-face) nil
6168               (copy-face 'default 'font-lock-type-face)
6169               (cond
6170                ((eq background 'light)
6171                 (set-face-foreground 'font-lock-type-face
6172                                      (if (x-color-defined-p "seagreen")
6173                                          "seagreen"
6174                                        "sea green")))
6175                ((eq background 'dark)
6176                 (set-face-foreground 'font-lock-type-face
6177                                      (if (x-color-defined-p "os2pink")
6178                                          "os2pink"
6179                                        "pink")))
6180                (t
6181                 (set-face-background 'font-lock-type-face "gray90"))))
6182             (if (cperl-is-face 'cperl-nonoverridable-face)
6183                 nil
6184               (copy-face 'font-lock-type-face 'cperl-nonoverridable-face)
6185               (cond
6186                ((eq background 'light)
6187                 (set-face-foreground 'cperl-nonoverridable-face
6188                                      (if (x-color-defined-p "chartreuse3")
6189                                          "chartreuse3"
6190                                        "chartreuse")))
6191                ((eq background 'dark)
6192                 (set-face-foreground 'cperl-nonoverridable-face
6193                                      (if (x-color-defined-p "orchid1")
6194                                          "orchid1"
6195                                        "orange")))))
6196 ;;;         (if (cperl-is-face 'font-lock-other-emphasized-face) nil
6197 ;;;           (copy-face 'bold-italic 'font-lock-other-emphasized-face)
6198 ;;;           (cond
6199 ;;;            ((eq background 'light)
6200 ;;;             (set-face-background 'font-lock-other-emphasized-face
6201 ;;;                                  (if (x-color-defined-p "lightyellow2")
6202 ;;;                                      "lightyellow2"
6203 ;;;                                    (if (x-color-defined-p "lightyellow")
6204 ;;;                                        "lightyellow"
6205 ;;;                                      "light yellow"))))
6206 ;;;            ((eq background 'dark)
6207 ;;;             (set-face-background 'font-lock-other-emphasized-face
6208 ;;;                                  (if (x-color-defined-p "navy")
6209 ;;;                                      "navy"
6210 ;;;                                    (if (x-color-defined-p "darkgreen")
6211 ;;;                                        "darkgreen"
6212 ;;;                                      "dark green"))))
6213 ;;;            (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
6214 ;;;         (if (cperl-is-face 'font-lock-emphasized-face) nil
6215 ;;;           (copy-face 'bold 'font-lock-emphasized-face)
6216 ;;;           (cond
6217 ;;;            ((eq background 'light)
6218 ;;;             (set-face-background 'font-lock-emphasized-face
6219 ;;;                                  (if (x-color-defined-p "lightyellow2")
6220 ;;;                                      "lightyellow2"
6221 ;;;                                    "lightyellow")))
6222 ;;;            ((eq background 'dark)
6223 ;;;             (set-face-background 'font-lock-emphasized-face
6224 ;;;                                  (if (x-color-defined-p "navy")
6225 ;;;                                      "navy"
6226 ;;;                                    (if (x-color-defined-p "darkgreen")
6227 ;;;                                        "darkgreen"
6228 ;;;                                      "dark green"))))
6229 ;;;            (t (set-face-background 'font-lock-emphasized-face "gray90"))))
6230             (if (cperl-is-face 'font-lock-variable-name-face) nil
6231               (copy-face 'italic 'font-lock-variable-name-face))
6232             (if (cperl-is-face 'font-lock-constant-face) nil
6233               (copy-face 'italic 'font-lock-constant-face))))
6234         (setq cperl-faces-init t))
6235     (error (message "cperl-init-faces (ignored): %s" errs))))
6236
6237
6238 (defun cperl-ps-print-init ()
6239   "Initialization of `ps-print' components for faces used in CPerl."
6240   (eval-after-load "ps-print"
6241     '(setq ps-bold-faces
6242            ;;                   font-lock-variable-name-face
6243            ;;                   font-lock-constant-face
6244            (append '(cperl-array-face
6245                      cperl-hash-face)
6246                    ps-bold-faces)
6247            ps-italic-faces
6248            ;;                   font-lock-constant-face
6249            (append '(cperl-nonoverridable-face
6250                      cperl-hash-face)
6251                    ps-italic-faces)
6252            ps-underlined-faces
6253            ;;        font-lock-type-face
6254            (append '(cperl-array-face
6255                      cperl-hash-face
6256                      underline
6257                      cperl-nonoverridable-face)
6258                    ps-underlined-faces))))
6259
6260 (defvar ps-print-face-extension-alist)
6261
6262 (defun cperl-ps-print (&optional file)
6263   "Pretty-print in CPerl style.
6264 If optional argument FILE is an empty string, prints to printer, otherwise
6265 to the file FILE.  If FILE is nil, prompts for a file name.
6266
6267 Style of printout regulated by the variable `cperl-ps-print-face-properties'."
6268   (interactive)
6269   (or file
6270       (setq file (read-from-minibuffer
6271                   "Print to file (if empty - to printer): "
6272                   (concat (buffer-file-name) ".ps")
6273                   nil nil 'file-name-history)))
6274   (or (> (length file) 0)
6275       (setq file nil))
6276   (require 'ps-print)                   ; To get ps-print-face-extension-alist
6277   (let ((ps-print-color-p t)
6278         (ps-print-face-extension-alist ps-print-face-extension-alist))
6279     (cperl-ps-extend-face-list cperl-ps-print-face-properties)
6280     (ps-print-buffer-with-faces file)))
6281
6282 ;;; (defun cperl-ps-print-init ()
6283 ;;;   "Initialization of `ps-print' components for faces used in CPerl."
6284 ;;;   ;; Guard against old versions
6285 ;;;   (defvar ps-underlined-faces nil)
6286 ;;;   (defvar ps-bold-faces nil)
6287 ;;;   (defvar ps-italic-faces nil)
6288 ;;;   (setq ps-bold-faces
6289 ;;;     (append '(font-lock-emphasized-face
6290 ;;;               cperl-array-face
6291 ;;;               font-lock-keyword-face
6292 ;;;               font-lock-variable-name-face
6293 ;;;               font-lock-constant-face
6294 ;;;               font-lock-reference-face
6295 ;;;               font-lock-other-emphasized-face
6296 ;;;               cperl-hash-face)
6297 ;;;             ps-bold-faces))
6298 ;;;   (setq ps-italic-faces
6299 ;;;     (append '(cperl-nonoverridable-face
6300 ;;;               font-lock-constant-face
6301 ;;;               font-lock-reference-face
6302 ;;;               font-lock-other-emphasized-face
6303 ;;;               cperl-hash-face)
6304 ;;;             ps-italic-faces))
6305 ;;;   (setq ps-underlined-faces
6306 ;;;     (append '(font-lock-emphasized-face
6307 ;;;               cperl-array-face
6308 ;;;               font-lock-other-emphasized-face
6309 ;;;               cperl-hash-face
6310 ;;;               cperl-nonoverridable-face font-lock-type-face)
6311 ;;;             ps-underlined-faces))
6312 ;;;   (cons 'font-lock-type-face ps-underlined-faces))
6313
6314
6315 (if (cperl-enable-font-lock) (cperl-windowed-init))
6316
6317 (defconst cperl-styles-entries
6318   '(cperl-indent-level cperl-brace-offset cperl-continued-brace-offset
6319     cperl-label-offset cperl-extra-newline-before-brace
6320     cperl-merge-trailing-else
6321     cperl-continued-statement-offset))
6322
6323 (defconst cperl-style-alist
6324   '(("CPerl"                         ; =GNU without extra-newline-before-brace
6325      (cperl-indent-level               .  2)
6326      (cperl-brace-offset               .  0)
6327      (cperl-continued-brace-offset     .  0)
6328      (cperl-label-offset               . -2)
6329      (cperl-extra-newline-before-brace .  nil)
6330      (cperl-merge-trailing-else        .  t)
6331      (cperl-continued-statement-offset .  2))
6332     ("PerlStyle"                        ; CPerl with 4 as indent
6333      (cperl-indent-level               .  4)
6334      (cperl-brace-offset               .  0)
6335      (cperl-continued-brace-offset     .  0)
6336      (cperl-label-offset               . -4)
6337      (cperl-extra-newline-before-brace .  nil)
6338      (cperl-merge-trailing-else        .  t)
6339      (cperl-continued-statement-offset .  4))
6340     ("GNU"
6341      (cperl-indent-level               .  2)
6342      (cperl-brace-offset               .  0)
6343      (cperl-continued-brace-offset     .  0)
6344      (cperl-label-offset               . -2)
6345      (cperl-extra-newline-before-brace .  t)
6346      (cperl-merge-trailing-else        .  nil)
6347      (cperl-continued-statement-offset .  2))
6348     ("K&R"
6349      (cperl-indent-level               .  5)
6350      (cperl-brace-offset               .  0)
6351      (cperl-continued-brace-offset     . -5)
6352      (cperl-label-offset               . -5)
6353      ;;(cperl-extra-newline-before-brace .  nil) ; ???
6354      (cperl-merge-trailing-else        .  nil)
6355      (cperl-continued-statement-offset .  5))
6356     ("BSD"
6357      (cperl-indent-level               .  4)
6358      (cperl-brace-offset               .  0)
6359      (cperl-continued-brace-offset     . -4)
6360      (cperl-label-offset               . -4)
6361      ;;(cperl-extra-newline-before-brace .  nil) ; ???
6362      (cperl-continued-statement-offset .  4))
6363     ("C++"
6364      (cperl-indent-level               .  4)
6365      (cperl-brace-offset               .  0)
6366      (cperl-continued-brace-offset     . -4)
6367      (cperl-label-offset               . -4)
6368      (cperl-continued-statement-offset .  4)
6369      (cperl-merge-trailing-else        .  nil)
6370      (cperl-extra-newline-before-brace .  t))
6371     ("Current")
6372     ("Whitesmith"
6373      (cperl-indent-level               .  4)
6374      (cperl-brace-offset               .  0)
6375      (cperl-continued-brace-offset     .  0)
6376      (cperl-label-offset               . -4)
6377      ;;(cperl-extra-newline-before-brace .  nil) ; ???
6378      (cperl-continued-statement-offset .  4)))
6379   "(Experimental) list of variables to set to get a particular indentation style.
6380 Should be used via `cperl-set-style' or via Perl menu.")
6381
6382 (defun cperl-set-style (style)
6383   "Set CPerl mode variables to use one of several different indentation styles.
6384 The arguments are a string representing the desired style.
6385 The list of styles is in `cperl-style-alist', available styles
6386 are GNU, K&R, BSD, C++ and Whitesmith.
6387
6388 The current value of style is memorized (unless there is a memorized
6389 data already), may be restored by `cperl-set-style-back'.
6390
6391 Chosing \"Current\" style will not change style, so this may be used for
6392 side-effect of memorizing only."
6393   (interactive
6394    (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
6395                        cperl-style-alist)))
6396      (list (completing-read "Enter style: " list nil 'insist))))
6397   (or cperl-old-style
6398       (setq cperl-old-style
6399             (mapcar (function
6400                      (lambda (name)
6401                        (cons name (eval name))))
6402                     cperl-styles-entries)))
6403   (let ((style (cdr (assoc style cperl-style-alist))) setting str sym)
6404     (while style
6405       (setq setting (car style) style (cdr style))
6406       (set (car setting) (cdr setting)))))
6407
6408 (defun cperl-set-style-back ()
6409   "Restore a style memorised by `cperl-set-style'."
6410   (interactive)
6411   (or cperl-old-style (error "The style was not changed"))
6412   (let (setting)
6413     (while cperl-old-style
6414       (setq setting (car cperl-old-style)
6415             cperl-old-style (cdr cperl-old-style))
6416       (set (car setting) (cdr setting)))))
6417
6418 (defun cperl-check-syntax ()
6419   (interactive)
6420   (require 'mode-compile)
6421   (let ((perl-dbg-flags (concat cperl-extra-perl-args " -wc")))
6422     (eval '(mode-compile))))            ; Avoid a warning
6423
6424 (defun cperl-info-buffer (type)
6425   ;; Returns buffer with documentation.  Creates if missing.
6426   ;; If TYPE, this vars buffer.
6427   ;; Special care is taken to not stomp over an existing info buffer
6428   (let* ((bname (if type "*info-perl-var*" "*info-perl*"))
6429          (info (get-buffer bname))
6430          (oldbuf (get-buffer "*info*")))
6431     (if info info
6432       (save-window-excursion
6433         ;; Get Info running
6434         (require 'info)
6435         (cond (oldbuf
6436                (set-buffer oldbuf)
6437                (rename-buffer "*info-perl-tmp*")))
6438         (save-window-excursion
6439           (info))
6440         (Info-find-node cperl-info-page (if type "perlvar" "perlfunc"))
6441         (set-buffer "*info*")
6442         (rename-buffer bname)
6443         (cond (oldbuf
6444                (set-buffer "*info-perl-tmp*")
6445                (rename-buffer "*info*")
6446                (set-buffer bname)))
6447         (make-local-variable 'window-min-height)
6448         (setq window-min-height 2)
6449         (current-buffer)))))
6450
6451 (defun cperl-word-at-point (&optional p)
6452   "Return the word at point or at P."
6453   (save-excursion
6454     (if p (goto-char p))
6455     (or (cperl-word-at-point-hard)
6456         (progn
6457           (require 'etags)
6458           (funcall (or (and (boundp 'find-tag-default-function)
6459                             find-tag-default-function)
6460                        (get major-mode 'find-tag-default-function)
6461                        ;; XEmacs 19.12 has `find-tag-default-hook'; it is
6462                        ;; automatically used within `find-tag-default':
6463                        'find-tag-default))))))
6464
6465 (defun cperl-info-on-command (command)
6466   "Show documentation for Perl command COMMAND in other window.
6467 If perl-info buffer is shown in some frame, uses this frame.
6468 Customized by setting variables `cperl-shrink-wrap-info-frame',
6469 `cperl-max-help-size'."
6470   (interactive
6471    (let* ((default (cperl-word-at-point))
6472           (read (read-string
6473                  (format "Find doc for Perl function (default %s): "
6474                          default))))
6475      (list (if (equal read "")
6476                default
6477              read))))
6478
6479   (let ((buffer (current-buffer))
6480         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
6481         pos isvar height iniheight frheight buf win fr1 fr2 iniwin not-loner
6482         max-height char-height buf-list)
6483     (if (string-match "^-[a-zA-Z]$" command)
6484         (setq cmd-desc "^-X[ \t\n]"))
6485     (setq isvar (string-match "^[$@%]" command)
6486           buf (cperl-info-buffer isvar)
6487           iniwin (selected-window)
6488           fr1 (window-frame iniwin))
6489     (set-buffer buf)
6490     (beginning-of-buffer)
6491     (or isvar
6492         (progn (re-search-forward "^-X[ \t\n]")
6493                (forward-line -1)))
6494     (if (re-search-forward cmd-desc nil t)
6495         (progn
6496           ;; Go back to beginning of the group (ex, for qq)
6497           (if (re-search-backward "^[ \t\n\f]")
6498               (forward-line 1))
6499           (beginning-of-line)
6500           ;; Get some of
6501           (setq pos (point)
6502                 buf-list (list buf "*info-perl-var*" "*info-perl*"))
6503           (while (and (not win) buf-list)
6504             (setq win (get-buffer-window (car buf-list) t))
6505             (setq buf-list (cdr buf-list)))
6506           (or (not win)
6507               (eq (window-buffer win) buf)
6508               (set-window-buffer win buf))
6509           (and win (setq fr2 (window-frame win)))
6510           (if (or (not fr2) (eq fr1 fr2))
6511               (pop-to-buffer buf)
6512             (special-display-popup-frame buf) ; Make it visible
6513             (select-window win))
6514           (goto-char pos)               ; Needed (?!).
6515           ;; Resize
6516           (setq iniheight (window-height)
6517                 frheight (frame-height)
6518                 not-loner (< iniheight (1- frheight))) ; Are not alone
6519           (cond ((if not-loner cperl-max-help-size
6520                    cperl-shrink-wrap-info-frame)
6521                  (setq height
6522                        (+ 2
6523                           (count-lines
6524                            pos
6525                            (save-excursion
6526                              (if (re-search-forward
6527                                   "^[ \t][^\n]*\n+\\([^ \t\n\f]\\|\\'\\)" nil t)
6528                                  (match-beginning 0) (point-max)))))
6529                        max-height
6530                        (if not-loner
6531                            (/ (* (- frheight 3) cperl-max-help-size) 100)
6532                          (setq char-height (frame-char-height))
6533                          ;; Non-functioning under OS/2:
6534                          (if (eq char-height 1) (setq char-height 18))
6535                          ;; Title, menubar, + 2 for slack
6536                          (- (/ (x-display-pixel-height) char-height) 4)))
6537                  (if (> height max-height) (setq height max-height))
6538                  ;;(message "was %s doing %s" iniheight height)
6539                  (if not-loner
6540                      (enlarge-window (- height iniheight))
6541                    (set-frame-height (window-frame win) (1+ height)))))
6542           (set-window-start (selected-window) pos))
6543       (message "No entry for %s found." command))
6544     ;;(pop-to-buffer buffer)
6545     (select-window iniwin)))
6546
6547 (defun cperl-info-on-current-command ()
6548   "Show documentation for Perl command at point in other window."
6549   (interactive)
6550   (cperl-info-on-command (cperl-word-at-point)))
6551
6552 (defun cperl-imenu-info-imenu-search ()
6553   (if (looking-at "^-X[ \t\n]") nil
6554     (re-search-backward
6555      "^\n\\([-a-zA-Z_]+\\)[ \t\n]")
6556     (forward-line 1)))
6557
6558 (defun cperl-imenu-info-imenu-name ()
6559   (buffer-substring
6560    (match-beginning 1) (match-end 1)))
6561
6562 (defun cperl-imenu-on-info ()
6563   (interactive)
6564   (let* ((buffer (current-buffer))
6565          imenu-create-index-function
6566          imenu-prev-index-position-function
6567          imenu-extract-index-name-function
6568          (index-item (save-restriction
6569                        (save-window-excursion
6570                          (set-buffer (cperl-info-buffer nil))
6571                          (setq imenu-create-index-function
6572                                'imenu-default-create-index-function
6573                                imenu-prev-index-position-function
6574                                'cperl-imenu-info-imenu-search
6575                                imenu-extract-index-name-function
6576                                'cperl-imenu-info-imenu-name)
6577                          (imenu-choose-buffer-index)))))
6578     (and index-item
6579          (progn
6580            (push-mark)
6581            (pop-to-buffer "*info-perl*")
6582            (cond
6583             ((markerp (cdr index-item))
6584              (goto-char (marker-position (cdr index-item))))
6585             (t
6586              (goto-char (cdr index-item))))
6587            (set-window-start (selected-window) (point))
6588            (pop-to-buffer buffer)))))
6589
6590 (defun cperl-lineup (beg end &optional step minshift)
6591   "Lineup construction in a region.
6592 Beginning of region should be at the start of a construction.
6593 All first occurrences of this construction in the lines that are
6594 partially contained in the region are lined up at the same column.
6595
6596 MINSHIFT is the minimal amount of space to insert before the construction.
6597 STEP is the tabwidth to position constructions.
6598 If STEP is nil, `cperl-lineup-step' will be used
6599 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
6600 Will not move the position at the start to the left."
6601   (interactive "r")
6602   (let (search col tcol seen b e)
6603     (save-excursion
6604       (goto-char end)
6605       (end-of-line)
6606       (setq end (point-marker))
6607       (goto-char beg)
6608       (skip-chars-forward " \t\f")
6609       (setq beg (point-marker))
6610       (indent-region beg end nil)
6611       (goto-char beg)
6612       (setq col (current-column))
6613       (if (looking-at "[a-zA-Z0-9_]")
6614           (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
6615               (setq search
6616                     (concat "\\<"
6617                             (regexp-quote
6618                              (buffer-substring (match-beginning 0)
6619                                                (match-end 0))) "\\>"))
6620             (error "Cannot line up in a middle of the word"))
6621         (if (looking-at "$")
6622             (error "Cannot line up end of line"))
6623         (setq search (regexp-quote (char-to-string (following-char)))))
6624       (setq step (or step cperl-lineup-step cperl-indent-level))
6625       (or minshift (setq minshift 1))
6626       (while (progn
6627                (beginning-of-line 2)
6628                (and (< (point) end)
6629                     (re-search-forward search end t)
6630                     (goto-char (match-beginning 0))))
6631         (setq tcol (current-column) seen t)
6632         (if (> tcol col) (setq col tcol)))
6633       (or seen
6634           (error "The construction to line up occurred only once"))
6635       (goto-char beg)
6636       (setq col (+ col minshift))
6637       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
6638       (while
6639           (progn
6640             (setq e (point))
6641             (skip-chars-backward " \t")
6642             (delete-region (point) e)
6643             (indent-to-column col) ;(make-string (- col (current-column)) ?\ ))
6644             (beginning-of-line 2)
6645             (and (< (point) end)
6646                  (re-search-forward search end t)
6647                  (goto-char (match-beginning 0)))))))) ; No body
6648
6649 (defun cperl-etags (&optional add all files)
6650   "Run etags with appropriate options for Perl files.
6651 If optional argument ALL is `recursive', will process Perl files
6652 in subdirectories too."
6653   (interactive)
6654   (let ((cmd "etags")
6655         (args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\(([^()]*)[ \t]*\\)?\\([{#]\\|$\\)\\)/\\4/"))
6656         res)
6657     (if add (setq args (cons "-a" args)))
6658     (or files (setq files (list buffer-file-name)))
6659     (cond
6660      ((eq all 'recursive)
6661       ;;(error "Not implemented: recursive")
6662       (setq args (append (list "-e"
6663                                "sub wanted {push @ARGV, $File::Find::name if /\\.[pP][Llm]$/}
6664                                 use File::Find;
6665                                 find(\\&wanted, '.');
6666                                 exec @ARGV;"
6667                                cmd) args)
6668             cmd "perl"))
6669      (all
6670       ;;(error "Not implemented: all")
6671       (setq args (append (list "-e"
6672                                "push @ARGV, <*.PL *.pl *.pm>;
6673                                 exec @ARGV;"
6674                                cmd) args)
6675             cmd "perl"))
6676      (t
6677       (setq args (append args files))))
6678     (setq res (apply 'call-process cmd nil nil nil args))
6679     (or (eq res 0)
6680         (message "etags returned \"%s\"" res))))
6681
6682 (defun cperl-toggle-auto-newline ()
6683   "Toggle the state of `cperl-auto-newline'."
6684   (interactive)
6685   (setq cperl-auto-newline (not cperl-auto-newline))
6686   (message "Newlines will %sbe auto-inserted now."
6687            (if cperl-auto-newline "" "not ")))
6688
6689 (defun cperl-toggle-abbrev ()
6690   "Toggle the state of automatic keyword expansion in CPerl mode."
6691   (interactive)
6692   (abbrev-mode (if abbrev-mode 0 1))
6693   (message "Perl control structure will %sbe auto-inserted now."
6694            (if abbrev-mode "" "not ")))
6695
6696
6697 (defun cperl-toggle-electric ()
6698   "Toggle the state of parentheses doubling in CPerl mode."
6699   (interactive)
6700   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
6701   (message "Parentheses will %sbe auto-doubled now."
6702            (if (cperl-val 'cperl-electric-parens) "" "not ")))
6703
6704 (defun cperl-toggle-autohelp ()
6705   "Toggle the state of Auto-Help on Perl constructs (put in the message area).
6706 Delay of auto-help controlled by `cperl-lazy-help-time'."
6707   (interactive)
6708   (if (fboundp 'run-with-idle-timer)
6709       (progn
6710         (if cperl-lazy-installed
6711             (cperl-lazy-unstall)
6712           (cperl-lazy-install))
6713         (message "Perl help messages will %sbe automatically shown now."
6714                  (if cperl-lazy-installed "" "not ")))
6715     (message "Cannot automatically show Perl help messages - run-with-idle-timer missing.")))
6716
6717 (defun cperl-toggle-construct-fix ()
6718   "Toggle whether `indent-region'/`indent-sexp' fix whitespace too."
6719   (interactive)
6720   (setq cperl-indent-region-fix-constructs
6721         (if cperl-indent-region-fix-constructs
6722             nil
6723           1))
6724   (message "indent-region/indent-sexp will %sbe automatically fix whitespace."
6725            (if cperl-indent-region-fix-constructs "" "not ")))
6726
6727 ;;;; Tags file creation.
6728
6729 (defvar cperl-tmp-buffer " *cperl-tmp*")
6730
6731 (defun cperl-setup-tmp-buf ()
6732   (set-buffer (get-buffer-create cperl-tmp-buffer))
6733   (set-syntax-table cperl-mode-syntax-table)
6734   (buffer-disable-undo)
6735   (auto-fill-mode 0)
6736   (if cperl-use-syntax-table-text-property-for-tags
6737       (progn
6738         (make-local-variable 'parse-sexp-lookup-properties)
6739         ;; Do not introduce variable if not needed, we check it!
6740         (set 'parse-sexp-lookup-properties t))))
6741
6742 (defun cperl-xsub-scan ()
6743   (require 'cl)
6744   (require 'imenu)
6745   (let ((index-alist '())
6746         (prev-pos 0) index index1 name package prefix)
6747     (goto-char (point-min))
6748     (if noninteractive
6749         (message "Scanning XSUB for index")
6750       (imenu-progress-message prev-pos 0))
6751     ;; Search for the function
6752     (progn ;;save-match-data
6753       (while (re-search-forward
6754               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
6755               nil t)
6756         (or noninteractive
6757             (imenu-progress-message prev-pos))
6758         (cond
6759          ((match-beginning 2)           ; SECTION
6760           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
6761           (goto-char (match-beginning 0))
6762           (skip-chars-forward " \t")
6763           (forward-char 1)
6764           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
6765               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
6766             (setq prefix nil)))
6767          ((not package) nil)            ; C language section
6768          ((match-beginning 3)           ; XSUB
6769           (goto-char (1+ (match-beginning 3)))
6770           (setq index (imenu-example--name-and-position))
6771           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
6772           (if (and prefix (string-match (concat "^" prefix) name))
6773               (setq name (substring name (length prefix))))
6774           (cond ((string-match "::" name) nil)
6775                 (t
6776                  (setq index1 (cons (concat package "::" name) (cdr index)))
6777                  (push index1 index-alist)))
6778           (setcar index name)
6779           (push index index-alist))
6780          (t                             ; BOOT: section
6781           ;; (beginning-of-line)
6782           (setq index (imenu-example--name-and-position))
6783           (setcar index (concat package "::BOOT:"))
6784           (push index index-alist)))))
6785     (or noninteractive
6786         (imenu-progress-message prev-pos 100))
6787     index-alist))
6788
6789 (defvar cperl-unreadable-ok nil)
6790
6791 (defun cperl-find-tags (ifile xs topdir)
6792   (let ((b (get-buffer cperl-tmp-buffer)) ind lst elt pos ret rel
6793         (cperl-pod-here-fontify nil) f file)
6794     (save-excursion
6795       (if b (set-buffer b)
6796         (cperl-setup-tmp-buf))
6797       (erase-buffer)
6798       (condition-case err
6799           (setq file (car (insert-file-contents ifile)))
6800         (error (if cperl-unreadable-ok nil
6801                  (if (y-or-n-p
6802                       (format "File %s unreadable.  Continue? " ifile))
6803                      (setq cperl-unreadable-ok t)
6804                    (error "Aborting: unreadable file %s" ifile)))))
6805       (if (not file)
6806           (message "Unreadable file %s" ifile)
6807         (message "Scanning file %s ..." file)
6808         (if (and cperl-use-syntax-table-text-property-for-tags
6809                  (not xs))
6810             (condition-case err         ; after __END__ may have garbage
6811                 (cperl-find-pods-heres nil nil noninteractive)
6812               (error (message "While scanning for syntax: %s" err))))
6813         (if xs
6814             (setq lst (cperl-xsub-scan))
6815           (setq ind (cperl-imenu--create-perl-index))
6816           (setq lst (cdr (assoc "+Unsorted List+..." ind))))
6817         (setq lst
6818               (mapcar
6819                (function
6820                 (lambda (elt)
6821                   (cond ((string-match "^[_a-zA-Z]" (car elt))
6822                          (goto-char (cdr elt))
6823                          (beginning-of-line) ; pos should be of the start of the line
6824                          (list (car elt)
6825                                (point)
6826                                (1+ (count-lines 1 (point))) ; 1+ since at beg-o-l
6827                                (buffer-substring (progn
6828                                                    (goto-char (cdr elt))
6829                                                    ;; After name now...
6830                                                    (or (eolp) (forward-char 1))
6831                                                    (point))
6832                                                  (progn
6833                                                    (beginning-of-line)
6834                                                    (point))))))))
6835                lst))
6836         (erase-buffer)
6837         (while lst
6838           (setq elt (car lst) lst (cdr lst))
6839           (if elt
6840               (progn
6841                 (insert (elt elt 3)
6842                         127
6843                         (if (string-match "^package " (car elt))
6844                             (substring (car elt) 8)
6845                           (car elt) )
6846                         1
6847                         (number-to-string (elt elt 2)) ; Line
6848                         ","
6849                         (number-to-string (1- (elt elt 1))) ; Char pos 0-based
6850                         "\n")
6851                 (if (and (string-match "^[_a-zA-Z]+::" (car elt))
6852                          (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
6853                                        (elt elt 3)))
6854                     ;; Need to insert the name without package as well
6855                     (setq lst (cons (cons (substring (elt elt 3) 
6856                                                      (match-beginning 1)
6857                                                      (match-end 1))
6858                                           (cdr elt))
6859                                     lst))))))
6860         (setq pos (point))
6861         (goto-char 1)
6862         (setq rel file)
6863         ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
6864         (set-text-properties 0 (length rel) nil rel)
6865         (and (equal topdir (substring rel 0 (length topdir)))
6866              (setq rel (substring file (length topdir))))
6867         (insert "\f\n" rel "," (number-to-string (1- pos)) "\n")
6868         (setq ret (buffer-substring 1 (point-max)))
6869         (erase-buffer)
6870         (or noninteractive
6871             (message "Scanning file %s finished" file))
6872         ret))))
6873
6874 (defun cperl-add-tags-recurse-noxs ()
6875   "Add to TAGS data for Perl (skipping XSUBs) in the current directory 
6876 and kids. Use as
6877   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
6878         -f cperl-add-tags-recurse-noxs
6879 "
6880   (cperl-write-tags nil nil t t nil t))
6881
6882 (defun cperl-add-tags-recurse-noxs-fullpath ()
6883   "Add to TAGS data for Perl (skipping XSUBs) in the current directory 
6884 and kids, using fullpath, so TAGS is relocatable. Use as
6885   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
6886         -f cperl-add-tags-recurse-noxs-fullpath
6887 "
6888   (cperl-write-tags nil nil t t nil t ""))
6889
6890 (defun cperl-add-tags-recurse ()
6891   "Add to TAGS file data for Perl files in the current directory and kids.
6892 Use as
6893   emacs -batch -q -no-site-file -l emacs/cperl-mode.el \
6894         -f cperl-add-tags-recurse
6895 "
6896   (cperl-write-tags nil nil t t))
6897
6898 (defun cperl-write-tags (&optional file erase recurse dir inbuffer noxs topdir)
6899   ;; If INBUFFER, do not select buffer, and do not save
6900   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
6901   (require 'etags)
6902   (if file nil
6903     (setq file (if dir default-directory (buffer-file-name)))
6904     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
6905   (or topdir
6906       (setq topdir default-directory))
6907   (let ((tags-file-name "TAGS")
6908         (case-fold-search (eq system-type 'emx))
6909         xs rel tm)
6910     (save-excursion
6911       (cond (inbuffer nil)              ; Already there
6912             ((file-exists-p tags-file-name)
6913              (if cperl-xemacs-p
6914                  (visit-tags-table-buffer)
6915                (visit-tags-table-buffer tags-file-name)))
6916             (t (set-buffer (find-file-noselect tags-file-name))))
6917       (cond
6918        (dir
6919         (cond ((eq erase 'ignore))
6920               (erase
6921                (erase-buffer)
6922                (setq erase 'ignore)))
6923         (let ((files
6924                (condition-case err
6925                    (directory-files file t
6926                                     (if recurse nil cperl-scan-files-regexp)
6927                                     t)
6928                  (error
6929                   (if cperl-unreadable-ok nil
6930                     (if (y-or-n-p
6931                          (format "Directory %s unreadable.  Continue? " file))
6932                         (setq cperl-unreadable-ok t
6933                               tm nil)   ; Return empty list
6934                       (error "Aborting: unreadable directory %s" file)))))))
6935           (mapcar (function 
6936                    (lambda (file)
6937                      (cond
6938                       ((string-match cperl-noscan-files-regexp file)
6939                        nil)
6940                       ((not (file-directory-p file))
6941                        (if (string-match cperl-scan-files-regexp file)
6942                            (cperl-write-tags file erase recurse nil t noxs topdir)))
6943                       ((not recurse) nil)
6944                       (t (cperl-write-tags file erase recurse t t noxs topdir)))))
6945                   files)))
6946        (t
6947         (setq xs (string-match "\\.xs$" file))
6948         (if (not (and xs noxs))
6949             (progn
6950               (cond ((eq erase 'ignore) (goto-char (point-max)))
6951                     (erase (erase-buffer))
6952                     (t
6953                      (goto-char 1)
6954                      (setq rel file)
6955                      ;; On case-preserving filesystems (EMX on OS/2) case might be encoded in properties
6956                      (set-text-properties 0 (length rel) nil rel)
6957                      (and (equal topdir (substring rel 0 (length topdir)))
6958                           (setq rel (substring file (length topdir))))
6959                      (if (search-forward (concat "\f\n" rel ",") nil t)
6960                          (progn
6961                            (search-backward "\f\n")
6962                            (delete-region (point)
6963                                           (save-excursion
6964                                             (forward-char 1)
6965                                             (if (search-forward "\f\n"
6966                                                                 nil 'toend)
6967                                                 (- (point) 2)
6968                                               (point-max)))))
6969                        (goto-char (point-max)))))
6970               (insert (cperl-find-tags file xs topdir))))))
6971       (if inbuffer nil                  ; Delegate to the caller
6972         (save-buffer 0)                 ; No backup
6973         (if (fboundp 'initialize-new-tags-table) ; Do we need something special in XEmacs?
6974             (initialize-new-tags-table))))))
6975
6976 (defvar cperl-tags-hier-regexp-list
6977   (concat
6978    "^\\("
6979       "\\(package\\)\\>"
6980      "\\|"
6981       "sub\\>[^\n]+::"
6982      "\\|"
6983       "[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::" ; XSUB?
6984      "\\|"
6985       "[ \t]*BOOT:\C-?[^\n]+::"         ; BOOT section
6986    "\\)"))
6987
6988 (defvar cperl-hierarchy '(() ())
6989   "Global hierarchy of classes.")
6990
6991 (defun cperl-tags-hier-fill ()
6992   ;; Suppose we are in a tag table cooked by cperl.
6993   (goto-char 1)
6994   (let (type pack name pos line chunk ord cons1 file str info fileind)
6995     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
6996       (setq pos (match-beginning 0)
6997             pack (match-beginning 2))
6998       (beginning-of-line)
6999       (if (looking-at (concat
7000                        "\\([^\n]+\\)"
7001                        "\C-?"
7002                        "\\([^\n]+\\)"
7003                        "\C-a"
7004                        "\\([0-9]+\\)"
7005                        ","
7006                        "\\([0-9]+\\)"))
7007           (progn
7008             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
7009                   name (buffer-substring (match-beginning 2) (match-end 2))
7010                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
7011                   line (buffer-substring (match-beginning 3) (match-end 3))
7012                   ord (if pack 1 0)
7013                   file (file-of-tag)
7014                   fileind (format "%s:%s" file line)
7015                   ;; Moves to beginning of the next line:
7016                   info (cperl-etags-snarf-tag file line))
7017             ;; Move back
7018             (forward-char -1)
7019             ;; Make new member of hierarchy name ==> file ==> pos if needed
7020             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
7021                 ;; Name known
7022                 (setcdr cons1 (cons (cons fileind (vector file info))
7023                                     (cdr cons1)))
7024               ;; First occurrence of the name, start alist
7025               (setq cons1 (cons name (list (cons fileind (vector file info)))))
7026               (if pack
7027                   (setcar (cdr cperl-hierarchy)
7028                           (cons cons1 (nth 1 cperl-hierarchy)))
7029                 (setcar cperl-hierarchy
7030                         (cons cons1 (car cperl-hierarchy)))))))
7031       (end-of-line))))
7032
7033 (defun cperl-tags-hier-init (&optional update)
7034   "Show hierarchical menu of classes and methods.
7035 Finds info about classes by a scan of loaded TAGS files.
7036 Supposes that the TAGS files contain fully qualified function names.
7037 One may build such TAGS files from CPerl mode menu."
7038   (interactive)
7039   (require 'etags)
7040   (require 'imenu)
7041   (if (or update (null (nth 2 cperl-hierarchy)))
7042       (let ((remover (function (lambda (elt) ; (name (file1...) (file2..))
7043                                  (or (nthcdr 2 elt)
7044                                      ;; Only in one file
7045                                      (setcdr elt (cdr (nth 1 elt)))))))
7046             pack name cons1 to l1 l2 l3 l4 b)
7047         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
7048         (setq cperl-hierarchy (list l1 l2 l3))
7049         (if cperl-xemacs-p              ; Not checked
7050             (progn
7051               (or tags-file-name
7052                   ;; Does this work in XEmacs?
7053                   (call-interactively 'visit-tags-table))
7054               (message "Updating list of classes...")
7055               (set-buffer (get-file-buffer tags-file-name))
7056               (cperl-tags-hier-fill))
7057           (or tags-table-list
7058               (call-interactively 'visit-tags-table))
7059           (mapcar 
7060            (function
7061             (lambda (tagsfile)
7062               (message "Updating list of classes... %s" tagsfile)
7063               (set-buffer (get-file-buffer tagsfile))
7064               (cperl-tags-hier-fill)))
7065            tags-table-list)
7066           (message "Updating list of classes... postprocessing..."))
7067         (mapcar remover (car cperl-hierarchy))
7068         (mapcar remover (nth 1 cperl-hierarchy))
7069         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
7070                        (cons "Methods: " (car cperl-hierarchy))))
7071         (cperl-tags-treeify to 1)
7072         (setcar (nthcdr 2 cperl-hierarchy)
7073                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
7074         (message "Updating list of classes: done, requesting display...")
7075         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
7076         ))
7077   (or (nth 2 cperl-hierarchy)
7078       (error "No items found"))
7079   (setq update
7080 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
7081         (if (if (boundp 'display-popup-menus-p)
7082                 (let ((f 'display-popup-menus-p))
7083                   (funcall f))
7084               window-system)
7085             (x-popup-menu t (nth 2 cperl-hierarchy))
7086           (require 'tmm)
7087           (tmm-prompt (nth 2 cperl-hierarchy))))
7088   (if (and update (listp update))
7089       (progn (while (cdr update) (setq update (cdr update)))
7090              (setq update (car update)))) ; Get the last from the list
7091   (if (vectorp update)
7092       (progn
7093         (find-file (elt update 0))
7094         (cperl-etags-goto-tag-location (elt update 1))))
7095   (if (eq update -999) (cperl-tags-hier-init t)))
7096
7097 (defun cperl-tags-treeify (to level)
7098   ;; cadr of `to' is read-write.  On start it is a cons
7099   (let* ((regexp (concat "^\\(" (mapconcat
7100                                  'identity
7101                                  (make-list level "[_a-zA-Z0-9]+")
7102                                  "::")
7103                          "\\)\\(::\\)?"))
7104          (packages (cdr (nth 1 to)))
7105          (methods (cdr (nth 2 to)))
7106          l1 head tail cons1 cons2 ord writeto packs recurse
7107          root-packages root-functions ms many_ms same_name ps
7108          (move-deeper
7109           (function 
7110            (lambda (elt)
7111              (cond ((and (string-match regexp (car elt))
7112                          (or (eq ord 1) (match-end 2)))
7113                     (setq head (substring (car elt) 0 (match-end 1))
7114                           tail (if (match-end 2) (substring (car elt) 
7115                                                             (match-end 2)))
7116                           recurse t)
7117                     (if (setq cons1 (assoc head writeto)) nil
7118                       ;; Need to init new head
7119                       (setcdr writeto (cons (list head (list "Packages: ")
7120                                                   (list "Methods: "))
7121                                             (cdr writeto)))
7122                       (setq cons1 (nth 1 writeto)))
7123                     (setq cons2 (nth ord cons1)) ; Either packs or meths
7124                     (setcdr cons2 (cons elt (cdr cons2))))
7125                    ((eq ord 2)
7126                     (setq root-functions (cons elt root-functions)))
7127                    (t
7128                     (setq root-packages (cons elt root-packages))))))))
7129     (setcdr to l1)                      ; Init to dynamic space
7130     (setq writeto to)
7131     (setq ord 1)
7132     (mapcar move-deeper packages)
7133     (setq ord 2)
7134     (mapcar move-deeper methods)
7135     (if recurse
7136         (mapcar (function (lambda (elt)
7137                           (cperl-tags-treeify elt (1+ level))))
7138                 (cdr to)))
7139     ;;Now clean up leaders with one child only
7140     (mapcar (function (lambda (elt)
7141                         (if (not (and (listp (cdr elt)) 
7142                                       (eq (length elt) 2))) nil
7143                             (setcar elt (car (nth 1 elt)))
7144                             (setcdr elt (cdr (nth 1 elt))))))
7145             (cdr to))
7146     ;; Sort the roots of subtrees
7147     (if (default-value 'imenu-sort-function)
7148         (setcdr to
7149                 (sort (cdr to) (default-value 'imenu-sort-function))))
7150     ;; Now add back functions removed from display
7151     (mapcar (function (lambda (elt)
7152                         (setcdr to (cons elt (cdr to)))))
7153             (if (default-value 'imenu-sort-function)
7154                 (nreverse
7155                  (sort root-functions (default-value 'imenu-sort-function)))
7156               root-functions))
7157     ;; Now add back packages removed from display
7158     (mapcar (function (lambda (elt)
7159                         (setcdr to (cons (cons (concat "package " (car elt)) 
7160                                                (cdr elt)) 
7161                                          (cdr to)))))
7162             (if (default-value 'imenu-sort-function)
7163                 (nreverse
7164                  (sort root-packages (default-value 'imenu-sort-function)))
7165               root-packages))))
7166
7167 ;;;(x-popup-menu t
7168 ;;;   '(keymap "Name1"
7169 ;;;         ("Ret1" "aa")
7170 ;;;         ("Head1" "ab"
7171 ;;;          keymap "Name2"
7172 ;;;          ("Tail1" "x") ("Tail2" "y"))))
7173
7174 (defun cperl-list-fold (list name limit)
7175   (let (list1 list2 elt1 (num 0))
7176     (if (<= (length list) limit) list
7177       (setq list1 nil list2 nil)
7178       (while list
7179         (setq num (1+ num)
7180               elt1 (car list)
7181               list (cdr list))
7182         (if (<= num imenu-max-items)
7183             (setq list2 (cons elt1 list2))
7184           (setq list1 (cons (cons name
7185                                   (nreverse list2))
7186                             list1)
7187                 list2 (list elt1)
7188                 num 1)))
7189       (nreverse (cons (cons name
7190                             (nreverse list2))
7191                       list1)))))
7192
7193 (defun cperl-menu-to-keymap (menu &optional name)
7194   (let (list)
7195     (cons 'keymap
7196           (mapcar
7197            (function
7198             (lambda (elt)
7199               (cond ((listp (cdr elt))
7200                      (setq list (cperl-list-fold
7201                                  (cdr elt) (car elt) imenu-max-items))
7202                      (cons nil
7203                            (cons (car elt)
7204                                  (cperl-menu-to-keymap list))))
7205                     (t
7206                      (list (cdr elt) (car elt) t))))) ; t is needed in 19.34
7207            (cperl-list-fold menu "Root" imenu-max-items)))))
7208
7209 \f
7210 (defvar cperl-bad-style-regexp
7211   (mapconcat 'identity
7212              '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
7213                "[-<>=+^&|]+[^- \t\n=+<>~]") ; sign+ char 
7214              "\\|")
7215   "Finds places such that insertion of a whitespace may help a lot.")
7216
7217 (defvar cperl-not-bad-style-regexp
7218   (mapconcat 
7219    'identity
7220    '("[^-\t <>=+]\\(--\\|\\+\\+\\)"     ; var-- var++
7221      "[a-zA-Z0-9_][|&][a-zA-Z0-9_$]"    ; abc|def abc&def are often used.
7222      "&[(a-zA-Z0-9_$]"                  ; &subroutine &(var->field)
7223      "<\\$?\\sw+\\(\\.\\sw+\\)?>"       ; <IN> <stdin.h>
7224      "-[a-zA-Z][ \t]+[_$\"'`a-zA-Z]"    ; -f file, -t STDIN
7225      "-[0-9]"                           ; -5
7226      "\\+\\+"                           ; ++var
7227      "--"                               ; --var
7228      ".->"                              ; a->b
7229      "->"                               ; a SPACE ->b
7230      "\\[-"                             ; a[-1]
7231      "\\\\[&$@*\\\\]"                   ; \&func
7232      "^="                               ; =head
7233      "\\$."                             ; $|
7234      "<<[a-zA-Z_'\"`]"                  ; <<FOO, <<'FOO'
7235      "||"
7236      "&&"
7237      "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
7238      "-[a-zA-Z_0-9]+[ \t]*=>"           ; -option => value
7239      ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
7240      ;;"[*/+-|&<.]+="
7241      )
7242    "\\|")
7243   "If matches at the start of match found by `my-bad-c-style-regexp',
7244 insertion of a whitespace will not help.")
7245
7246 (defvar found-bad)
7247
7248 (defun cperl-find-bad-style ()
7249   "Find places in the buffer where insertion of a whitespace may help.
7250 Prompts user for insertion of spaces.
7251 Currently it is tuned to C and Perl syntax."
7252   (interactive)
7253   (let (found-bad (p (point)))
7254     (setq last-nonmenu-event 13)        ; To disable popup
7255     (beginning-of-buffer)
7256     (map-y-or-n-p "Insert space here? "
7257                   (lambda (arg) (insert " "))
7258                   'cperl-next-bad-style
7259                   '("location" "locations" "insert a space into")
7260                   '((?\C-r (lambda (arg)
7261                              (let ((buffer-quit-function
7262                                     'exit-recursive-edit))
7263                                (message "Exit with Esc Esc")
7264                                (recursive-edit)
7265                                t))      ; Consider acted upon
7266                            "edit, exit with Esc Esc")
7267                     (?e (lambda (arg)
7268                           (let ((buffer-quit-function
7269                                  'exit-recursive-edit))
7270                             (message "Exit with Esc Esc")
7271                             (recursive-edit)
7272                             t))         ; Consider acted upon
7273                         "edit, exit with Esc Esc"))
7274                   t)
7275     (if found-bad (goto-char found-bad)
7276       (goto-char p)
7277       (message "No appropriate place found"))))
7278
7279 (defun cperl-next-bad-style ()
7280   (let (p (not-found t) (point (point)) found)
7281     (while (and not-found
7282                 (re-search-forward cperl-bad-style-regexp nil 'to-end))
7283       (setq p (point))
7284       (goto-char (match-beginning 0))
7285       (if (or
7286            (looking-at cperl-not-bad-style-regexp)
7287            ;; Check for a < -b and friends
7288            (and (eq (following-char) ?\-)
7289                 (save-excursion
7290                   (skip-chars-backward " \t\n")
7291                   (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\( ?\[ ?\{))))
7292            ;; Now check for syntax type
7293            (save-match-data
7294              (setq found (point))
7295              (beginning-of-defun)
7296              (let ((pps (parse-partial-sexp (point) found)))
7297                (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
7298           (goto-char (match-end 0))
7299         (goto-char (1- p))
7300         (setq not-found nil
7301               found-bad found)))
7302     (not not-found)))
7303
7304 \f
7305 ;;; Getting help
7306 (defvar cperl-have-help-regexp
7307   ;;(concat "\\("
7308   (mapconcat
7309    'identity
7310    '("[$@%*&][0-9a-zA-Z_:]+\\([ \t]*[[{]\\)?" ; Usual variable
7311      "[$@]\\^[a-zA-Z]"                  ; Special variable
7312      "[$@][^ \n\t]"                     ; Special variable
7313      "-[a-zA-Z]"                        ; File test
7314      "\\\\[a-zA-Z0]"                    ; Special chars
7315      "^=[a-z][a-zA-Z0-9_]*"             ; POD sections
7316      "[-!&*+,-./<=>?\\\\^|~]+"          ; Operator
7317      "[a-zA-Z_0-9:]+"                   ; symbol or number
7318      "x="
7319      "#!")
7320    ;;"\\)\\|\\("
7321    "\\|")
7322   ;;"\\)"
7323   ;;)
7324   "Matches places in the buffer we can find help for.")
7325
7326 (defvar cperl-message-on-help-error t)
7327 (defvar cperl-help-from-timer nil)
7328
7329 (defun cperl-word-at-point-hard ()
7330   ;; Does not save-excursion
7331   ;; Get to the something meaningful
7332   (or (eobp) (eolp) (forward-char 1))
7333   (re-search-backward "[-a-zA-Z0-9_:!&*+,-./<=>?\\\\^|~$%@]"
7334                       (save-excursion (beginning-of-line) (point))
7335                       'to-beg)
7336   ;;  (cond
7337   ;;   ((or (eobp) (looking-at "[][ \t\n{}();,]")) ; Not at a symbol
7338   ;;    (skip-chars-backward " \n\t\r({[]});,")
7339   ;;    (or (bobp) (backward-char 1))))
7340   ;; Try to backtrace
7341   (cond
7342    ((looking-at "[a-zA-Z0-9_:]")        ; symbol
7343     (skip-chars-backward "a-zA-Z0-9_:")
7344     (cond
7345      ((and (eq (preceding-char) ?^)     ; $^I
7346            (eq (char-after (- (point) 2)) ?\$))
7347       (forward-char -2))
7348      ((memq (preceding-char) (append "*$@%&\\" nil)) ; *glob
7349       (forward-char -1))
7350      ((and (eq (preceding-char) ?\=)
7351            (eq (current-column) 1))
7352       (forward-char -1)))               ; =head1
7353     (if (and (eq (preceding-char) ?\<)
7354              (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <FH>
7355         (forward-char -1)))
7356    ((and (looking-at "=") (eq (preceding-char) ?x)) ; x=
7357     (forward-char -1))
7358    ((and (looking-at "\\^") (eq (preceding-char) ?\$)) ; $^I
7359     (forward-char -1))
7360    ((looking-at "[-!&*+,-./<=>?\\\\^|~]")
7361     (skip-chars-backward "-!&*+,-./<=>?\\\\^|~")
7362     (cond
7363      ((and (eq (preceding-char) ?\$)
7364            (not (eq (char-after (- (point) 2)) ?\$))) ; $-
7365       (forward-char -1))
7366      ((and (eq (following-char) ?\>)
7367            (string-match "[a-zA-Z0-9_]" (char-to-string (preceding-char)))
7368            (save-excursion
7369              (forward-sexp -1)
7370              (and (eq (preceding-char) ?\<)
7371                   (looking-at "\\$?[a-zA-Z0-9_:]+>")))) ; <FH>
7372       (search-backward "<"))))
7373    ((and (eq (following-char) ?\$)
7374          (eq (preceding-char) ?\<)
7375          (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <$fh>
7376     (forward-char -1)))
7377   (if (looking-at cperl-have-help-regexp)
7378       (buffer-substring (match-beginning 0) (match-end 0))))
7379
7380 (defun cperl-get-help ()
7381   "Get one-line docs on the symbol at the point.
7382 The data for these docs is a little bit obsolete and may be in fact longer
7383 than a line.  Your contribution to update/shorten it is appreciated."
7384   (interactive)
7385   (save-match-data                      ; May be called "inside" query-replace
7386     (save-excursion
7387       (let ((word (cperl-word-at-point-hard)))
7388         (if word
7389             (if (and cperl-help-from-timer ; Bail out if not in mainland
7390                      (not (string-match "^#!\\|\\\\\\|^=" word)) ; Show help even in comments/strings.
7391                      (or (memq (get-text-property (point) 'face)
7392                                '(font-lock-comment-face font-lock-string-face))
7393                          (memq (get-text-property (point) 'syntax-type)
7394                                '(pod here-doc format))))
7395                 nil
7396               (cperl-describe-perl-symbol word))
7397           (if cperl-message-on-help-error
7398               (message "Nothing found for %s..."
7399                        (buffer-substring (point) (min (+ 5 (point)) (point-max))))))))))
7400
7401 ;;; Stolen from perl-descr.el by Johan Vromans:
7402
7403 (defvar cperl-doc-buffer " *perl-doc*"
7404   "Where the documentation can be found.")
7405
7406 (defun cperl-describe-perl-symbol (val)
7407   "Display the documentation of symbol at point, a Perl operator."
7408   (let ((enable-recursive-minibuffers t)
7409         args-file regexp)
7410     (cond
7411      ((string-match "^[&*][a-zA-Z_]" val)
7412       (setq val (concat (substring val 0 1) "NAME")))
7413      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*\\[" val)
7414       (setq val (concat "@" (substring val 1 (match-end 1)))))
7415      ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*{" val)
7416       (setq val (concat "%" (substring val 1 (match-end 1)))))
7417      ((and (string= val "x") (string-match "^x=" val))
7418       (setq val "x="))
7419      ((string-match "^\\$[\C-a-\C-z]" val)
7420       (setq val (concat "$^" (char-to-string (+ ?A -1 (aref val 1))))))
7421      ((string-match "^CORE::" val)
7422       (setq val "CORE::"))
7423      ((string-match "^SUPER::" val)
7424       (setq val "SUPER::"))
7425      ((and (string= "<" val) (string-match "^<\\$?[a-zA-Z0-9_:]+>" val))
7426       (setq val "<NAME>")))
7427     (setq regexp (concat "^"
7428                          "\\([^a-zA-Z0-9_:]+[ \t]+\\)?"
7429                          (regexp-quote val)
7430                          "\\([ \t([/]\\|$\\)"))
7431
7432     ;; get the buffer with the documentation text
7433     (cperl-switch-to-doc-buffer)
7434
7435     ;; lookup in the doc
7436     (goto-char (point-min))
7437     (let ((case-fold-search nil))
7438       (list
7439        (if (re-search-forward regexp (point-max) t)
7440            (save-excursion
7441              (beginning-of-line 1)
7442              (let ((lnstart (point)))
7443                (end-of-line)
7444                (message "%s" (buffer-substring lnstart (point)))))
7445          (if cperl-message-on-help-error
7446              (message "No definition for %s" val)))))))
7447
7448 (defvar cperl-short-docs 'please-ignore-this-line
7449   ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl)
7450   "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5]
7451 ...     Range (list context); flip/flop [no flop when flip] (scalar context).
7452 ! ...   Logical negation.
7453 ... != ...      Numeric inequality.
7454 ... !~ ...      Search pattern, substitution, or translation (negated).
7455 $!      In numeric context: errno.  In a string context: error string.
7456 $\"     The separator which joins elements of arrays interpolated in strings.
7457 $#      The output format for printed numbers.  Default is %.15g or close.
7458 $$      Process number of this script.  Changes in the fork()ed child process.
7459 $%      The current page number of the currently selected output channel.
7460
7461         The following variables are always local to the current block:
7462
7463 $1      Match of the 1st set of parentheses in the last match (auto-local).
7464 $2      Match of the 2nd set of parentheses in the last match (auto-local).
7465 $3      Match of the 3rd set of parentheses in the last match (auto-local).
7466 $4      Match of the 4th set of parentheses in the last match (auto-local).
7467 $5      Match of the 5th set of parentheses in the last match (auto-local).
7468 $6      Match of the 6th set of parentheses in the last match (auto-local).
7469 $7      Match of the 7th set of parentheses in the last match (auto-local).
7470 $8      Match of the 8th set of parentheses in the last match (auto-local).
7471 $9      Match of the 9th set of parentheses in the last match (auto-local).
7472 $&      The string matched by the last pattern match (auto-local).
7473 $'      The string after what was matched by the last match (auto-local).
7474 $`      The string before what was matched by the last match (auto-local).
7475
7476 $(      The real gid of this process.
7477 $)      The effective gid of this process.
7478 $*      Deprecated: Set to 1 to do multiline matching within a string.
7479 $+      The last bracket matched by the last search pattern.
7480 $,      The output field separator for the print operator.
7481 $-      The number of lines left on the page.
7482 $.      The current input line number of the last filehandle that was read.
7483 $/      The input record separator, newline by default.
7484 $0      Name of the file containing the current perl script (read/write).
7485 $:     String may be broken after these characters to fill ^-lines in a format.
7486 $;      Subscript separator for multi-dim array emulation.  Default \"\\034\".
7487 $<      The real uid of this process.
7488 $=      The page length of the current output channel.  Default is 60 lines.
7489 $>      The effective uid of this process.
7490 $?      The status returned by the last ``, pipe close or `system'.
7491 $@      The perl error message from the last eval or do @var{EXPR} command.
7492 $ARGV   The name of the current file used with <> .
7493 $[      Deprecated: The index of the first element/char in an array/string.
7494 $\\     The output record separator for the print operator.
7495 $]      The perl version string as displayed with perl -v.
7496 $^      The name of the current top-of-page format.
7497 $^A     The current value of the write() accumulator for format() lines.
7498 $^D     The value of the perl debug (-D) flags.
7499 $^E     Information about the last system error other than that provided by $!.
7500 $^F     The highest system file descriptor, ordinarily 2.
7501 $^H     The current set of syntax checks enabled by `use strict'.
7502 $^I     The value of the in-place edit extension (perl -i option).
7503 $^L     What formats output to perform a formfeed.  Default is \f.
7504 $^M     A buffer for emergency memory allocation when running out of memory.
7505 $^O     The operating system name under which this copy of Perl was built.
7506 $^P     Internal debugging flag.
7507 $^T     The time the script was started.  Used by -A/-M/-C file tests.
7508 $^W     True if warnings are requested (perl -w flag).
7509 $^X     The name under which perl was invoked (argv[0] in C-speech).
7510 $_      The default input and pattern-searching space.
7511 $|      Auto-flush after write/print on current output channel?  Default 0.
7512 $~      The name of the current report format.
7513 ... % ...       Modulo division.
7514 ... %= ...      Modulo division assignment.
7515 %ENV    Contains the current environment.
7516 %INC    List of files that have been require-d or do-ne.
7517 %SIG    Used to set signal handlers for various signals.
7518 ... & ...       Bitwise and.
7519 ... && ...      Logical and.
7520 ... &&= ...     Logical and assignment.
7521 ... &= ...      Bitwise and assignment.
7522 ... * ...       Multiplication.
7523 ... ** ...      Exponentiation.
7524 *NAME   Glob: all objects refered by NAME.  *NAM1 = *NAM2 aliases NAM1 to NAM2.
7525 &NAME(arg0, ...)        Subroutine call.  Arguments go to @_.
7526 ... + ...       Addition.               +EXPR   Makes EXPR into scalar context.
7527 ++      Auto-increment (magical on strings).    ++EXPR  EXPR++
7528 ... += ...      Addition assignment.
7529 ,       Comma operator.
7530 ... - ...       Subtraction.
7531 --      Auto-decrement (NOT magical on strings).        --EXPR  EXPR--
7532 ... -= ...      Subtraction assignment.
7533 -A      Access time in days since script started.
7534 -B      File is a non-text (binary) file.
7535 -C      Inode change time in days since script started.
7536 -M      Age in days since script started.
7537 -O      File is owned by real uid.
7538 -R      File is readable by real uid.
7539 -S      File is a socket .
7540 -T      File is a text file.
7541 -W      File is writable by real uid.
7542 -X      File is executable by real uid.
7543 -b      File is a block special file.
7544 -c      File is a character special file.
7545 -d      File is a directory.
7546 -e      File exists .
7547 -f      File is a plain file.
7548 -g      File has setgid bit set.
7549 -k      File has sticky bit set.
7550 -l      File is a symbolic link.
7551 -o      File is owned by effective uid.
7552 -p      File is a named pipe (FIFO).
7553 -r      File is readable by effective uid.
7554 -s      File has non-zero size.
7555 -t      Tests if filehandle (STDIN by default) is opened to a tty.
7556 -u      File has setuid bit set.
7557 -w      File is writable by effective uid.
7558 -x      File is executable by effective uid.
7559 -z      File has zero size.
7560 .       Concatenate strings.
7561 ..      Range (list context); flip/flop (scalar context) operator.
7562 .=      Concatenate assignment strings
7563 ... / ...       Division.       /PATTERN/ioxsmg Pattern match
7564 ... /= ...      Division assignment.
7565 /PATTERN/ioxsmg Pattern match.
7566 ... < ...    Numeric less than. <pattern>       Glob.   See <NAME>, <> as well.
7567 <NAME>  Reads line from filehandle NAME (a bareword or dollar-bareword).
7568 <pattern>       Glob (Unless pattern is bareword/dollar-bareword - see <NAME>).
7569 <>      Reads line from union of files in @ARGV (= command line) and STDIN.
7570 ... << ...      Bitwise shift left.     <<      start of HERE-DOCUMENT.
7571 ... <= ...      Numeric less than or equal to.
7572 ... <=> ...     Numeric compare.
7573 ... = ...       Assignment.
7574 ... == ...      Numeric equality.
7575 ... =~ ...      Search pattern, substitution, or translation
7576 ... > ...       Numeric greater than.
7577 ... >= ...      Numeric greater than or equal to.
7578 ... >> ...      Bitwise shift right.
7579 ... >>= ...     Bitwise shift right assignment.
7580 ... ? ... : ... Condition=if-then-else operator.   ?PAT? One-time pattern match.
7581 ?PATTERN?       One-time pattern match.
7582 @ARGV   Command line arguments (not including the command name - see $0).
7583 @INC    List of places to look for perl scripts during do/include/use.
7584 @_    Parameter array for subroutines; result of split() unless in list context.
7585 \\  Creates reference to what follows, like \$var, or quotes non-\w in strings.
7586 \\0     Octal char, e.g. \\033.
7587 \\E     Case modification terminator.  See \\Q, \\L, and \\U.
7588 \\L     Lowercase until \\E .  See also \l, lc.
7589 \\U     Upcase until \\E .  See also \u, uc.
7590 \\Q     Quote metacharacters until \\E .  See also quotemeta.
7591 \\a     Alarm character (octal 007).
7592 \\b     Backspace character (octal 010).
7593 \\c     Control character, e.g. \\c[ .
7594 \\e     Escape character (octal 033).
7595 \\f     Formfeed character (octal 014).
7596 \\l     Lowercase the next character.  See also \\L and \\u, lcfirst.
7597 \\n     Newline character (octal 012 on most systems).
7598 \\r     Return character (octal 015 on most systems).
7599 \\t     Tab character (octal 011).
7600 \\u     Upcase the next character.  See also \\U and \\l, ucfirst.
7601 \\x     Hex character, e.g. \\x1b.
7602 ... ^ ...       Bitwise exclusive or.
7603 __END__ Ends program source.
7604 __DATA__        Ends program source.
7605 __FILE__        Current (source) filename.
7606 __LINE__        Current line in current source.
7607 __PACKAGE__     Current package.
7608 ARGV    Default multi-file input filehandle.  <ARGV> is a synonym for <>.
7609 ARGVOUT Output filehandle with -i flag.
7610 BEGIN { ... }   Immediately executed (during compilation) piece of code.
7611 END { ... }     Pseudo-subroutine executed after the script finishes.
7612 CHECK { ... }   Pseudo-subroutine executed after the script is compiled.
7613 INIT { ... }    Pseudo-subroutine executed before the script starts running.
7614 DATA    Input filehandle for what follows after __END__ or __DATA__.
7615 accept(NEWSOCKET,GENERICSOCKET)
7616 alarm(SECONDS)
7617 atan2(X,Y)
7618 bind(SOCKET,NAME)
7619 binmode(FILEHANDLE)
7620 caller[(LEVEL)]
7621 chdir(EXPR)
7622 chmod(LIST)
7623 chop[(LIST|VAR)]
7624 chown(LIST)
7625 chroot(FILENAME)
7626 close(FILEHANDLE)
7627 closedir(DIRHANDLE)
7628 ... cmp ...     String compare.
7629 connect(SOCKET,NAME)
7630 continue of { block } continue { block }.  Is executed after `next' or at end.
7631 cos(EXPR)
7632 crypt(PLAINTEXT,SALT)
7633 dbmclose(%HASH)
7634 dbmopen(%HASH,DBNAME,MODE)
7635 defined(EXPR)
7636 delete($HASH{KEY})
7637 die(LIST)
7638 do { ... }|SUBR while|until EXPR        executes at least once
7639 do(EXPR|SUBR([LIST]))   (with while|until executes at least once)
7640 dump LABEL
7641 each(%HASH)
7642 endgrent
7643 endhostent
7644 endnetent
7645 endprotoent
7646 endpwent
7647 endservent
7648 eof[([FILEHANDLE])]
7649 ... eq ...      String equality.
7650 eval(EXPR) or eval { BLOCK }
7651 exec(LIST)
7652 exit(EXPR)
7653 exp(EXPR)
7654 fcntl(FILEHANDLE,FUNCTION,SCALAR)
7655 fileno(FILEHANDLE)
7656 flock(FILEHANDLE,OPERATION)
7657 for (EXPR;EXPR;EXPR) { ... }
7658 foreach [VAR] (@ARRAY) { ... }
7659 fork
7660 ... ge ...      String greater than or equal.
7661 getc[(FILEHANDLE)]
7662 getgrent
7663 getgrgid(GID)
7664 getgrnam(NAME)
7665 gethostbyaddr(ADDR,ADDRTYPE)
7666 gethostbyname(NAME)
7667 gethostent
7668 getlogin
7669 getnetbyaddr(ADDR,ADDRTYPE)
7670 getnetbyname(NAME)
7671 getnetent
7672 getpeername(SOCKET)
7673 getpgrp(PID)
7674 getppid
7675 getpriority(WHICH,WHO)
7676 getprotobyname(NAME)
7677 getprotobynumber(NUMBER)
7678 getprotoent
7679 getpwent
7680 getpwnam(NAME)
7681 getpwuid(UID)
7682 getservbyname(NAME,PROTO)
7683 getservbyport(PORT,PROTO)
7684 getservent
7685 getsockname(SOCKET)
7686 getsockopt(SOCKET,LEVEL,OPTNAME)
7687 gmtime(EXPR)
7688 goto LABEL
7689 ... gt ...      String greater than.
7690 hex(EXPR)
7691 if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXPR if EXPR
7692 index(STR,SUBSTR[,OFFSET])
7693 int(EXPR)
7694 ioctl(FILEHANDLE,FUNCTION,SCALAR)
7695 join(EXPR,LIST)
7696 keys(%HASH)
7697 kill(LIST)
7698 last [LABEL]
7699 ... le ...      String less than or equal.
7700 length(EXPR)
7701 link(OLDFILE,NEWFILE)
7702 listen(SOCKET,QUEUESIZE)
7703 local(LIST)
7704 localtime(EXPR)
7705 log(EXPR)
7706 lstat(EXPR|FILEHANDLE|VAR)
7707 ... lt ...      String less than.
7708 m/PATTERN/iogsmx
7709 mkdir(FILENAME,MODE)
7710 msgctl(ID,CMD,ARG)
7711 msgget(KEY,FLAGS)
7712 msgrcv(ID,VAR,SIZE,TYPE.FLAGS)
7713 msgsnd(ID,MSG,FLAGS)
7714 my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, or %HASH).
7715 our VAR or our (VAR1,...) Lexically enable a global variable ($V, @A, or %H).
7716 ... ne ...      String inequality.
7717 next [LABEL]
7718 oct(EXPR)
7719 open(FILEHANDLE[,EXPR])
7720 opendir(DIRHANDLE,EXPR)
7721 ord(EXPR)       ASCII value of the first char of the string.
7722 pack(TEMPLATE,LIST)
7723 package NAME    Introduces package context.
7724 pipe(READHANDLE,WRITEHANDLE)    Create a pair of filehandles on ends of a pipe.
7725 pop(ARRAY)
7726 print [FILEHANDLE] [(LIST)]
7727 printf [FILEHANDLE] (FORMAT,LIST)
7728 push(ARRAY,LIST)
7729 q/STRING/       Synonym for 'STRING'
7730 qq/STRING/      Synonym for \"STRING\"
7731 qx/STRING/      Synonym for `STRING`
7732 rand[(EXPR)]
7733 read(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
7734 readdir(DIRHANDLE)
7735 readlink(EXPR)
7736 recv(SOCKET,SCALAR,LEN,FLAGS)
7737 redo [LABEL]
7738 rename(OLDNAME,NEWNAME)
7739 require [FILENAME | PERL_VERSION]
7740 reset[(EXPR)]
7741 return(LIST)
7742 reverse(LIST)
7743 rewinddir(DIRHANDLE)
7744 rindex(STR,SUBSTR[,OFFSET])
7745 rmdir(FILENAME)
7746 s/PATTERN/REPLACEMENT/gieoxsm
7747 scalar(EXPR)
7748 seek(FILEHANDLE,POSITION,WHENCE)
7749 seekdir(DIRHANDLE,POS)
7750 select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT)
7751 semctl(ID,SEMNUM,CMD,ARG)
7752 semget(KEY,NSEMS,SIZE,FLAGS)
7753 semop(KEY,...)
7754 send(SOCKET,MSG,FLAGS[,TO])
7755 setgrent
7756 sethostent(STAYOPEN)
7757 setnetent(STAYOPEN)
7758 setpgrp(PID,PGRP)
7759 setpriority(WHICH,WHO,PRIORITY)
7760 setprotoent(STAYOPEN)
7761 setpwent
7762 setservent(STAYOPEN)
7763 setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
7764 shift[(ARRAY)]
7765 shmctl(ID,CMD,ARG)
7766 shmget(KEY,SIZE,FLAGS)
7767 shmread(ID,VAR,POS,SIZE)
7768 shmwrite(ID,STRING,POS,SIZE)
7769 shutdown(SOCKET,HOW)
7770 sin(EXPR)
7771 sleep[(EXPR)]
7772 socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
7773 socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
7774 sort [SUBROUTINE] (LIST)
7775 splice(ARRAY,OFFSET[,LENGTH[,LIST]])
7776 split[(/PATTERN/[,EXPR[,LIMIT]])]
7777 sprintf(FORMAT,LIST)
7778 sqrt(EXPR)
7779 srand(EXPR)
7780 stat(EXPR|FILEHANDLE|VAR)
7781 study[(SCALAR)]
7782 sub [NAME [(format)]] { BODY }  sub NAME [(format)];    sub [(format)] {...}
7783 substr(EXPR,OFFSET[,LEN])
7784 symlink(OLDFILE,NEWFILE)
7785 syscall(LIST)
7786 sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
7787 system(LIST)
7788 syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
7789 tell[(FILEHANDLE)]
7790 telldir(DIRHANDLE)
7791 time
7792 times
7793 tr/SEARCHLIST/REPLACEMENTLIST/cds
7794 truncate(FILE|EXPR,LENGTH)
7795 umask[(EXPR)]
7796 undef[(EXPR)]
7797 unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR
7798 unlink(LIST)
7799 unpack(TEMPLATE,EXPR)
7800 unshift(ARRAY,LIST)
7801 until (EXPR) { ... }                                    EXPR until EXPR
7802 utime(LIST)
7803 values(%HASH)
7804 vec(EXPR,OFFSET,BITS)
7805 wait
7806 waitpid(PID,FLAGS)
7807 wantarray       Returns true if the sub/eval is called in list context.
7808 warn(LIST)
7809 while  (EXPR) { ... }                                   EXPR while EXPR
7810 write[(EXPR|FILEHANDLE)]
7811 ... x ...       Repeat string or array.
7812 x= ...  Repetition assignment.
7813 y/SEARCHLIST/REPLACEMENTLIST/
7814 ... | ...       Bitwise or.
7815 ... || ...      Logical or.
7816 ~ ...           Unary bitwise complement.
7817 #!      OS interpreter indicator.  If contains `perl', used for options, and -x.
7818 AUTOLOAD {...}  Shorthand for `sub AUTOLOAD {...}'.
7819 CORE::          Prefix to access builtin function if imported sub obscures it.
7820 SUPER::         Prefix to lookup for a method in @ISA classes.
7821 DESTROY         Shorthand for `sub DESTROY {...}'.
7822 ... EQ ...      Obsolete synonym of `eq'.
7823 ... GE ...      Obsolete synonym of `ge'.
7824 ... GT ...      Obsolete synonym of `gt'.
7825 ... LE ...      Obsolete synonym of `le'.
7826 ... LT ...      Obsolete synonym of `lt'.
7827 ... NE ...      Obsolete synonym of `ne'.
7828 abs [ EXPR ]    absolute value
7829 ... and ...             Low-precedence synonym for &&.
7830 bless REFERENCE [, PACKAGE]     Makes reference into an object of a package.
7831 chomp [LIST]    Strips $/ off LIST/$_.  Returns count.  Special if $/ eq ''!
7832 chr             Converts a number to char with the same ordinal.
7833 else            Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
7834 elsif           Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
7835 exists $HASH{KEY}       True if the key exists.
7836 format [NAME] =  Start of output format.  Ended by a single dot (.) on a line.
7837 formline PICTURE, LIST  Backdoor into \"format\" processing.
7838 glob EXPR       Synonym of <EXPR>.
7839 lc [ EXPR ]     Returns lowercased EXPR.
7840 lcfirst [ EXPR ]        Returns EXPR with lower-cased first letter.
7841 grep EXPR,LIST  or grep {BLOCK} LIST    Filters LIST via EXPR/BLOCK.
7842 map EXPR, LIST  or map {BLOCK} LIST     Applies EXPR/BLOCK to elts of LIST.
7843 no PACKAGE [SYMBOL1, ...]  Partial reverse for `use'.  Runs `unimport' method.
7844 not ...         Low-precedence synonym for ! - negation.
7845 ... or ...              Low-precedence synonym for ||.
7846 pos STRING    Set/Get end-position of the last match over this string, see \\G.
7847 quotemeta [ EXPR ]      Quote regexp metacharacters.
7848 qw/WORD1 .../           Synonym of split('', 'WORD1 ...')
7849 readline FH     Synonym of <FH>.
7850 readpipe CMD    Synonym of `CMD`.
7851 ref [ EXPR ]    Type of EXPR when dereferenced.
7852 sysopen FH, FILENAME, MODE [, PERM]     (MODE is numeric, see Fcntl.)
7853 tie VAR, PACKAGE, LIST  Hide an object behind a simple Perl variable.
7854 tied            Returns internal object for a tied data.
7855 uc [ EXPR ]     Returns upcased EXPR.
7856 ucfirst [ EXPR ]        Returns EXPR with upcased first letter.
7857 untie VAR       Unlink an object from a simple Perl variable.
7858 use PACKAGE [SYMBOL1, ...]  Compile-time `require' with consequent `import'.
7859 ... xor ...             Low-precedence synonym for exclusive or.
7860 prototype \&SUB Returns prototype of the function given a reference.
7861 =head1          Top-level heading.
7862 =head2          Second-level heading.
7863 =head3          Third-level heading (is there such?).
7864 =over [ NUMBER ]        Start list.
7865 =item [ TITLE ]         Start new item in the list.
7866 =back           End list.
7867 =cut            Switch from POD to Perl.
7868 =pod            Switch from Perl to POD.
7869 ")
7870
7871 (defun cperl-switch-to-doc-buffer ()
7872   "Go to the perl documentation buffer and insert the documentation."
7873   (interactive)
7874   (let ((buf (get-buffer-create cperl-doc-buffer)))
7875     (if (interactive-p)
7876         (switch-to-buffer-other-window buf)
7877       (set-buffer buf))
7878     (if (= (buffer-size) 0)
7879         (progn
7880           (insert (documentation-property 'cperl-short-docs
7881                                           'variable-documentation))
7882           (setq buffer-read-only t)))))
7883
7884 (defun cperl-beautify-regexp-piece (b e embed level)
7885   ;; b is before the starting delimiter, e before the ending
7886   ;; e should be a marker, may be changed, but remains "correct".
7887   ;; EMBED is nil iff we process the whole REx.
7888   ;; The REx is guarantied to have //x
7889   ;; LEVEL shows how many levels deep to go
7890   ;; position at enter and at leave is not defined
7891   (let (s c tmp (m (make-marker)) (m1 (make-marker)) c1 spaces inline code pos)
7892     (if (not embed)
7893         (goto-char (1+ b))
7894       (goto-char b)
7895       (cond ((looking-at "(\\?\\\\#")   ;  (?#) wrongly commented when //x-ing
7896              (forward-char 2)
7897              (delete-char 1)
7898              (forward-char 1))
7899             ((looking-at "(\\?[^a-zA-Z]")
7900              (forward-char 3))
7901             ((looking-at "(\\?")        ; (?i)
7902              (forward-char 2))
7903             (t
7904              (forward-char 1))))
7905     (setq c (if embed (current-indentation) (1- (current-column)))
7906           c1 (+ c (or cperl-regexp-indent-step cperl-indent-level)))
7907     (or (looking-at "[ \t]*[\n#]")
7908         (progn
7909           (insert "\n")))
7910     (goto-char e)
7911     (beginning-of-line)
7912     (if (re-search-forward "[^ \t]" e t)
7913         (progn                         ; Something before the ending delimiter
7914           (goto-char e)
7915           (delete-horizontal-space)
7916           (insert "\n")
7917           (indent-to-column c)
7918           (set-marker e (point))))
7919     (goto-char b)
7920     (end-of-line 2)
7921     (while (< (point) (marker-position e))
7922       (beginning-of-line)
7923       (setq s (point)
7924             inline t)
7925       (skip-chars-forward " \t")
7926       (delete-region s (point))
7927       (indent-to-column c1)
7928       (while (and
7929               inline
7930               (looking-at
7931                (concat "\\([a-zA-Z0-9]+[^*+{?]\\)" ; 1 word
7932                        "\\|"            ; Embedded variable
7933                        "\\$\\([a-zA-Z0-9_]+\\([[{]\\)?\\|[^\n \t)|]\\)" ; 2 3
7934                        "\\|"            ; $ ^
7935                        "[$^]"
7936                        "\\|"            ; simple-code simple-code*?
7937                        "\\(\\\\.\\|[^][()#|*+?\n]\\)\\([*+{?]\\??\\)?" ; 4 5
7938                        "\\|"            ; Class
7939                        "\\(\\[\\)"      ; 6
7940                        "\\|"            ; Grouping
7941                        "\\((\\(\\?\\)?\\)" ; 7 8
7942                        "\\|"            ; |
7943                        "\\(|\\)")))     ; 9
7944         (goto-char (match-end 0))
7945         (setq spaces t)
7946         (cond ((match-beginning 1)      ; Alphanum word + junk
7947                (forward-char -1))
7948               ((or (match-beginning 3)  ; $ab[12]
7949                    (and (match-beginning 5) ; X* X+ X{2,3}
7950                         (eq (preceding-char) ?\{)))
7951                (forward-char -1)
7952                (forward-sexp 1))
7953               ((match-beginning 6)      ; []
7954                (setq tmp (point))
7955                (if (looking-at "\\^?\\]")
7956                    (goto-char (match-end 0)))
7957                ;; XXXX POSIX classes?!
7958                (while (and (not pos)
7959                            (re-search-forward "\\[:\\|\\]" e t))
7960                  (if (eq (preceding-char) ?:)
7961                      (or (re-search-forward ":\\]" e t)
7962                          (error "[:POSIX:]-group in []-group not terminated"))
7963                    (setq pos t)))
7964                (or (eq (preceding-char) ?\])
7965                    (error "[]-group not terminated"))
7966                (if (eq (following-char) ?\{)
7967                    (progn
7968                      (forward-sexp 1)
7969                      (and (eq (following-char) ??)
7970                           (forward-char 1)))
7971                  (re-search-forward "\\=\\([*+?]\\??\\)" e t)))
7972               ((match-beginning 7)      ; ()
7973                (goto-char (match-beginning 0))
7974                (setq pos (current-column))
7975                (or (eq pos c1)
7976                    (progn
7977                      (delete-horizontal-space)
7978                      (insert "\n")
7979                      (indent-to-column c1)))
7980                (setq tmp (point))
7981                (forward-sexp 1)
7982                ;;              (or (forward-sexp 1)
7983                ;;                  (progn
7984                ;;                    (goto-char tmp)
7985                ;;                    (error "()-group not terminated")))
7986                (set-marker m (1- (point)))
7987                (set-marker m1 (point))
7988                (if (= level 1)
7989                    (if (progn           ; indent rigidly if multiline
7990                          ;; In fact does not make a lot of sense, since
7991                          ;; the starting position can be already lost due
7992                          ;; to insertion of "\n" and " "
7993                          (goto-char tmp)
7994                          (search-forward "\n" m1 t))
7995                        (indent-rigidly (point) m1 (- c1 pos)))
7996                  (setq level (1- level))
7997                  (cond
7998                   ((not (match-beginning 8))
7999                    (cperl-beautify-regexp-piece tmp m t level))
8000                   ((eq (char-after (+ 2 tmp)) ?\{) ; Code
8001                    t)
8002                   ((eq (char-after (+ 2 tmp)) ?\() ; Conditional
8003                    (goto-char (+ 2 tmp))
8004                    (forward-sexp 1)
8005                    (cperl-beautify-regexp-piece (point) m t level))
8006                   ((eq (char-after (+ 2 tmp)) ?<) ; Lookbehind
8007                    (goto-char (+ 3 tmp))
8008                    (cperl-beautify-regexp-piece (point) m t level))
8009                   (t
8010                    (cperl-beautify-regexp-piece tmp m t level))))
8011                (goto-char m1)
8012                (cond ((looking-at "[*+?]\\??")
8013                       (goto-char (match-end 0)))
8014                      ((eq (following-char) ?\{)
8015                       (forward-sexp 1)
8016                       (if (eq (following-char) ?\?)
8017                           (forward-char))))
8018                (skip-chars-forward " \t")
8019                (setq spaces nil)
8020                (if (looking-at "[#\n]")
8021                    (progn
8022                      (or (eolp) (indent-for-comment))
8023                      (beginning-of-line 2))
8024                  (delete-horizontal-space)
8025                  (insert "\n"))
8026                (end-of-line)
8027                (setq inline nil))
8028               ((match-beginning 9)      ; |
8029                (forward-char -1)
8030                (setq tmp (point))
8031                (beginning-of-line)
8032                (if (re-search-forward "[^ \t]" tmp t)
8033                    (progn
8034                      (goto-char tmp)
8035                      (delete-horizontal-space)
8036                      (insert "\n"))
8037                  ;; first at line
8038                  (delete-region (point) tmp))
8039                (indent-to-column c)
8040                (forward-char 1)
8041                (skip-chars-forward " \t")
8042                (setq spaces nil)
8043                (if (looking-at "[#\n]")
8044                    (beginning-of-line 2)
8045                  (delete-horizontal-space)
8046                  (insert "\n"))
8047                (end-of-line)
8048                (setq inline nil)))
8049         (or (looking-at "[ \t\n]")
8050             (not spaces)
8051             (insert " "))
8052         (skip-chars-forward " \t"))
8053       (or (looking-at "[#\n]")
8054           (error "Unknown code `%s' in a regexp"
8055                  (buffer-substring (point) (1+ (point)))))
8056       (and inline (end-of-line 2)))
8057     ;; Special-case the last line of group
8058     (if (and (>= (point) (marker-position e))
8059              (/= (current-indentation) c))
8060         (progn
8061           (beginning-of-line)
8062           (setq s (point))
8063           (skip-chars-forward " \t")
8064           (delete-region s (point))
8065           (indent-to-column c)))))
8066
8067 (defun cperl-make-regexp-x ()
8068   ;; Returns position of the start
8069   ;; XXX this is called too often!  Need to cache the result!
8070   (save-excursion
8071     (or cperl-use-syntax-table-text-property
8072         (error "I need to have a regexp marked!"))
8073     ;; Find the start
8074     (if (looking-at "\\s|")
8075         nil                             ; good already
8076       (if (looking-at "\\([smy]\\|qr\\)\\s|")
8077           (forward-char 1)
8078         (re-search-backward "\\s|")))   ; Assume it is scanned already.
8079     ;;(forward-char 1)
8080     (let ((b (point)) (e (make-marker)) have-x delim (c (current-column))
8081           (sub-p (eq (preceding-char) ?s)) s)
8082       (forward-sexp 1)
8083       (set-marker e (1- (point)))
8084       (setq delim (preceding-char))
8085       (if (and sub-p (eq delim (char-after (- (point) 2))))
8086           (error "Possible s/blah// - do not know how to deal with"))
8087       (if sub-p (forward-sexp 1))
8088       (if (looking-at "\\sw*x")
8089           (setq have-x t)
8090         (insert "x"))
8091       ;; Protect fragile " ", "#"
8092       (if have-x nil
8093         (goto-char (1+ b))
8094         (while (re-search-forward "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*[ \t\n#]" e t) ; Need to include (?#) too?
8095           (forward-char -1)
8096           (insert "\\")
8097           (forward-char 1)))
8098       b)))
8099
8100 (defun cperl-beautify-regexp (&optional deep)
8101   "Do it.  (Experimental, may change semantics, recheck the result.)
8102 We suppose that the regexp is scanned already."
8103   (interactive "P")
8104   (setq deep (if deep (prefix-numeric-value deep) -1))
8105   (save-excursion
8106     (goto-char (cperl-make-regexp-x))
8107     (let ((b (point)) (e (make-marker)))
8108       (forward-sexp 1)
8109       (set-marker e (1- (point)))
8110       (cperl-beautify-regexp-piece b e nil deep))))
8111
8112 (defun cperl-regext-to-level-start ()
8113   "Goto start of an enclosing group in regexp.
8114 We suppose that the regexp is scanned already."
8115   (interactive)
8116   (let ((limit (cperl-make-regexp-x)) done)
8117     (while (not done)
8118       (or (eq (following-char) ?\()
8119           (search-backward "(" (1+ limit) t)
8120           (error "Cannot find `(' which starts a group"))
8121       (setq done
8122             (save-excursion
8123               (skip-chars-backward "\\")
8124               (looking-at "\\(\\\\\\\\\\)*(")))
8125       (or done (forward-char -1)))))
8126
8127 (defun cperl-contract-level ()
8128   "Find an enclosing group in regexp and contract it.
8129 \(Experimental, may change semantics, recheck the result.)
8130 We suppose that the regexp is scanned already."
8131   (interactive)
8132   ;; (save-excursion            ; Can't, breaks `cperl-contract-levels'
8133   (cperl-regext-to-level-start)
8134   (let ((b (point)) (e (make-marker)) s c)
8135     (forward-sexp 1)
8136     (set-marker e (1- (point)))
8137     (goto-char b)
8138     (while (re-search-forward "\\(#\\)\\|\n" e 'to-end)
8139       (cond
8140        ((match-beginning 1)             ; #-comment
8141         (or c (setq c (current-indentation)))
8142         (beginning-of-line 2)           ; Skip
8143         (setq s (point))
8144         (skip-chars-forward " \t")
8145         (delete-region s (point))
8146         (indent-to-column c))
8147        (t
8148         (delete-char -1)
8149         (just-one-space))))))
8150
8151 (defun cperl-contract-levels ()
8152   "Find an enclosing group in regexp and contract all the kids.
8153 \(Experimental, may change semantics, recheck the result.)
8154 We suppose that the regexp is scanned already."
8155   (interactive)
8156   (save-excursion
8157     (condition-case nil
8158         (cperl-regext-to-level-start)
8159       (error                            ; We are outside outermost group
8160        (goto-char (cperl-make-regexp-x))))
8161     (let ((b (point)) (e (make-marker)) s c)
8162       (forward-sexp 1)
8163       (set-marker e (1- (point)))
8164       (goto-char (1+ b))
8165       (while (re-search-forward "\\(\\\\\\\\\\)\\|(" e t)
8166         (cond
8167          ((match-beginning 1)           ; Skip
8168           nil)
8169          (t                             ; Group
8170           (cperl-contract-level)))))))
8171
8172 (defun cperl-beautify-level (&optional deep)
8173   "Find an enclosing group in regexp and beautify it.
8174 \(Experimental, may change semantics, recheck the result.)
8175 We suppose that the regexp is scanned already."
8176   (interactive "P")
8177   (setq deep (if deep (prefix-numeric-value deep) -1))
8178   (save-excursion
8179     (cperl-regext-to-level-start)
8180     (let ((b (point)) (e (make-marker)))
8181       (forward-sexp 1)
8182       (set-marker e (1- (point)))
8183       (cperl-beautify-regexp-piece b e nil deep))))
8184
8185 (defun cperl-invert-if-unless ()
8186   "Change `if (A) {B}' into `B if A;' etc if possible."
8187   (interactive)
8188   (or (looking-at "\\<")
8189       (forward-sexp -1))
8190   (if (looking-at "\\<\\(if\\|unless\\|while\\|until\\|for\\|foreach\\)\\>")
8191       (let ((pos1 (point))
8192             pos2 pos3 pos4 pos5 s1 s2 state p pos45
8193             (s0 (buffer-substring (match-beginning 0) (match-end 0))))
8194         (forward-sexp 2)
8195         (setq pos3 (point))
8196         (forward-sexp -1)
8197         (setq pos2 (point))
8198         (if (eq (following-char) ?\( )
8199             (progn
8200               (goto-char pos3)
8201               (forward-sexp 1)
8202               (setq pos5 (point))
8203               (forward-sexp -1)
8204               (setq pos4 (point))
8205               ;; XXXX In fact may be `A if (B); {C}' ...
8206               (if (and (eq (following-char) ?\{ )
8207                        (progn
8208                          (cperl-backward-to-noncomment pos3)
8209                          (eq (preceding-char) ?\) )))
8210                   (if (condition-case nil
8211                           (progn
8212                             (goto-char pos5)
8213                             (forward-sexp 1)
8214                             (forward-sexp -1)
8215                             (looking-at "\\<els\\(e\\|if\\)\\>"))
8216                         (error nil))
8217                       (error
8218                        "`%s' (EXPR) {BLOCK} with `else'/`elsif'" s0)
8219                     (goto-char (1- pos5))
8220                     (cperl-backward-to-noncomment pos4)
8221                     (if (eq (preceding-char) ?\;)
8222                         (forward-char -1))
8223                     (setq pos45 (point))
8224                     (goto-char pos4)
8225                     (while (re-search-forward "\\<\\(for\\|foreach\\|if\\|unless\\|while\\|until\\)\\>\\|;" pos45 t)
8226                       (setq p (match-beginning 0)
8227                             s1 (buffer-substring p (match-end 0))
8228                             state (parse-partial-sexp pos4 p))
8229                       (or (nth 3 state)
8230                           (nth 4 state)
8231                           (nth 5 state)
8232                           (error "`%s' inside `%s' BLOCK" s1 s0))
8233                       (goto-char (match-end 0)))
8234                     ;; Finally got it
8235                     (goto-char (1+ pos4))
8236                     (skip-chars-forward " \t\n")
8237                     (setq s2 (buffer-substring (point) pos45))
8238                     (goto-char pos45)
8239                     (or (looking-at ";?[ \t\n]*}")
8240                         (progn
8241                           (skip-chars-forward "; \t\n")
8242                           (setq s2 (concat s2 "\n" (buffer-substring (point) (1- pos5))))))
8243                     (and (equal s2 "")
8244                          (setq s2 "1"))
8245                     (goto-char (1- pos3))
8246                     (cperl-backward-to-noncomment pos2)
8247                     (or (looking-at "[ \t\n]*)")
8248                         (goto-char (1- pos3)))
8249                     (setq p (point))
8250                     (goto-char (1+ pos2))
8251                     (skip-chars-forward " \t\n")
8252                     (setq s1 (buffer-substring (point) p))
8253                     (delete-region pos4 pos5)
8254                     (delete-region pos2 pos3)
8255                     (goto-char pos1)
8256                     (insert s2 " ")
8257                     (just-one-space)
8258                     (forward-word 1)
8259                     (setq pos1 (point))
8260                     (insert " " s1 ";")
8261                     (delete-horizontal-space)
8262                     (forward-char -1)
8263                     (delete-horizontal-space)
8264                     (goto-char pos1)
8265                     (just-one-space)
8266                     (cperl-indent-line))
8267                 (error "`%s' (EXPR) not with an {BLOCK}" s0)))
8268           (error "`%s' not with an (EXPR)" s0)))
8269     (error "Not at `if', `unless', `while', `until', `for' or `foreach'")))
8270
8271 ;;; By Anthony Foiani <afoiani@uswest.com>
8272 ;;; Getting help on modules in C-h f ?
8273 ;;; This is a modified version of `man'.
8274 ;;; Need to teach it how to lookup functions
8275 (defun cperl-perldoc (word)
8276   "Run `perldoc' on WORD."
8277   (interactive
8278    (list (let* ((default-entry (cperl-word-at-point))
8279                 (input (read-string
8280                         (format "perldoc entry%s: "
8281                                 (if (string= default-entry "")
8282                                     ""
8283                                   (format " (default %s)" default-entry))))))
8284            (if (string= input "")
8285                (if (string= default-entry "")
8286                    (error "No perldoc args given")
8287                  default-entry)
8288              input))))
8289   (require 'man)
8290   (let* ((case-fold-search nil)
8291          (is-func (and
8292                    (string-match "^[a-z]+$" word)
8293                    (string-match (concat "^" word "\\>")
8294                                  (documentation-property
8295                                   'cperl-short-docs
8296                                   'variable-documentation))))
8297          (manual-program (if is-func "perldoc -f" "perldoc")))
8298     (cond
8299      (cperl-xemacs-p
8300       (let ((Manual-program "perldoc")
8301             (Manual-switches (if is-func (list "-f"))))
8302         (manual-entry word)))
8303      (t
8304       (Man-getpage-in-background word)))))
8305
8306 (defun cperl-perldoc-at-point ()
8307   "Run a `perldoc' on the word around point."
8308   (interactive)
8309   (cperl-perldoc (cperl-word-at-point)))
8310
8311 (defcustom pod2man-program "pod2man"
8312   "*File name for `pod2man'."
8313   :type 'file
8314   :group 'cperl)
8315
8316 ;;; By Nick Roberts <Nick.Roberts@src.bae.co.uk> (with changes)
8317 (defun cperl-pod-to-manpage ()
8318   "Create a virtual manpage in Emacs from the Perl Online Documentation."
8319   (interactive)
8320   (require 'man)
8321   (let* ((pod2man-args (concat buffer-file-name " | nroff -man "))
8322          (bufname (concat "Man " buffer-file-name))
8323          (buffer (generate-new-buffer bufname)))
8324     (save-excursion
8325       (set-buffer buffer)
8326       (let ((process-environment (copy-sequence process-environment)))
8327         ;; Prevent any attempt to use display terminal fanciness.
8328         (setenv "TERM" "dumb")
8329         (set-process-sentinel
8330          (start-process pod2man-program buffer "sh" "-c"
8331                         (format (cperl-pod2man-build-command) pod2man-args))
8332          'Man-bgproc-sentinel)))))
8333
8334 ;;; Updated version by him too
8335 (defun cperl-build-manpage ()
8336   "Create a virtual manpage in Emacs from the POD in the file."
8337   (interactive)
8338   (require 'man)
8339   (cond
8340    (cperl-xemacs-p
8341     (let ((Manual-program "perldoc"))
8342       (manual-entry buffer-file-name)))
8343    (t
8344     (let* ((manual-program "perldoc"))
8345       (Man-getpage-in-background buffer-file-name)))))
8346
8347 (defun cperl-pod2man-build-command ()
8348   "Builds the entire background manpage and cleaning command."
8349   (let ((command (concat pod2man-program " %s 2>/dev/null"))
8350         (flist Man-filter-list))
8351     (while (and flist (car flist))
8352       (let ((pcom (car (car flist)))
8353             (pargs (cdr (car flist))))
8354         (setq command
8355               (concat command " | " pcom " "
8356                       (mapconcat '(lambda (phrase)
8357                                     (if (not (stringp phrase))
8358                                         (error "Malformed Man-filter-list"))
8359                                     phrase)
8360                                  pargs " ")))
8361         (setq flist (cdr flist))))
8362     command))
8363
8364 (defun cperl-lazy-install ())           ; Avoid a warning
8365 (defun cperl-lazy-unstall ())           ; Avoid a warning
8366
8367 (if (fboundp 'run-with-idle-timer)
8368     (progn
8369       (defvar cperl-help-shown nil
8370         "Non-nil means that the help was already shown now.")
8371
8372       (defvar cperl-lazy-installed nil
8373         "Non-nil means that the lazy-help handlers are installed now.")
8374
8375       (defun cperl-lazy-install ()
8376         "Switches on Auto-Help on Perl constructs (put in the message area).
8377 Delay of auto-help controlled by `cperl-lazy-help-time'."
8378         (interactive)
8379         (make-variable-buffer-local 'cperl-help-shown)
8380         (if (and (cperl-val 'cperl-lazy-help-time)
8381                  (not cperl-lazy-installed))
8382             (progn
8383               (add-hook 'post-command-hook 'cperl-lazy-hook)
8384               (run-with-idle-timer
8385                (cperl-val 'cperl-lazy-help-time 1000000 5)
8386                t
8387                'cperl-get-help-defer)
8388               (setq cperl-lazy-installed t))))
8389
8390       (defun cperl-lazy-unstall ()
8391         "Switches off Auto-Help on Perl constructs (put in the message area).
8392 Delay of auto-help controlled by `cperl-lazy-help-time'."
8393         (interactive)
8394         (remove-hook 'post-command-hook 'cperl-lazy-hook)
8395         (cancel-function-timers 'cperl-get-help-defer)
8396         (setq cperl-lazy-installed nil))
8397
8398       (defun cperl-lazy-hook ()
8399         (setq cperl-help-shown nil))
8400
8401       (defun cperl-get-help-defer ()
8402         (if (not (memq major-mode '(perl-mode cperl-mode))) nil
8403           (let ((cperl-message-on-help-error nil) (cperl-help-from-timer t))
8404             (cperl-get-help)
8405             (setq cperl-help-shown t))))
8406       (cperl-lazy-install)))
8407
8408
8409 ;;; Plug for wrong font-lock:
8410
8411 (defun cperl-font-lock-unfontify-region-function (beg end)
8412   (let* ((modified (buffer-modified-p)) (buffer-undo-list t)
8413          (inhibit-read-only t) (inhibit-point-motion-hooks t)
8414          before-change-functions after-change-functions
8415          deactivate-mark buffer-file-name buffer-file-truename)
8416     (remove-text-properties beg end '(face nil))
8417     (when (and (not modified) (buffer-modified-p))
8418       (set-buffer-modified-p nil))))
8419
8420 (defvar cperl-d-l nil)
8421 (defun cperl-fontify-syntaxically (end)
8422   ;; Some vars for debugging only
8423   ;; (message "Syntaxifying...")
8424   (let ((dbg (point)) (iend end)
8425         (istate (car cperl-syntax-state))
8426         start)
8427     (and cperl-syntaxify-unwind
8428          (setq end (cperl-unwind-to-safe t end)))
8429     (setq start (point))
8430     (or cperl-syntax-done-to
8431         (setq cperl-syntax-done-to (point-min)))
8432     (if (or (not (boundp 'font-lock-hot-pass))
8433             (eval 'font-lock-hot-pass)
8434             t)                          ; Not debugged otherwise
8435         ;; Need to forget what is after `start'
8436         (setq start (min cperl-syntax-done-to start))
8437       ;; Fontification without a change
8438       (setq start (max cperl-syntax-done-to start)))
8439     (and (> end start)
8440          (setq cperl-syntax-done-to start) ; In case what follows fails
8441          (cperl-find-pods-heres start end t nil t))
8442     (if (eq cperl-syntaxify-by-font-lock 'message)
8443         (message "Syntaxified %s..%s from %s to %s(%s), state %s-->%s"
8444                  dbg iend
8445                  start end cperl-syntax-done-to
8446                  istate (car cperl-syntax-state))) ; For debugging
8447     nil))                               ; Do not iterate
8448
8449 (defun cperl-fontify-update (end)
8450   (let ((pos (point)) prop posend)
8451     (while (< pos end)
8452       (setq prop (get-text-property pos 'cperl-postpone))
8453       (setq posend (next-single-property-change pos 'cperl-postpone nil end))
8454       (and prop (put-text-property pos posend (car prop) (cdr prop)))
8455       (setq pos posend)))
8456   nil)                                  ; Do not iterate
8457
8458 (defun cperl-update-syntaxification (from to)
8459   (if (and cperl-use-syntax-table-text-property
8460            cperl-syntaxify-by-font-lock
8461            (or (null cperl-syntax-done-to)
8462                (< cperl-syntax-done-to to)))
8463       (progn
8464         (save-excursion
8465           (goto-char from)
8466           (cperl-fontify-syntaxically to)))))
8467
8468 (defvar cperl-version
8469   (let ((v  "$Revision: 5.0 $"))
8470     (string-match ":\\s *\\([0-9.]+\\)" v)
8471     (substring v (match-beginning 1) (match-end 1)))
8472   "Version of IZ-supported CPerl package this file is based on.")
8473
8474 (provide 'cperl-mode)
8475
8476 ;;; cperl-mode.el ends here