Emacs CPerl update for 5.004_04
[p5sagit/p5-mst-13.2.git] / emacs / cperl-mode.el
1 ;;; This code started from the following message of long time ago (IZ):
2
3 ;;; From: olson@mcs.anl.gov (Bob Olson)
4 ;;; Newsgroups: comp.lang.perl
5 ;;; Subject: cperl-mode: Another perl mode for Gnuemacs
6 ;;; Date: 14 Aug 91 15:20:01 GMT
7
8 ;; Perl code editing commands for Emacs
9 ;; Copyright (C) 1985-1996 Bob Olson, Ilya Zakharevich
10
11 ;; This file is not (yet) part of GNU Emacs. It may be distributed
12 ;; either under the same terms as GNU Emacs, or under the same terms
13 ;; as Perl. You should have received a copy of Perl Artistic license
14 ;; along with the Perl distribution.
15
16 ;; GNU Emacs is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
28 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
29 ;; Boston, MA 02111-1307, USA.
30
31
32 ;;; Corrections made by Ilya Zakharevich ilya@math.mps.ohio-state.edu
33 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
34
35 ;; $Id: cperl-mode.el,v 1.39 1997/10/14 08:28:00 ilya Exp ilya $
36
37 ;;; To use this mode put the following into your .emacs file:
38
39 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
40
41 ;;; You can either fine-tune the bells and whistles of this mode or
42 ;;; bulk enable them by putting
43
44 ;; (setq cperl-hairy t)
45
46 ;;; in your .emacs file. (Emacs rulers do not consider it politically
47 ;;; correct to make whistles enabled by default.)
48
49 ;;; DO NOT FORGET to read micro-docs. (available from `Perl' menu). <<<<<<
50 ;;; or as help on variables `cperl-tips', `cperl-problems',         <<<<<<
51 ;;; `cperl-non-problems', `cperl-praise'.                           <<<<<<
52
53 ;;; Additional useful commands to put into your .emacs file:
54
55 ;; (setq auto-mode-alist
56 ;;      (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
57 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
58 ;;                                      '(("miniperl" . perl-mode))))
59
60 ;;; The mode information (on C-h m) provides some customization help.
61 ;;; If you use font-lock feature of this mode, it is advisable to use
62 ;;; either lazy-lock-mode or fast-lock-mode (available on ELisp
63 ;;; archive in files lazy-lock.el and fast-lock.el). I prefer lazy-lock.
64
65 ;;; Faces used now: three faces for first-class and second-class keywords
66 ;;; and control flow words, one for each: comments, string, labels,
67 ;;; functions definitions and packages, arrays, hashes, and variable
68 ;;; definitions. If you do not see all these faces, your font-lock does
69 ;;; not define them, so you need to define them manually. Maybe you have 
70 ;;; an obsolete font-lock from 19.28 or earlier. Upgrade.
71
72 ;;; If you have a grayscale monitor, and do not have the variable
73 ;;; font-lock-display-type bound to 'grayscale, insert 
74
75 ;;; (setq font-lock-display-type 'grayscale)
76
77 ;;; into your .emacs file.
78
79 ;;;; This mode supports font-lock, imenu and mode-compile. In the
80 ;;;; hairy version font-lock is on, but you should activate imenu
81 ;;;; yourself (note that mode-compile is not standard yet). Well, you
82 ;;;; can use imenu from keyboard anyway (M-x imenu), but it is better
83 ;;;; to bind it like that:
84
85 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
86
87 ;;; In fact the version of font-lock that this version supports can be
88 ;;; much newer than the version you actually have. This means that a
89 ;;; lot of faces can be set up, but are not visible on your screen
90 ;;; since the coloring rules for this faces are not defined.
91
92 ;;; Updates: ========================================
93
94 ;;; Made less hairy by default: parentheses not electric, 
95 ;;; linefeed not magic. Bug with abbrev-mode corrected.
96
97 ;;;; After 1.4:
98 ;;;  Better indentation:
99 ;;;  subs inside braces should work now, 
100 ;;;  Toplevel braces obey customization.
101 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
102 ;;;  moves cursor to a correct place.
103 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-( 
104 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
105 ;;;  Minor documentation fixes.
106 ;;;  Imenu understands packages as prefixes (including nested).
107 ;;;  Hairy options can be switched off one-by-one by setting to null.
108 ;;;  Names of functions and variables changed to conform to `cperl-' style.
109
110 ;;;; After 1.5:
111 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
112 ;;;  `cperl-indent-region' done (slow :-()).
113 ;;;  `cperl-fill-paragraph' done.
114 ;;;  Better package support for `imenu'.
115 ;;;  Progress indicator for indentation (with `imenu' loaded).
116 ;;;  `Cperl-set' was busted, now setting the individual hairy option 
117 ;;;     should be better.
118
119 ;;;; After 1.6:
120 ;;; `cperl-set-style' done.
121 ;;; `cperl-check-syntax' done.
122 ;;; Menu done.
123 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
124 ;;; Bugs with `cperl-auto-newline' corrected.
125 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation 
126 ;;; like $hash{.
127
128 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
129 ;;; - use `next-command-event', if `next-command-events' does not exist
130 ;;; - use `find-face' as def. of `is-face'
131 ;;; - corrected def. of `x-color-defined-p'
132 ;;; - added const defs for font-lock-comment-face,
133 ;;;   font-lock-keyword-face and font-lock-function-name-face
134 ;;; - added def. of font-lock-variable-name-face
135 ;;; - added (require 'easymenu) inside an `eval-when-compile'
136 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
137 ;;;   `define-key's
138 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
139 ;;; Todo (at least):
140 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
141 ;;;   for portable code?
142 ;;; - should `cperl-mode' do a 
143 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
144 ;;;   or should this be left to the user's `cperl-mode-hook'?
145
146 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
147 ;;; Some bugs under XEmacs introduced by the correction corrected.
148
149 ;;; Some more can remain since there are two many different variants. 
150 ;;; Please feedback!
151
152 ;;; We do not support fontification of arrays and hashes under 
153 ;;; obsolete font-lock any more. Upgrade.
154
155 ;;;; after 1.8 Minor bug with parentheses.
156 ;;;; after 1.9 Improvements from Joe Marzot.
157 ;;;; after 1.10
158 ;;;  Does not need easymenu to compile under XEmacs.
159 ;;;  `vc-insert-headers' should work better.
160 ;;;  Should work with 19.29 and 19.12.
161 ;;;  Small improvements to fontification.
162 ;;;  Expansion of keywords does not depend on C-? being backspace.
163
164 ;;; after 1.10+
165 ;;; 19.29 and 19.12 supported.
166 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
167 ;;; Support for font-lock-extra.el.
168
169 ;;;; After 1.11:
170 ;;; Tools submenu.
171 ;;; Support for perl5-info.
172 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
173 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
174 ;;; Fontifies `require a if b;', __DATA__.
175 ;;; Arglist for auto-fill-mode was incorrect.
176
177 ;;;; After 1.12:
178 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions 
179 ;;; vertically.
180 ;;; `cperl-do-auto-fill' updated for 19.29 style.
181 ;;; `cperl-info-on-command' now has a default.
182 ;;; Workaround for broken C-h on XEmacs.
183 ;;; VC strings escaped.
184 ;;; C-h f now may prompt for function name instead of going on,
185 ;;; controlled by `cperl-info-on-command-no-prompt'.
186
187 ;;;; After 1.13:
188 ;;; Msb buffer list includes perl files
189 ;;; Indent-for-comment uses indent-to
190 ;;; Can write tag files using etags.
191
192 ;;;; After 1.14:
193 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
194 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
195 ;;; Bug with auto-filling comments started with "##" corrected.
196
197 ;;;; Very slow now: on DB::DB 0.91, 486/66:
198
199 ;;;Function Name                             Call Count  Elapsed Time  Average Time
200 ;;;========================================  ==========  ============  ============
201 ;;;cperl-block-p                             469         3.7799999999  0.0080597014
202 ;;;cperl-get-state                           505         163.39000000  0.3235445544
203 ;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
204 ;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
205 ;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
206 ;;;cperl-indent-line                         505         172.88000000  0.3423366336
207 ;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
208 ;;;cperl-indent-exp                          1           177.97000000  177.97000000
209 ;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
210 ;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
211 ;;;cperl-indent-region                       1           177.94000000  177.94000000
212
213 ;;;; After 1.15:
214 ;;; Takes into account white space after opening parentheses during indent.
215 ;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
216 ;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
217 ;;; for indentation so far.
218 ;;; Fontification updated to 19.30 style. 
219 ;;; The change 19.29->30 did not add all the required functionality,
220 ;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
221 ;;;       ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
222
223 ;;;; After 1.16:
224 ;;;       else # comment
225 ;;;    recognized as a start of a block.
226 ;;;  Two different font-lock-levels provided.
227 ;;;  `cperl-pod-head-face' introduced. Used for highlighting.
228 ;;;  `imenu' marks pods, +Packages moved to the head. 
229
230 ;;;; After 1.17:
231 ;;;  Scan for pods highlights here-docs too.
232 ;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
233 ;;;  Only one here-doc-tag per line is supported, and one in comment
234 ;;;  or a string may break fontification.
235 ;;;  POD headers were supposed to fill one line only.
236
237 ;;;; After 1.18:
238 ;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme 
239 ;;;    may  break under XEmacs.
240 ;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
241 ;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
242 ;;;    compatibility with older lazy-lock.el) (older one overfontifies
243 ;;;    something nevertheless :-().
244 ;;;  Will not indent something inside pod and here-documents.
245 ;;;  Fontifies the package name after import/no/bootstrap.
246 ;;;  Added new entry to menu with meta-info about the mode.
247
248 ;;;; After 1.19:
249 ;;;  Prefontification works much better with 19.29. Should be checked
250 ;;;   with 19.30 as well.
251 ;;;  Some misprints in docs corrected.
252 ;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
253 ;;;  Now the pod search is much stricter, so it can help you to find
254 ;;;    pod sections which are broken because of whitespace before =blah
255 ;;;    - just observe the fontification.
256
257 ;;;; After 1.20
258 ;;;  Anonymous subs are indented with respect to the level of
259 ;;;    indentation of `sub' now.
260 ;;;  {} is recognized as hash after `bless' and `return'.
261 ;;;  Anonymous subs are split by `cperl-linefeed' as well.
262 ;;;  Electric parens embrace a region if present.
263 ;;;  To make `cperl-auto-newline' useful,
264 ;;;    `cperl-auto-newline-after-colon' is introduced.
265 ;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
266 ;;;  `cperl-electric-parens-string'.
267 ;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
268 ;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
269 ;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
270 ;;;  Beginning-of-defun-regexp was not anchored.
271
272 ;;;; After 1.21
273 ;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
274 ;;;    after ")".
275 ;;;  {} is recognized as expression after `tr' and friends.
276
277 ;;;; After 1.22
278 ;;;  Entry Hierarchy added to imenu. Very primitive so far.
279 ;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
280 ;;;  Writes its own TAGS files.
281 ;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
282 ;;;  19.31: Problems with scan for PODs corrected.
283 ;;;  First POD header correctly fontified.
284 ;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
285 ;;;  Apparently it makes a lot of hierarchy code obsolete...
286
287 ;;;; After 1.23
288 ;;;  Tags filler now scans *.xs as well.
289 ;;;  The info from *.xs scan is used by the hierarchy viewer.
290 ;;;  Hierarchy viewer documented.
291 ;;;  Bug in 19.31 imenu documented.
292
293 ;;;; After 1.24
294 ;;;  New location for info-files mentioned,
295 ;;;  Electric-; should work better.
296 ;;;  Minor bugs with POD marking.
297
298 ;;;; After 1.25 (probably not...)
299 ;;;  `cperl-info-page' introduced.  
300 ;;;  To make `uncomment-region' working, `comment-region' would
301 ;;;  not insert extra space.
302 ;;;  Here documents delimiters better recognized 
303 ;;;  (empty one, and non-alphanums in quotes handled). May be wrong with 1<<14?
304 ;;;  `cperl-db' added, used in menu.
305 ;;;  imenu scan removes text-properties, for better debugging
306 ;;;    - but the bug is in 19.31 imenu.
307 ;;;  formats highlighted by font-lock and prescan, embedded comments
308 ;;;  are not treated.
309 ;;;  POD/friends scan merged in one pass.
310 ;;;  Syntax class is not used for analyzing the code, only char-syntax
311 ;;;  may be checked against _ or'ed with w.
312 ;;;  Syntax class of `:' changed to be _.
313 ;;;  `cperl-find-bad-style' added.
314
315 ;;;; After 1.25
316 ;;;  When search for here-documents, we ignore commented << in simplest cases.
317 ;;;  `cperl-get-help' added, available on C-h v and from menu.
318 ;;;  Auto-help added. Default with `cperl-hairy', switchable on/off
319 ;;;   with startup variable `cperl-lazy-help-time' and from
320 ;;;   menu. Requires `run-with-idle-timer'.
321 ;;;  Highlighting of @abc{@efg} was wrong - interchanged two regexps.
322
323 ;;;; After 1.27
324 ;;;  Indentation: At toplevel after a label - fixed.
325 ;;;  1.27 was put to archives in binary mode ===> DOSish :-(
326
327 ;;;; After 1.28
328 ;;;  Thanks to Martin Buchholz <mrb@Eng.Sun.COM>: misprints in
329 ;;;  comments and docstrings corrected, XEmacs support cleaned up.
330 ;;;  The closing parenths would enclose the region into matching
331 ;;;  parens under the same conditions as the opening ones.
332 ;;;  Minor updates to `cperl-short-docs'.
333 ;;;  Will not consider <<= as start of here-doc.
334
335 ;;;; After 1.29
336 ;;;  Added an extra advice to look into Micro-docs. ;-).
337 ;;;  Enclosing of region when you press a closing parenth is regulated by
338 ;;;  `cperl-electric-parens-string'.
339 ;;;  Minor updates to `cperl-short-docs'.
340 ;;;  `initialize-new-tags-table' called only if present (Does this help
341 ;;;     with generation of tags under XEmacs?).
342 ;;;  When creating/updating tag files, new info is written at the old place,
343 ;;;     or at the end (is this a wanted behaviour? I need this in perl build directory).
344
345 ;;;; After 1.30
346 ;;;  All the keywords from keywords.pl included (maybe with dummy explanation).
347 ;;;  No auto-help inside strings, comment, here-docs, formats, and pods.
348 ;;;  Shrinkwrapping of info, regulated by `cperl-max-help-size',
349 ;;;  `cperl-shrink-wrap-info-frame'.
350 ;;;  Info on variables as well.
351 ;;;  Recognision of HERE-DOCS improved yet more.
352 ;;;  Autonewline works on `}' without warnings.
353 ;;;  Autohelp works again on $_[0].
354
355 ;;;; After 1.31
356 ;;;  perl-descr.el found its author - hi, Johan!
357 ;;;  Some support for correct indent after here-docs and friends (may
358 ;;;  be superseeded by eminent change to Emacs internals).
359 ;;;  Should work with older Emaxen as well ( `-style stuff removed).
360
361 ;;;; After 1.32
362
363 ;;;  Started to add support for `syntax-table' property (should work
364 ;;;  with patched Emaxen), controlled by
365 ;;;  `cperl-use-syntax-table-text-property'. Currently recognized:
366 ;;;    All quote-like operators: m, s, y, tr, qq, qw, qx, q,
367 ;;;    // in most frequent context: 
368 ;;;          after block or
369 ;;;                    ~ { ( = | & + - * ! , ;
370 ;;;          or 
371 ;;;                    while if unless until and or not xor split grep map
372 ;;;    Here-documents, formats, PODs, 
373 ;;;    ${...}
374 ;;;    'abc$'
375 ;;;    sub a ($); sub a ($) {}
376 ;;;  (provide 'cperl-mode) was missing!
377 ;;;  `cperl-after-expr-p' is now much smarter after `}'.
378 ;;;  `cperl-praise' added to mini-docs.
379 ;;;  Utilities try to support subs-with-prototypes.
380
381 ;;;; After 1.32.1
382 ;;;  `cperl-after-expr-p' is now much smarter after "() {}" and "word {}":
383 ;;;     if word is "else, map, grep".
384 ;;;  Updated for new values of syntax-table constants.
385 ;;;  Uses `help-char' (at last!) (disabled, does not work?!)
386 ;;;  A couple of regexps where missing _ in character classes.
387 ;;;  -s could be considered as start of regexp, 1../blah/ was not,
388 ;;;  as was not /blah/ at start of file.
389
390 ;;;; After 1.32.2
391 ;;;  "\C-hv" was wrongly "\C-hf"
392 ;;;  C-hv was not working on `[index()]' because of [] in skip-chars-*.
393 ;;;  `__PACKAGE__' supported.
394 ;;;  Thanks for Greg Badros: `cperl-lazy-unstall' is more complete,
395 ;;;  `cperl-get-help' is made compatible with `query-replace'.
396
397 ;;;; As of Apr 15, development version of 19.34 supports
398 ;;;; `syntax-table' text properties. Try setting
399 ;;;; `cperl-use-syntax-table-text-property'.
400
401 ;;;; After 1.32.3
402 ;;;  We scan for s{}[] as well (in simplest situations).
403 ;;;  We scan for $blah'foo as well.
404 ;;;  The default is to use `syntax-table' text property if Emacs is good enough.
405 ;;;  `cperl-lineup' is put on C-M-| (=C-M-S-\\).
406 ;;;  Start of `cperl-beautify-regexp'.
407
408 ;;;; After 1.32.4
409 ;;; `cperl-tags-hier-init' did not work in text-mode.
410 ;;; `cperl-noscan-files-regexp' had a misprint.
411 ;;; Generation of Class Hierarchy was broken due to a bug in `x-popup-menu'
412 ;;;  in 19.34.
413
414 ;;;; After 1.33:
415 ;;; my,local highlight vars after {} too.
416 ;;; TAGS could not be created before imenu was loaded.
417 ;;; `cperl-indent-left-aligned-comments' created.
418 ;;; Logic of `cperl-indent-exp' changed a little bit, should be more
419 ;;;  robust w.r.t. multiline strings.
420 ;;; Recognition of blah'foo takes into account strings.
421 ;;; Added '.al' to the list of Perl extensions.
422 ;;; Class hierarchy is "mostly" sorted (need to rethink algorthm
423 ;;;  of pruning one-root-branch subtrees to get yet better sorting.)
424 ;;; Regeneration of TAGS was busted.
425 ;;; Can use `syntax-table' property when generating TAGS
426 ;;;  (governed by  `cperl-use-syntax-table-text-property-for-tags').
427
428 ;;;; After 1.35:
429 ;;; Can process several =pod/=cut sections one after another.
430 ;;; Knows of `extproc' when under `emx', indents with `__END__' and `__DATA__'.
431 ;;; `cperl-under-as-char' implemented (XEmacs people like broken behaviour).
432 ;;; Beautifier for regexps fixed.
433 ;;; `cperl-beautify-level', `cperl-contract-level' coded
434 ;;;
435 ;;;; Emacs's 20.2 problems:
436 ;;; `imenu.el' has bugs, `imenu-add-to-menubar' does not work.
437 ;;; Couple of others problems with 20.2 were reported, my ability to check/fix
438 ;;; them is very reduced now.
439
440 ;;;; After 1.36:
441 ;;;  'C-M-|' in XEmacs fixed
442
443 ;;;; After 1.37:
444 ;;;  &&s was not recognized as start of regular expression;
445 ;;;  Will "preprocess" the contents of //e part of s///e too;
446 ;;;  What to do with s# blah # foo #e ?
447 ;;;  Should handle s;blah;foo;; better.
448 ;;;  Now the only known problems with regular expression recognition:
449 ;;;;;;;  s<foo>/bar/    - different delimiters (end ignored)
450 ;;;;;;;  s/foo/\\bar/   - backslash at start of subst (made into one chunk)
451 ;;;;;;;  s/foo//        - empty subst (made into one chunk + '/')
452 ;;;;;;;  s/foo/(bar)/   - start-group at start of subst (internal group will not match backwards)
453
454 ;;;; After 1.38:
455 ;;;  We highlight closing / of s/blah/foo/e;
456 ;;;  This handles s# blah # foo #e too;
457 ;;;  s//blah/, s///, s/blah// works again, and s#blah## too, the algorithm
458 ;;;   is much simpler now;
459 ;;;  Next round of changes: s\\\ works, s<blah>/foo/, 
460 ;;;   comments between the first and the second part allowed
461 ;;;  Another problem discovered:
462 ;;;;;;;  s[foo] <blah>e - e part delimited by different <> (will not match)
463 ;;;  `cperl-find-pods-heres' somehow maybe called when string-face is undefined
464 ;;;   - put a stupid workaround for 20.1
465
466 (defconst cperl-xemacs-p (string-match "XEmacs\\|Lucid" emacs-version))
467 \f
468 (defvar cperl-extra-newline-before-brace nil
469   "*Non-nil means that if, elsif, while, until, else, for, foreach
470 and do constructs look like:
471
472         if ()
473         {
474         }
475
476 instead of:
477
478         if () {
479         }
480 ")
481
482 (defvar cperl-indent-level 2
483   "*Indentation of CPerl statements with respect to containing block.")
484 (defvar cperl-lineup-step nil
485   "*`cperl-lineup' will always lineup at multiple of this number.
486 If `nil', the value of `cperl-indent-level' will be used.")
487 (defvar cperl-brace-imaginary-offset 0
488   "*Imagined indentation of a Perl open brace that actually follows a statement.
489 An open brace following other text is treated as if it were this far
490 to the right of the start of its line.")
491 (defvar cperl-brace-offset 0
492   "*Extra indentation for braces, compared with other text in same context.")
493 (defvar cperl-label-offset -2
494   "*Offset of CPerl label lines relative to usual indentation.")
495 (defvar cperl-min-label-indent 1
496   "*Minimal offset of CPerl label lines.")
497 (defvar cperl-continued-statement-offset 2
498   "*Extra indent for lines not starting new statements.")
499 (defvar cperl-continued-brace-offset 0
500   "*Extra indent for substatements that start with open-braces.
501 This is in addition to cperl-continued-statement-offset.")
502 (defvar cperl-close-paren-offset -1
503   "*Extra indent for substatements that start with close-parenthesis.")
504
505 (defvar cperl-auto-newline nil
506   "*Non-nil means automatically newline before and after braces,
507 and after colons and semicolons, inserted in CPerl code. The following
508 \\[cperl-electric-backspace] will remove the inserted whitespace.
509 Insertion after colons requires both this variable and 
510 `cperl-auto-newline-after-colon' set.")
511
512 (defvar cperl-auto-newline-after-colon nil
513   "*Non-nil means automatically newline even after colons.
514 Subject to `cperl-auto-newline' setting.")
515
516 (defvar cperl-tab-always-indent t
517   "*Non-nil means TAB in CPerl mode should always reindent the current line,
518 regardless of where in the line point is when the TAB command is used.")
519
520 (defvar cperl-font-lock nil
521   "*Non-nil (and non-null) means CPerl buffers will use font-lock-mode.
522 Can be overwritten by `cperl-hairy' if nil.")
523
524 (defvar cperl-electric-lbrace-space nil
525   "*Non-nil (and non-null) means { after $ in CPerl buffers should be preceded by ` '.
526 Can be overwritten by `cperl-hairy' if nil.")
527
528 (defvar cperl-electric-parens-string "({[]})<"
529   "*String of parentheses that should be electric in CPerl.
530 Closing ones are electric only if the region is highlighted.")
531
532 (defvar cperl-electric-parens nil
533   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
534 Can be overwritten by `cperl-hairy' if nil.")
535 (defvar cperl-electric-parens-mark  
536   (and window-system
537        (or (and (boundp 'transient-mark-mode) ; For Emacs
538                 transient-mark-mode)
539            (and (boundp 'zmacs-regions) ; For XEmacs
540                 zmacs-regions)))
541   "*Not-nil means that electric parens look for active mark.
542 Default is yes if there is visual feedback on mark.")
543
544 (defvar cperl-electric-linefeed nil
545   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
546 In any case these two mean plain and hairy linefeeds together.
547 Can be overwritten by `cperl-hairy' if nil.")
548
549 (defvar cperl-electric-keywords nil
550   "*Not-nil (and non-null) means keywords are electric in CPerl.
551 Can be overwritten by `cperl-hairy' if nil.")
552
553 (defvar cperl-hairy nil
554   "*Not-nil means all the bells and whistles are enabled in CPerl.")
555
556 (defvar cperl-comment-column 32
557   "*Column to put comments in CPerl (use \\[cperl-indent]' to lineup with code).")
558
559 (defvar cperl-vc-header-alist '((SCCS "$sccs = '%W\%' ;")
560                                 (RCS "$rcs = ' $Id\$ ' ;"))
561   "*What to use as `vc-header-alist' in CPerl.")
562
563 (defvar cperl-info-on-command-no-prompt nil
564   "*Not-nil (and non-null) means not to prompt on C-h f.
565 The opposite behaviour is always available if prefixed with C-c.
566 Can be overwritten by `cperl-hairy' if nil.")
567
568 (defvar cperl-lazy-help-time nil
569   "*Not-nil (and non-null) means to show lazy help after given idle time.")
570
571 (defvar cperl-pod-face 'font-lock-comment-face
572   "*The result of evaluation of this expression is used for pod highlighting.")
573
574 (defvar cperl-pod-head-face 'font-lock-variable-name-face
575   "*The result of evaluation of this expression is used for pod highlighting.
576 Font for POD headers.")
577
578 (defvar cperl-here-face 'font-lock-string-face
579   "*The result of evaluation of this expression is used for here-docs highlighting.")
580
581 (defvar cperl-pod-here-fontify '(featurep 'font-lock)
582   "*Not-nil after evaluation means to highlight pod and here-docs sections.")
583
584 (defvar cperl-pod-here-scan t
585   "*Not-nil means look for pod and here-docs sections during startup.
586 You can always make lookup from menu or using \\[cperl-find-pods-heres].")
587
588 (defvar cperl-imenu-addback nil
589   "*Not-nil means add backreferences to generated `imenu's.
590 May require patched `imenu' and `imenu-go'.")
591
592 (defvar cperl-max-help-size 66
593   "*Non-nil means shrink-wrapping of info-buffer allowed up to these percents.")
594
595 (defvar cperl-shrink-wrap-info-frame t
596   "*Non-nil means shrink-wrapping of info-buffer-frame allowed.")
597
598 (defvar cperl-info-page "perl"
599   "*Name of the info page containing perl docs.
600 Older version of this page was called `perl5', newer `perl'.")
601
602 (defvar cperl-use-syntax-table-text-property 
603   (boundp 'parse-sexp-lookup-properties)
604   "*Non-nil means CPerl sets up and uses `syntax-table' text property.")
605
606 (defvar cperl-use-syntax-table-text-property-for-tags 
607   cperl-use-syntax-table-text-property
608   "*Non-nil means: set up and use `syntax-table' text property generating TAGS.")
609
610 (defvar cperl-scan-files-regexp "\\.\\([pP][Llm]\\|xs\\)$"
611   "*Regexp to match files to scan when generating TAGS.")
612
613 (defvar cperl-noscan-files-regexp "/\\(\\.\\.?\\|SCCS\\|RCS\\|blib\\)$"
614   "*Regexp to match files/dirs to skip when generating TAGS.")
615
616 (defvar cperl-regexp-indent-step nil
617   "*indentation used when beautifying regexps.
618 If `nil', the value of `cperl-indent-level' will be used.")
619
620 (defvar cperl-indent-left-aligned-comments t
621   "*Non-nil means that the comment starting in leftmost column should indent.")
622
623 (defvar cperl-under-as-char t
624   "*Non-nil means that the _ (underline) should be treated as word char.")
625
626
627 \f
628
629 ;;; Short extra-docs.
630
631 (defvar cperl-tips 'please-ignore-this-line
632   "Get newest version of this package from
633   ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
634 and/or
635   ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
636
637 Get support packages choose-color.el (or font-lock-extra.el before
638 19.30), imenu-go.el from the same place.  \(Look for other files there
639 too... ;-) Get a patch for imenu.el in 19.29.  Note that for 19.30 and
640 later you should use choose-color.el *instead* of font-lock-extra.el 
641 \(and you will not get smart highlighting in C :-().
642
643 Note that to enable Compile choices in the menu you need to install
644 mode-compile.el.
645
646 Get perl5-info from 
647   $CPAN/doc/manual/info/perl-info.tar.gz
648 older version was on
649   http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz
650
651 If you use imenu-go, run imenu on perl5-info buffer (you can do it
652 from CPerl menu). If many files are related, generate TAGS files from
653 Tools/Tags submenu in CPerl menu.
654
655 If some class structure is too complicated, use Tools/Hierarchy-view
656 from CPerl menu, or hierarchic view of imenu. The second one uses the
657 current buffer only, the first one requires generation of TAGS from
658 CPerl/Tools/Tags menu beforehand.
659
660 Run CPerl/Tools/Insert-spaces-if-needed to fix your lazy typing.
661
662 Switch auto-help on/off with CPerl/Tools/Auto-help.
663
664 Before reporting (non-)problems look in the problem section on what I
665 know about them.")
666
667 (defvar cperl-problems 'please-ignore-this-line
668 "Emacs has a _very_ restricted syntax parsing engine. 
669
670 It may be corrected on the level of C code, please look in the
671 `non-problems' section if you want to volunteer.
672
673 CPerl mode tries to corrects some Emacs misunderstandings, however,
674 for efficiency reasons the degree of correction is different for
675 different operations. The partially corrected problems are: POD
676 sections, here-documents, regexps. The operations are: highlighting,
677 indentation, electric keywords, electric braces. 
678
679 This may be confusing, since the regexp s#//#/#\; may be highlighted
680 as a comment, but it will be recognized as a regexp by the indentation
681 code. Or the opposite case, when a pod section is highlighted, but
682 may break the indentation of the following code (though indentation
683 should work if the balance of delimiters is not broken by POD).
684
685 The main trick (to make $ a \"backslash\") makes constructions like
686 ${aaa} look like unbalanced braces. The only trick I can think of is
687 to insert it as $ {aaa} (legal in perl5, not in perl4). 
688
689 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
690 as /($|\\s)/. Note that such a transposition is not always possible
691 :-(.  " )
692
693 (defvar cperl-non-problems 'please-ignore-this-line
694 "As you know from `problems' section, Perl syntax is too hard for CPerl.
695
696 Most the time, if you write your own code, you may find an equivalent
697 \(and almost as readable) expression.
698
699 Try to help CPerl: add comments with embedded quotes to fix CPerl
700 misunderstandings about the end of quotation:
701
702 $a='500$';      # ';
703
704 You won't need it too often. The reason: $ \"quotes\" the following
705 character (this saves a life a lot of times in CPerl), thus due to
706 Emacs parsing rules it does not consider tick (i.e., ' ) after a
707 dollar as a closing one, but as a usual character.
708
709 Now the indentation code is pretty wise. The only drawback is that it
710 relies on Emacs parsing to find matching parentheses. And Emacs
711 *cannot* match parentheses in Perl 100% correctly. So
712         1 if s#//#/#;
713 will not break indentation, but
714         1 if ( s#//#/# );
715 will.
716
717 By similar reasons
718         s\"abc\"def\";
719 will confuse CPerl a lot.
720
721 If you still get wrong indentation in situation that you think the
722 code should be able to parse, try:
723
724 a) Check what Emacs thinks about balance of your parentheses.
725 b) Supply the code to me (IZ).
726
727 Pods are treated _very_ rudimentally. Here-documents are not treated
728 at all (except highlighting and inhibiting indentation). (This may
729 change some time. RMS approved making syntax lookup recognize text
730 attributes, but volunteers are needed to change Emacs C code.)
731
732 To speed up coloring the following compromises exist:
733    a) sub in $mypackage::sub may be highlighted.
734    b) -z in [a-z] may be highlighted.
735    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
736
737
738 Imenu in 19.31 is broken. Set `imenu-use-keymap-menu' to t, and remove
739 `car' before `imenu-choose-buffer-index' in `imenu'.
740 ")
741
742 (defvar cperl-praise 'please-ignore-this-line
743   "RMS asked me to list good things about CPerl. Here they go:
744
745 0) It uses the newest `syntax-table' property ;-);
746
747 1) It does 99% of Perl syntax correct (as opposed to 80-90% in Perl
748 mode - but the latter number may have improved too in last years) even 
749 without `syntax-table' property; When using this property, it should 
750 handle 99.995% of lines correct - or somesuch.
751
752 2) It is generally belived to be \"the most user-friendly Emacs
753 package\" whatever it may mean (I doubt that the people who say similar
754 things tried _all_ the rest of Emacs ;-), but this was not a lonely
755 voice);
756
757 3) Everything is customizable, one-by-one or in a big sweep;
758
759 4) It has many easily-accessable \"tools\":
760         a) Can run program, check syntax, start debugger;
761         b) Can lineup vertically \"middles\" of rows, like `=' in
762                 a  = b;
763                 cc = d;
764         c) Can insert spaces where this impoves readability (in one
765                 interactive sweep over the buffer);
766         d) Has support for imenu, including:
767                 1) Separate unordered list of \"interesting places\";
768                 2) Separate TOC of POD sections;
769                 3) Separate list of packages;
770                 4) Hierarchical view of methods in (sub)packages;
771                 5) and functions (by the full name - with package);
772         e) Has an interface to INFO docs for Perl; The interface is
773                 very flexible, including shrink-wrapping of
774                 documentation buffer/frame;
775         f) Has a builtin list of one-line explanations for perl constructs.
776         g) Can show these explanations if you stay long enough at the
777                 corresponding place (or on demand);
778         h) Has an enhanced fontification (using 3 or 4 additional faces
779                 comparing to font-lock - basically, different
780                 namespaces in Perl have different colors);
781         i) Can construct TAGS basing on its knowledge of Perl syntax,
782                 the standard menu has 6 different way to generate
783                 TAGS (if by directory, .xs files - with C-language
784                 bindings - are included in the scan);
785         j) Can build a hierarchical view of classes (via imenu) basing
786                 on generated TAGS file;
787         k) Has electric parentheses, electric newlines, uses Abbrev
788                 for electric logical constructs
789                         while () {}
790                 with different styles of expansion (context sensitive
791                 to be not so bothering). Electric parentheses behave
792                 \"as they should\" in a presence of a visible region.
793         l) Changes msb.el \"on the fly\" to insert a group \"Perl files\";
794
795 5) The indentation engine was very smart, but most of tricks may be
796 not needed anymore with the support for `syntax-table' property. Has
797 progress indicator for indentation (with `imenu' loaded).
798
799 6) Indent-region improves inline-comments as well;
800
801 7) Fill-paragraph correctly handles multi-line comments;
802 ")
803
804 \f
805
806 ;;; Portability stuff:
807
808 (defmacro cperl-define-key (fsf-key definition &optional xemacs-key)
809   (` (define-key cperl-mode-map
810        (, (if xemacs-key
811               (` (if cperl-xemacs-p (, xemacs-key) (, fsf-key)))
812             fsf-key))
813        (, definition))))
814
815 (defvar del-back-ch (car (append (where-is-internal 'delete-backward-char)
816                                  (where-is-internal 'backward-delete-char-untabify)))
817   "Character generated by key bound to delete-backward-char.")
818
819 (and (vectorp del-back-ch) (= (length del-back-ch) 1) 
820      (setq del-back-ch (aref del-back-ch 0)))
821
822 (if cperl-xemacs-p
823     (progn
824       ;; "Active regions" are on: use region only if active
825       ;; "Active regions" are off: use region unconditionally
826       (defun cperl-use-region-p ()
827         (if zmacs-regions (mark) t))
828       (defun cperl-mark-active () (mark)))
829   (defun cperl-use-region-p ()
830     (if transient-mark-mode mark-active t))
831   (defun cperl-mark-active () mark-active))
832
833 (defsubst cperl-enable-font-lock ()
834   (or cperl-xemacs-p window-system))
835
836 (if (boundp 'unread-command-events)
837     (if cperl-xemacs-p
838         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
839           (setq unread-command-events (list (character-to-event c))))
840       (defun cperl-putback-char (c)     ; Emacs 19
841         (setq unread-command-events (list c))))
842   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
843     (setq unread-command-event (character-to-event c))))
844
845 (or (fboundp 'uncomment-region)
846     (defun uncomment-region (beg end)
847       (interactive "r")
848       (comment-region beg end -1)))
849
850 (defvar cperl-do-not-fontify
851   (if (string< emacs-version "19.30")
852       'fontified
853     'lazy-lock)
854   "Text property which inhibits refontification.")
855
856 (defsubst cperl-put-do-not-fontify (from to)
857   (put-text-property (max (point-min) (1- from))
858                      to cperl-do-not-fontify t))
859
860 (defvar cperl-mode-hook nil
861   "Hook run by `cperl-mode'.")
862
863 \f
864 ;;; Probably it is too late to set these guys already, but it can help later:
865
866 (setq auto-mode-alist
867       (append '(("\\.\\([pP][Llm]\\|al\\)$" . perl-mode))  auto-mode-alist ))
868 (and (boundp 'interpreter-mode-alist)
869      (setq interpreter-mode-alist (append interpreter-mode-alist
870                                           '(("miniperl" . perl-mode)))))
871 (if (fboundp 'eval-when-compile)
872     (eval-when-compile
873       (condition-case nil
874           (require 'imenu)
875         (error nil))
876       (condition-case nil
877           (require 'easymenu)
878         (error nil))
879       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
880       ;; macros instead of defsubsts don't work on Emacs, so we do the
881       ;; expansion manually. Any other suggestions?
882       (if (or (string-match "XEmacs\\|Lucid" emacs-version)
883               window-system)
884           (require 'font-lock))
885       (require 'cl)
886       ))
887
888 (defvar cperl-mode-abbrev-table nil
889   "Abbrev table in use in Cperl-mode buffers.")
890
891 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
892
893 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
894
895 (if cperl-mode-map nil
896   (setq cperl-mode-map (make-sparse-keymap))
897   (cperl-define-key "{" 'cperl-electric-lbrace)
898   (cperl-define-key "[" 'cperl-electric-paren)
899   (cperl-define-key "(" 'cperl-electric-paren)
900   (cperl-define-key "<" 'cperl-electric-paren)
901   (cperl-define-key "}" 'cperl-electric-brace)
902   (cperl-define-key "]" 'cperl-electric-rparen)
903   (cperl-define-key ")" 'cperl-electric-rparen)
904   (cperl-define-key ";" 'cperl-electric-semi)
905   (cperl-define-key ":" 'cperl-electric-terminator)
906   (cperl-define-key "\C-j" 'newline-and-indent)
907   (cperl-define-key "\C-c\C-j" 'cperl-linefeed)
908   (cperl-define-key "\C-c\C-a" 'cperl-toggle-auto-newline)
909   (cperl-define-key "\C-c\C-k" 'cperl-toggle-abbrev)
910   (cperl-define-key "\C-c\C-e" 'cperl-toggle-electric)
911   (cperl-define-key "\e\C-q" 'cperl-indent-exp) ; Usually not bound
912   (cperl-define-key [?\C-\M-\|] 'cperl-lineup
913                     [(control meta |)])
914   ;;(cperl-define-key "\M-q" 'cperl-fill-paragraph)
915   ;;(cperl-define-key "\e;" 'cperl-indent-for-comment)
916   (cperl-define-key "\177" 'cperl-electric-backspace)
917   (cperl-define-key "\t" 'cperl-indent-command)
918   ;; don't clobber the backspace binding:
919   (cperl-define-key "\C-c\C-hf" 'cperl-info-on-current-command
920                     [(control c) (control h) f])
921   (cperl-define-key "\C-hf"
922                     ;;(concat (char-to-string help-char) "f") ; does not work
923                     'cperl-info-on-command
924                     [(control h) f])
925   (cperl-define-key "\C-hv"
926                     ;;(concat (char-to-string help-char) "v") ; does not work
927                     'cperl-get-help
928                     [(control h) v])
929   (if (and cperl-xemacs-p 
930            (<= emacs-minor-version 11) (<= emacs-major-version 19))
931       (progn
932         ;; substitute-key-definition is usefulness-deenhanced...
933         (cperl-define-key "\M-q" 'cperl-fill-paragraph)
934         (cperl-define-key "\e;" 'cperl-indent-for-comment)
935         (cperl-define-key "\e\C-\\" 'cperl-indent-region))
936     (substitute-key-definition
937      'indent-sexp 'cperl-indent-exp
938      cperl-mode-map global-map)
939     (substitute-key-definition
940      'fill-paragraph 'cperl-fill-paragraph
941      cperl-mode-map global-map)
942     (substitute-key-definition
943      'indent-region 'cperl-indent-region
944      cperl-mode-map global-map)
945     (substitute-key-definition
946      'indent-for-comment 'cperl-indent-for-comment
947      cperl-mode-map global-map)))
948
949 (defvar cperl-menu)
950 (condition-case nil
951     (progn
952       (require 'easymenu)
953       (easy-menu-define cperl-menu cperl-mode-map "Menu for CPerl mode"
954          '("Perl"
955            ["Beginning of function" beginning-of-defun t]
956            ["End of function" end-of-defun t]
957            ["Mark function" mark-defun t]
958            ["Indent expression" cperl-indent-exp t]
959            ["Fill paragraph/comment" cperl-fill-paragraph t]
960            "----"
961            ["Line up a construction" cperl-lineup (cperl-use-region-p)]
962            ["Beautify a regexp" cperl-beautify-regexp
963             cperl-use-syntax-table-text-property]
964            ["Beautify a group in regexp" cperl-beautify-level
965             cperl-use-syntax-table-text-property]
966            ["Contract a group in regexp" cperl-contract-level
967             cperl-use-syntax-table-text-property]
968            "----"
969            ["Indent region" cperl-indent-region (cperl-use-region-p)]
970            ["Comment region" cperl-comment-region (cperl-use-region-p)]
971            ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
972            "----"
973            ["Run" mode-compile (fboundp 'mode-compile)]
974            ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
975                                           (get-buffer "*compilation*"))]
976            ["Next error" next-error (get-buffer "*compilation*")]
977            ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
978            "----"
979            ["Debugger" cperl-db t]
980            "----"
981            ("Tools"
982             ["Imenu" imenu (fboundp 'imenu)]
983             ["Insert spaces if needed" cperl-find-bad-style t]
984             ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
985             ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
986             ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
987             ("Tags"
988 ;;;          ["Create tags for current file" cperl-etags t]
989 ;;;          ["Add tags for current file" (cperl-etags t) t]
990 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
991 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
992 ;;;          ["Create tags for Perl files in (sub)directories" 
993 ;;;           (cperl-etags nil 'recursive) t]
994 ;;;          ["Add tags for Perl files in (sub)directories"
995 ;;;           (cperl-etags t 'recursive) t]) 
996 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
997              ["Create tags for current file" (cperl-write-tags nil t) t]
998              ["Add tags for current file" (cperl-write-tags) t]
999              ["Create tags for Perl files in directory" 
1000               (cperl-write-tags nil t nil t) t]
1001              ["Add tags for Perl files in directory" 
1002               (cperl-write-tags nil nil nil t) t]
1003              ["Create tags for Perl files in (sub)directories" 
1004               (cperl-write-tags nil t t t) t]
1005              ["Add tags for Perl files in (sub)directories"
1006               (cperl-write-tags nil nil t t) t])
1007             ["Recalculate \"hard\" constructions" cperl-find-pods-heres t]
1008             ["Define word at point" imenu-go-find-at-position 
1009              (fboundp 'imenu-go-find-at-position)]
1010             ["Help on function" cperl-info-on-command t]
1011             ["Help on function at point" cperl-info-on-current-command t]
1012             ["Help on symbol at point" cperl-get-help t]
1013             ["Auto-help on" cperl-lazy-install (fboundp 'run-with-idle-timer)]
1014             ["Auto-help off" cperl-lazy-unstall 
1015              (fboundp 'run-with-idle-timer)])
1016            ("Toggle..."
1017             ["Auto newline" cperl-toggle-auto-newline t]
1018             ["Electric parens" cperl-toggle-electric t]
1019             ["Electric keywords" cperl-toggle-abbrev t]
1020             )
1021            ("Indent styles..."
1022             ["GNU" (cperl-set-style "GNU") t]
1023             ["C++" (cperl-set-style "C++") t]
1024             ["FSF" (cperl-set-style "FSF") t]
1025             ["BSD" (cperl-set-style "BSD") t]
1026             ["Whitesmith" (cperl-set-style "Whitesmith") t])
1027            ("Micro-docs"
1028             ["Tips" (describe-variable 'cperl-tips) t]
1029             ["Problems" (describe-variable 'cperl-problems) t]
1030             ["Non-problems" (describe-variable 'cperl-non-problems) t]
1031             ["Praise" (describe-variable 'cperl-praise) t]))))
1032   (error nil))
1033
1034 (autoload 'c-macro-expand "cmacexp"
1035   "Display the result of expanding all C macros occurring in the region.
1036 The expansion is entirely correct because it uses the C preprocessor."
1037   t)
1038
1039 (defvar cperl-mode-syntax-table nil
1040   "Syntax table in use in Cperl-mode buffers.")
1041
1042 (defvar cperl-string-syntax-table nil
1043   "Syntax table in use in Cperl-mode string-like chunks.")
1044
1045 (if cperl-mode-syntax-table
1046     ()
1047   (setq cperl-mode-syntax-table (make-syntax-table))
1048   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
1049   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
1050   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
1051   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
1052   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
1053   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
1054   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
1055   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
1056   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
1057   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
1058   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
1059   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
1060   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
1061   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
1062   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
1063   (if cperl-under-as-char
1064       (modify-syntax-entry ?_ "w" cperl-mode-syntax-table))
1065   (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
1066   (modify-syntax-entry ?| "." cperl-mode-syntax-table)
1067   (setq cperl-string-syntax-table (copy-syntax-table cperl-mode-syntax-table))
1068   (modify-syntax-entry ?$ "." cperl-string-syntax-table)
1069   (modify-syntax-entry ?# "." cperl-string-syntax-table) ; (?# comment )
1070 )
1071
1072
1073 \f
1074 ;; Make customization possible "in reverse"
1075 ;;(defun cperl-set (symbol to)
1076 ;;  (or (eq (symbol-value symbol) 'null) (set symbol to)))
1077 (defsubst cperl-val (symbol &optional default hairy)
1078   (cond
1079    ((eq (symbol-value symbol) 'null) default)
1080    (cperl-hairy (or hairy t))
1081    (t (symbol-value symbol))))
1082 \f
1083 ;; provide an alias for working with emacs 19.  the perl-mode that comes
1084 ;; with it is really bad, and this lets us seamlessly replace it.
1085 (fset 'perl-mode 'cperl-mode)
1086 (defvar cperl-faces-init)
1087 ;; Fix for msb.el
1088 (defvar cperl-msb-fixed nil)
1089 (defun cperl-mode ()
1090   "Major mode for editing Perl code.
1091 Expression and list commands understand all C brackets.
1092 Tab indents for Perl code.
1093 Paragraphs are separated by blank lines only.
1094 Delete converts tabs to spaces as it moves back.
1095
1096 Various characters in Perl almost always come in pairs: {}, (), [],
1097 sometimes <>. When the user types the first, she gets the second as
1098 well, with optional special formatting done on {}.  (Disabled by
1099 default.)  You can always quote (with \\[quoted-insert]) the left
1100 \"paren\" to avoid the expansion. The processing of < is special,
1101 since most the time you mean \"less\". Cperl mode tries to guess
1102 whether you want to type pair <>, and inserts is if it
1103 appropriate. You can set `cperl-electric-parens-string' to the string that
1104 contains the parenths from the above list you want to be electrical.
1105 Electricity of parenths is controlled by `cperl-electric-parens'.
1106 You may also set `cperl-electric-parens-mark' to have electric parens
1107 look for active mark and \"embrace\" a region if possible.'
1108
1109 CPerl mode provides expansion of the Perl control constructs:
1110    if, else, elsif, unless, while, until, for, and foreach.
1111 =========(Disabled by default, see `cperl-electric-keywords'.)
1112 The user types the keyword immediately followed by a space, which causes
1113 the construct to be expanded, and the user is positioned where she is most
1114 likely to want to be.
1115 eg. when the user types a space following \"if\" the following appears in
1116 the buffer:
1117             if () {     or   if ()
1118             }                 {
1119                               }
1120 and the cursor is between the parentheses.  The user can then type some
1121 boolean expression within the parens.  Having done that, typing
1122 \\[cperl-linefeed] places you, appropriately indented on a new line
1123 between the braces. If CPerl decides that you want to insert
1124 \"English\" style construct like
1125             bite if angry;
1126 it will not do any expansion. See also help on variable 
1127 `cperl-extra-newline-before-brace'.
1128
1129 \\[cperl-linefeed] is a convenience replacement for typing carriage
1130 return. It places you in the next line with proper indentation, or if
1131 you type it inside the inline block of control construct, like
1132             foreach (@lines) {print; print}
1133 and you are on a boundary of a statement inside braces, it will
1134 transform the construct into a multiline and will place you into an
1135 appropriately indented blank line. If you need a usual 
1136 `newline-and-indent' behaviour, it is on \\[newline-and-indent], 
1137 see documentation on `cperl-electric-linefeed'.
1138
1139 \\{cperl-mode-map}
1140
1141 Setting the variable `cperl-font-lock' to t switches on
1142 font-lock-mode, `cperl-electric-lbrace-space' to t switches on
1143 electric space between $ and {, `cperl-electric-parens-string' is the
1144 string that contains parentheses that should be electric in CPerl (see
1145 also `cperl-electric-parens-mark' and `cperl-electric-parens'),
1146 setting `cperl-electric-keywords' enables electric expansion of
1147 control structures in CPerl. `cperl-electric-linefeed' governs which
1148 one of two linefeed behavior is preferable. You can enable all these
1149 options simultaneously (recommended mode of use) by setting
1150 `cperl-hairy' to t. In this case you can switch separate options off
1151 by setting them to `null'. Note that one may undo the extra whitespace
1152 inserted by semis and braces in `auto-newline'-mode by consequent
1153 \\[cperl-electric-backspace].
1154
1155 If your site has perl5 documentation in info format, you can use commands
1156 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
1157 These keys run commands `cperl-info-on-current-command' and
1158 `cperl-info-on-command', which one is which is controlled by variable
1159 `cperl-info-on-command-no-prompt' (in turn affected by `cperl-hairy').
1160
1161 Even if you have no info-format documentation, short one-liner-style
1162 help is available on \\[cperl-get-help]. 
1163
1164 It is possible to show this help automatically after some idle
1165 time. This is regulated by variable `cperl-lazy-help-time'.  Default
1166 with `cperl-hairy' is 5 secs idle time if the value of this variable
1167 is nil.  It is also possible to switch this on/off from the
1168 menu. Requires `run-with-idle-timer'.
1169
1170 Use \\[cperl-lineup] to vertically lineup some construction - put the
1171 beginning of the region at the start of construction, and make region
1172 span the needed amount of lines.
1173
1174 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
1175 `cperl-pod-face', `cperl-pod-head-face' control processing of pod and
1176 here-docs sections. In a future version results of scan may be used
1177 for indentation too, currently they are used for highlighting only.
1178
1179 Variables controlling indentation style:
1180  `cperl-tab-always-indent'
1181     Non-nil means TAB in CPerl mode should always reindent the current line,
1182     regardless of where in the line point is when the TAB command is used.
1183  `cperl-auto-newline'
1184     Non-nil means automatically newline before and after braces,
1185     and after colons and semicolons, inserted in Perl code. The following
1186     \\[cperl-electric-backspace] will remove the inserted whitespace.
1187     Insertion after colons requires both this variable and 
1188     `cperl-auto-newline-after-colon' set. 
1189  `cperl-auto-newline-after-colon'
1190     Non-nil means automatically newline even after colons.
1191     Subject to `cperl-auto-newline' setting.
1192  `cperl-indent-level'
1193     Indentation of Perl statements within surrounding block.
1194     The surrounding block's indentation is the indentation
1195     of the line on which the open-brace appears.
1196  `cperl-continued-statement-offset'
1197     Extra indentation given to a substatement, such as the
1198     then-clause of an if, or body of a while, or just a statement continuation.
1199  `cperl-continued-brace-offset'
1200     Extra indentation given to a brace that starts a substatement.
1201     This is in addition to `cperl-continued-statement-offset'.
1202  `cperl-brace-offset'
1203     Extra indentation for line if it starts with an open brace.
1204  `cperl-brace-imaginary-offset'
1205     An open brace following other text is treated as if it the line started
1206     this far to the right of the actual line indentation.
1207  `cperl-label-offset'
1208     Extra indentation for line that is a label.
1209  `cperl-min-label-indent'
1210     Minimal indentation for line that is a label.
1211
1212 Settings for K&R and BSD indentation styles are
1213   `cperl-indent-level'                5    8
1214   `cperl-continued-statement-offset'  5    8
1215   `cperl-brace-offset'               -5   -8
1216   `cperl-label-offset'               -5   -8
1217
1218 If `cperl-indent-level' is 0, the statement after opening brace in column 0 is indented on `cperl-brace-offset'+`cperl-continued-statement-offset'.
1219
1220 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
1221 with no args."
1222   (interactive)
1223   (kill-all-local-variables)
1224   ;;(if cperl-hairy
1225   ;;    (progn
1226   ;;    (cperl-set 'cperl-font-lock cperl-hairy)
1227   ;;    (cperl-set 'cperl-electric-lbrace-space cperl-hairy)
1228   ;;    (cperl-set 'cperl-electric-parens "{[(<")
1229   ;;    (cperl-set 'cperl-electric-keywords cperl-hairy)
1230   ;;    (cperl-set 'cperl-electric-linefeed cperl-hairy)))
1231   (use-local-map cperl-mode-map)
1232   (if (cperl-val 'cperl-electric-linefeed)
1233       (progn
1234         (local-set-key "\C-J" 'cperl-linefeed)
1235         (local-set-key "\C-C\C-J" 'newline-and-indent)))
1236   (if (cperl-val 'cperl-info-on-command-no-prompt)
1237       (progn
1238         ;; don't clobber the backspace binding:
1239         (cperl-define-key "\C-hf" 'cperl-info-on-current-command [(control h) f])
1240         (cperl-define-key "\C-c\C-hf" 'cperl-info-on-command
1241                           [(control c) (control h) f])))
1242   (setq major-mode 'perl-mode)
1243   (setq mode-name "CPerl")
1244   (if (not cperl-mode-abbrev-table)
1245       (let ((prev-a-c abbrevs-changed))
1246         (define-abbrev-table 'cperl-mode-abbrev-table '(
1247                 ("if" "if" cperl-electric-keyword 0)
1248                 ("elsif" "elsif" cperl-electric-keyword 0)
1249                 ("while" "while" cperl-electric-keyword 0)
1250                 ("until" "until" cperl-electric-keyword 0)
1251                 ("unless" "unless" cperl-electric-keyword 0)
1252                 ("else" "else" cperl-electric-else 0)
1253                 ("for" "for" cperl-electric-keyword 0)
1254                 ("foreach" "foreach" cperl-electric-keyword 0)
1255                 ("do" "do" cperl-electric-keyword 0)))
1256         (setq abbrevs-changed prev-a-c)))
1257   (setq local-abbrev-table cperl-mode-abbrev-table)
1258   (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
1259   (set-syntax-table cperl-mode-syntax-table)
1260   (make-local-variable 'paragraph-start)
1261   (setq paragraph-start (concat "^$\\|" page-delimiter))
1262   (make-local-variable 'paragraph-separate)
1263   (setq paragraph-separate paragraph-start)
1264   (make-local-variable 'paragraph-ignore-fill-prefix)
1265   (setq paragraph-ignore-fill-prefix t)
1266   (make-local-variable 'indent-line-function)
1267   (setq indent-line-function 'cperl-indent-line)
1268   (make-local-variable 'require-final-newline)
1269   (setq require-final-newline t)
1270   (make-local-variable 'comment-start)
1271   (setq comment-start "# ")
1272   (make-local-variable 'comment-end)
1273   (setq comment-end "")
1274   (make-local-variable 'comment-column)
1275   (setq comment-column cperl-comment-column)
1276   (make-local-variable 'comment-start-skip)
1277   (setq comment-start-skip "#+ *")
1278   (make-local-variable 'defun-prompt-regexp)
1279   (setq defun-prompt-regexp "^[ \t]*sub[ \t]+\\([^ \t\n{(;]+\\)[ \t]*")
1280   (make-local-variable 'comment-indent-function)
1281   (setq comment-indent-function 'cperl-comment-indent)
1282   (make-local-variable 'parse-sexp-ignore-comments)
1283   (setq parse-sexp-ignore-comments t)
1284   (make-local-variable 'indent-region-function)
1285   (setq indent-region-function 'cperl-indent-region)
1286   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
1287   (make-local-variable 'imenu-create-index-function)
1288   (setq imenu-create-index-function
1289         (function imenu-example--create-perl-index))
1290   (make-local-variable 'imenu-sort-function)
1291   (setq imenu-sort-function nil)
1292   (make-local-variable 'vc-header-alist)
1293   (setq vc-header-alist cperl-vc-header-alist)
1294   (make-local-variable 'font-lock-defaults)
1295   (setq font-lock-defaults
1296         (if (string< emacs-version "19.30")
1297             '(perl-font-lock-keywords-2)
1298           '((perl-font-lock-keywords
1299              perl-font-lock-keywords-1
1300              perl-font-lock-keywords-2))))
1301   (if cperl-use-syntax-table-text-property
1302       (progn
1303         (make-variable-buffer-local 'parse-sexp-lookup-properties)
1304         ;; Do not introduce variable if not needed, we check it!
1305         (set 'parse-sexp-lookup-properties t)))
1306   (or (fboundp 'cperl-old-auto-fill-mode)
1307       (progn
1308         (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
1309         (defun auto-fill-mode (&optional arg)
1310           (interactive "P")
1311           (cperl-old-auto-fill-mode arg)
1312           (and auto-fill-function (eq major-mode 'perl-mode)
1313                (setq auto-fill-function 'cperl-do-auto-fill)))))
1314   (if (cperl-enable-font-lock)
1315       (if (cperl-val 'cperl-font-lock) 
1316           (progn (or cperl-faces-init (cperl-init-faces))
1317                  (font-lock-mode 1))))
1318   (and (boundp 'msb-menu-cond)
1319        (not cperl-msb-fixed)
1320        (cperl-msb-fix))
1321   (if (featurep 'easymenu)
1322       (easy-menu-add cperl-menu))       ; A NOP under FSF Emacs.
1323   (run-hooks 'cperl-mode-hook)
1324   ;; After hooks since fontification will break this
1325   (if cperl-pod-here-scan (cperl-find-pods-heres)))
1326 \f
1327 ;; Fix for perldb - make default reasonable
1328 (defun cperl-db ()
1329   (interactive)
1330   (require 'gud)
1331   (perldb (read-from-minibuffer "Run perldb (like this): "
1332                                 (if (consp gud-perldb-history)
1333                                     (car gud-perldb-history)
1334                                   (concat "perl " ;;(file-name-nondirectory
1335                                                    ;; I have problems
1336                                                    ;; in OS/2
1337                                                    ;; otherwise
1338                                                    (buffer-file-name)))
1339                                 nil nil
1340                                 '(gud-perldb-history . 1))))
1341 \f
1342
1343 (defun cperl-msb-fix ()
1344   ;; Adds perl files to msb menu, supposes that msb is already loaded
1345   (setq cperl-msb-fixed t)
1346   (let* ((l (length msb-menu-cond))
1347          (last (nth (1- l) msb-menu-cond))
1348          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
1349          (handle (1- (nth 1 last))))
1350     (setcdr precdr (list
1351                     (list
1352                      '(eq major-mode 'perl-mode)
1353                      handle
1354                      "Perl Files (%d)")
1355                     last))))
1356 \f
1357 ;; This is used by indent-for-comment
1358 ;; to decide how much to indent a comment in CPerl code
1359 ;; based on its context. Do fallback if comment is found wrong.
1360
1361 (defvar cperl-wrong-comment)
1362
1363 (defun cperl-comment-indent ()
1364   (let ((p (point)) (c (current-column)) was)
1365     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
1366       ;; Wrong comment found
1367       (save-excursion
1368         (setq was (cperl-to-comment-or-eol))
1369         (if (= (point) p)
1370             (progn
1371               (skip-chars-backward " \t")
1372               (max (1+ (current-column)) ; Else indent at comment column
1373                    comment-column))
1374           (if was nil
1375             (insert comment-start)
1376             (backward-char (length comment-start)))
1377           (setq cperl-wrong-comment t)
1378           (indent-to comment-column 1)  ; Indent minimum 1
1379           c)))))                        ; except leave at least one space.
1380
1381 ;;;(defun cperl-comment-indent-fallback ()
1382 ;;;  "Is called if the standard comment-search procedure fails.
1383 ;;;Point is at start of real comment."
1384 ;;;  (let ((c (current-column)) target cnt prevc)
1385 ;;;    (if (= c comment-column) nil
1386 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
1387 ;;;      (setq target (max (1+ (setq prevc 
1388 ;;;                          (current-column))) ; Else indent at comment column
1389 ;;;                comment-column))
1390 ;;;      (if (= c comment-column) nil
1391 ;;;     (delete-backward-char cnt)
1392 ;;;     (while (< prevc target)
1393 ;;;       (insert "\t")
1394 ;;;       (setq prevc (current-column)))
1395 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
1396 ;;;     (while (< prevc target)
1397 ;;;       (insert " ")
1398 ;;;       (setq prevc (current-column)))))))
1399
1400 (defun cperl-indent-for-comment ()
1401   "Substitute for `indent-for-comment' in CPerl."
1402   (interactive)
1403   (let (cperl-wrong-comment)
1404     (indent-for-comment)
1405     (if cperl-wrong-comment
1406         (progn (cperl-to-comment-or-eol)
1407                (forward-char (length comment-start))))))
1408
1409 (defun cperl-comment-region (b e arg)
1410   "Comment or uncomment each line in the region in CPerl mode.
1411 See `comment-region'."
1412   (interactive "r\np")
1413   (let ((comment-start "#"))
1414     (comment-region b e arg)))
1415
1416 (defun cperl-uncomment-region (b e arg)
1417   "Uncomment or comment each line in the region in CPerl mode.
1418 See `comment-region'."
1419   (interactive "r\np")
1420   (let ((comment-start "#"))
1421     (comment-region b e (- arg))))
1422
1423 (defvar cperl-brace-recursing nil)
1424
1425 (defun cperl-electric-brace (arg &optional only-before)
1426   "Insert character and correct line's indentation.
1427 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
1428 place (even in empty line), but not after. If after \")\" and the inserted
1429 char is \"{\", insert extra newline before only if 
1430 `cperl-extra-newline-before-brace'."
1431   (interactive "P")
1432   (let (insertpos
1433         (other-end (if (and cperl-electric-parens-mark
1434                             (cperl-mark-active) 
1435                             (< (mark) (point)))
1436                        (mark) 
1437                      nil)))
1438     (if (and other-end
1439              (not cperl-brace-recursing)
1440              (cperl-val 'cperl-electric-parens)
1441              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point)))
1442         ;; Need to insert a matching pair
1443         (progn
1444           (save-excursion
1445             (setq insertpos (point-marker))
1446             (goto-char other-end)
1447             (setq last-command-char ?\{)
1448             (cperl-electric-lbrace arg insertpos))
1449           (forward-char 1))
1450       (if (and (not arg)                ; No args, end (of empty line or auto)
1451                (eolp)
1452                (or (and (null only-before)
1453                         (save-excursion
1454                           (skip-chars-backward " \t")
1455                           (bolp)))
1456                    (and (eq last-command-char ?\{) ; Do not insert newline
1457                         ;; if after ")" and `cperl-extra-newline-before-brace'
1458                         ;; is nil, do not insert extra newline.
1459                         (not cperl-extra-newline-before-brace)
1460                         (save-excursion
1461                           (skip-chars-backward " \t")
1462                           (eq (preceding-char) ?\))))
1463                    (if cperl-auto-newline 
1464                        (progn (cperl-indent-line) (newline) t) nil)))
1465           (progn
1466             (insert last-command-char)
1467             (cperl-indent-line)
1468             (if cperl-auto-newline
1469                 (setq insertpos (1- (point))))
1470             (if (and cperl-auto-newline (null only-before))
1471                 (progn
1472                   (newline)
1473                   (cperl-indent-line)))
1474             (save-excursion
1475               (if insertpos (progn (goto-char insertpos)
1476                                    (search-forward (make-string 
1477                                                     1 last-command-char))
1478                                    (setq insertpos (1- (point)))))
1479               (delete-char -1))))
1480       (if insertpos
1481           (save-excursion
1482             (goto-char insertpos)
1483             (self-insert-command (prefix-numeric-value arg)))
1484         (self-insert-command (prefix-numeric-value arg))))))
1485
1486 (defun cperl-electric-lbrace (arg &optional end)
1487   "Insert character, correct line's indentation, correct quoting by space."
1488   (interactive "P")
1489   (let (pos after 
1490             (cperl-brace-recursing t)
1491             (cperl-auto-newline cperl-auto-newline)
1492             (other-end (or end
1493                            (if (and cperl-electric-parens-mark
1494                                     (cperl-mark-active)
1495                                     (> (mark) (point)))
1496                                (save-excursion
1497                                  (goto-char (mark))
1498                                  (point-marker)) 
1499                              nil))))
1500     (and (cperl-val 'cperl-electric-lbrace-space)
1501          (eq (preceding-char) ?$)
1502          (save-excursion
1503            (skip-chars-backward "$")
1504            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
1505          (insert ? ))
1506     (if (cperl-after-expr-p nil "{;)") nil (setq cperl-auto-newline nil))
1507     (cperl-electric-brace arg)
1508     (and (cperl-val 'cperl-electric-parens)
1509          (eq last-command-char ?{)
1510          (memq last-command-char 
1511                (append cperl-electric-parens-string nil))
1512          (or (if other-end (goto-char (marker-position other-end)))
1513              t)
1514          (setq last-command-char ?} pos (point))
1515          (progn (cperl-electric-brace arg t)
1516                 (goto-char pos)))))
1517
1518 (defun cperl-electric-paren (arg)
1519   "Insert a matching pair of parentheses."
1520   (interactive "P")
1521   (let ((beg (save-excursion (beginning-of-line) (point)))
1522         (other-end (if (and cperl-electric-parens-mark
1523                             (cperl-mark-active) 
1524                             (> (mark) (point)))
1525                            (save-excursion
1526                              (goto-char (mark))
1527                              (point-marker)) 
1528                      nil)))
1529     (if (and (cperl-val 'cperl-electric-parens)
1530              (memq last-command-char
1531                    (append cperl-electric-parens-string nil))
1532              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
1533              ;;(not (save-excursion (search-backward "#" beg t)))
1534              (if (eq last-command-char ?<)
1535                  (cperl-after-expr-p nil "{;(,:=")
1536                1))
1537         (progn
1538           (insert last-command-char)
1539           (if other-end (goto-char (marker-position other-end)))
1540           (insert (cdr (assoc last-command-char '((?{ .?})
1541                                                   (?[ . ?])
1542                                                   (?( . ?))
1543                                                   (?< . ?>)))))
1544           (forward-char -1))
1545       (insert last-command-char)
1546       )))
1547
1548 (defun cperl-electric-rparen (arg)
1549   "Insert a matching pair of parentheses if marking is active.
1550 If not, or if we are not at the end of marking range, would self-insert."
1551   (interactive "P")
1552   (let ((beg (save-excursion (beginning-of-line) (point)))
1553         (other-end (if (and cperl-electric-parens-mark
1554                             (cperl-val 'cperl-electric-parens)
1555                             (memq last-command-char
1556                                   (append cperl-electric-parens-string nil))
1557                             (cperl-mark-active) 
1558                             (< (mark) (point)))
1559                        (mark) 
1560                      nil))
1561         p)
1562     (if (and other-end
1563              (cperl-val 'cperl-electric-parens)
1564              (memq last-command-char '( ?\) ?\] ?\} ?\> ))
1565              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
1566              ;;(not (save-excursion (search-backward "#" beg t)))
1567              )
1568         (progn
1569           (insert last-command-char)
1570           (setq p (point))
1571           (if other-end (goto-char other-end))
1572           (insert (cdr (assoc last-command-char '((?\} . ?\{)
1573                                                   (?\] . ?\[)
1574                                                   (?\) . ?\()
1575                                                   (?\> . ?\<)))))
1576           (goto-char (1+ p)))
1577       (call-interactively 'self-insert-command)
1578       )))
1579
1580 (defun cperl-electric-keyword ()
1581   "Insert a construction appropriate after a keyword."
1582   (let ((beg (save-excursion (beginning-of-line) (point))) 
1583         (dollar (eq last-command-char ?$)))
1584     (and (save-excursion
1585            (backward-sexp 1)
1586            (cperl-after-expr-p nil "{;:"))
1587          (save-excursion 
1588            (not 
1589             (re-search-backward
1590              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
1591              beg t)))
1592          (save-excursion (or (not (re-search-backward "^=" nil t))
1593                              (looking-at "=cut")))
1594          (progn
1595            (and dollar (insert " $"))
1596            (cperl-indent-line)
1597            ;;(insert " () {\n}")
1598            (cond
1599             (cperl-extra-newline-before-brace
1600              (insert " ()\n")
1601              (insert "{")
1602              (cperl-indent-line)
1603              (insert "\n")
1604              (cperl-indent-line)
1605              (insert "\n}"))
1606             (t
1607              (insert " () {\n}"))
1608             )
1609            (or (looking-at "[ \t]\\|$") (insert " "))
1610            (cperl-indent-line)
1611            (if dollar (progn (search-backward "$")
1612                              (forward-char 1))
1613              (search-backward ")"))
1614            (cperl-putback-char del-back-ch)))))
1615
1616 (defun cperl-electric-else ()
1617   "Insert a construction appropriate after a keyword."
1618   (let ((beg (save-excursion (beginning-of-line) (point))))
1619     (and (save-excursion
1620            (backward-sexp 1)
1621            (cperl-after-expr-p nil "{;:"))
1622          (save-excursion 
1623            (not 
1624             (re-search-backward
1625              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
1626              beg t)))
1627          (save-excursion (or (not (re-search-backward "^=" nil t))
1628                              (looking-at "=cut")))
1629          (progn
1630            (cperl-indent-line)
1631            ;;(insert " {\n\n}")
1632            (cond
1633             (cperl-extra-newline-before-brace
1634              (insert "\n")
1635              (insert "{")
1636              (cperl-indent-line)
1637              (insert "\n\n}"))
1638             (t
1639              (insert " {\n\n}"))
1640             )
1641            (or (looking-at "[ \t]\\|$") (insert " "))
1642            (cperl-indent-line)
1643            (forward-line -1)
1644            (cperl-indent-line)
1645            (cperl-putback-char del-back-ch)))))
1646
1647 (defun cperl-linefeed ()
1648   "Go to end of line, open a new line and indent appropriately."
1649   (interactive)
1650   (let ((beg (save-excursion (beginning-of-line) (point)))
1651         (end (save-excursion (end-of-line) (point)))
1652         (pos (point)) start)
1653     (if (and                            ; Check if we need to split:
1654                                         ; i.e., on a boundary and inside "{...}" 
1655          (save-excursion (cperl-to-comment-or-eol)
1656            (>= (point) pos))            ; Not in a comment
1657          (or (save-excursion
1658                (skip-chars-backward " \t" beg)
1659                (forward-char -1)
1660                (looking-at "[;{]"))     ; After { or ; + spaces
1661              (looking-at "[ \t]*}")     ; Before }
1662              (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
1663          (save-excursion
1664            (and
1665             (eq (car (parse-partial-sexp pos end -1)) -1) 
1666                                         ; Leave the level of parens
1667             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
1668                                         ; Are at end
1669             (progn
1670               (backward-sexp 1)
1671               (setq start (point-marker))
1672               (<= start pos)))))        ; Redundant? Are after the
1673                                         ; start of parens group.
1674         (progn
1675           (skip-chars-backward " \t")
1676           (or (memq (preceding-char) (append ";{" nil))
1677               (insert ";"))
1678           (insert "\n")
1679           (forward-line -1)
1680           (cperl-indent-line)
1681           (goto-char start)
1682           (or (looking-at "{[ \t]*$")   ; If there is a statement
1683                                         ; before, move it to separate line
1684               (progn
1685                 (forward-char 1)
1686                 (insert "\n")
1687                 (cperl-indent-line)))
1688           (forward-line 1)              ; We are on the target line
1689           (cperl-indent-line)
1690           (beginning-of-line)
1691           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
1692                                             ; after, move it to separate line
1693               (progn
1694                 (end-of-line)
1695                 (search-backward "}" beg)
1696                 (skip-chars-backward " \t")
1697                 (or (memq (preceding-char) (append ";{" nil))
1698                     (insert ";"))
1699                 (insert "\n")
1700                 (cperl-indent-line)
1701                 (forward-line -1)))
1702           (forward-line -1)             ; We are on the line before target 
1703           (end-of-line)
1704           (newline-and-indent))
1705       (end-of-line)                     ; else
1706       (cond
1707        ((and (looking-at "\n[ \t]*{$")
1708              (save-excursion
1709                (skip-chars-backward " \t")
1710                (eq (preceding-char) ?\)))) ; Probably if () {} group
1711                                            ; with an extra newline.
1712         (forward-line 2)
1713         (cperl-indent-line))
1714        ((looking-at "\n[ \t]*$")        ; Next line is empty - use it.
1715         (forward-line 1)
1716         (cperl-indent-line))
1717        (t
1718         (newline-and-indent))))))
1719
1720 (defun cperl-electric-semi (arg)
1721   "Insert character and correct line's indentation."
1722   (interactive "P")
1723   (if cperl-auto-newline
1724       (cperl-electric-terminator arg)
1725     (self-insert-command (prefix-numeric-value arg))))
1726
1727 (defun cperl-electric-terminator (arg)
1728   "Insert character and correct line's indentation."
1729   (interactive "P")
1730   (let (insertpos (end (point)) 
1731                   (auto (and cperl-auto-newline
1732                              (or (not (eq last-command-char ?:))
1733                                  cperl-auto-newline-after-colon))))
1734     (if (and ;;(not arg) 
1735              (eolp)
1736              (not (save-excursion
1737                     (beginning-of-line)
1738                     (skip-chars-forward " \t")
1739                     (or
1740                      ;; Ignore in comment lines
1741                      (= (following-char) ?#)
1742                      ;; Colon is special only after a label
1743                      ;; So quickly rule out most other uses of colon
1744                      ;; and do no indentation for them.
1745                      (and (eq last-command-char ?:)
1746                           (save-excursion
1747                             (forward-word 1)
1748                             (skip-chars-forward " \t")
1749                             (and (< (point) end)
1750                                  (progn (goto-char (- end 1))
1751                                         (not (looking-at ":"))))))
1752                      (progn
1753                        (beginning-of-defun)
1754                        (let ((pps (parse-partial-sexp (point) end)))
1755                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
1756         (progn
1757           (insert last-command-char)
1758           ;;(forward-char -1)
1759           (if auto (setq insertpos (point-marker)))
1760           ;;(forward-char 1)
1761           (cperl-indent-line)
1762           (if auto
1763               (progn
1764                 (newline)
1765                 (cperl-indent-line)))
1766 ;;        (save-excursion
1767 ;;          (if insertpos (progn (goto-char (marker-position insertpos))
1768 ;;                               (search-forward (make-string 
1769 ;;                                                1 last-command-char))
1770 ;;                               (setq insertpos (1- (point)))))
1771 ;;          (delete-char -1))))
1772           (save-excursion
1773             (if insertpos (goto-char (1- (marker-position insertpos)))
1774               (forward-char -1))
1775             (delete-char 1))))
1776     (if insertpos
1777         (save-excursion
1778           (goto-char insertpos)
1779           (self-insert-command (prefix-numeric-value arg)))
1780       (self-insert-command (prefix-numeric-value arg)))))
1781
1782 (defun cperl-electric-backspace (arg)
1783   "Backspace-untabify, or remove the whitespace inserted by an electric key."
1784   (interactive "p")
1785   (if (and cperl-auto-newline 
1786            (memq last-command '(cperl-electric-semi 
1787                                 cperl-electric-terminator
1788                                 cperl-electric-lbrace))
1789            (memq (preceding-char) '(?  ?\t ?\n)))
1790       (let (p)
1791         (if (eq last-command 'cperl-electric-lbrace) 
1792             (skip-chars-forward " \t\n"))
1793         (setq p (point))
1794         (skip-chars-backward " \t\n")
1795         (delete-region (point) p))
1796     (backward-delete-char-untabify arg)))
1797
1798 (defun cperl-inside-parens-p ()
1799   (condition-case ()
1800       (save-excursion
1801         (save-restriction
1802           (narrow-to-region (point)
1803                             (progn (beginning-of-defun) (point)))
1804           (goto-char (point-max))
1805           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
1806     (error nil)))
1807 \f
1808 (defun cperl-indent-command (&optional whole-exp)
1809   "Indent current line as Perl code, or in some cases insert a tab character.
1810 If `cperl-tab-always-indent' is non-nil (the default), always indent current line.
1811 Otherwise, indent the current line only if point is at the left margin
1812 or in the line's indentation; otherwise insert a tab.
1813
1814 A numeric argument, regardless of its value,
1815 means indent rigidly all the lines of the expression starting after point
1816 so that this line becomes properly indented.
1817 The relative indentation among the lines of the expression are preserved."
1818   (interactive "P")
1819   (if whole-exp
1820       ;; If arg, always indent this line as Perl
1821       ;; and shift remaining lines of expression the same amount.
1822       (let ((shift-amt (cperl-indent-line))
1823             beg end)
1824         (save-excursion
1825           (if cperl-tab-always-indent
1826               (beginning-of-line))
1827           (setq beg (point))
1828           (forward-sexp 1)
1829           (setq end (point))
1830           (goto-char beg)
1831           (forward-line 1)
1832           (setq beg (point)))
1833         (if (> end beg)
1834             (indent-code-rigidly beg end shift-amt "#")))
1835     (if (and (not cperl-tab-always-indent)
1836              (save-excursion
1837                (skip-chars-backward " \t")
1838                (not (bolp))))
1839         (insert-tab)
1840       (cperl-indent-line))))
1841
1842 (defun cperl-indent-line (&optional symbol)
1843   "Indent current line as Perl code.
1844 Return the amount the indentation changed by."
1845   (let (indent
1846         beg shift-amt
1847         (case-fold-search nil)
1848         (pos (- (point-max) (point))))
1849     (setq indent (cperl-calculate-indent nil symbol))
1850     (beginning-of-line)
1851     (setq beg (point))
1852     (cond ((or (eq indent nil) (eq indent t))
1853            (setq indent (current-indentation)))
1854           ;;((eq indent t)    ; Never?
1855           ;; (setq indent (cperl-calculate-indent-within-comment)))
1856           ;;((looking-at "[ \t]*#")
1857           ;; (setq indent 0))
1858           (t
1859            (skip-chars-forward " \t")
1860            (if (listp indent) (setq indent (car indent)))
1861            (cond ((looking-at "[A-Za-z_][A-Za-z_0-9]*:[^:]")
1862                   (and (> indent 0)
1863                        (setq indent (max cperl-min-label-indent
1864                                          (+ indent cperl-label-offset)))))
1865                  ((= (following-char) ?})
1866                   (setq indent (- indent cperl-indent-level)))
1867                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
1868                   (setq indent (+ indent cperl-close-paren-offset)))
1869                  ((= (following-char) ?{)
1870                   (setq indent (+ indent cperl-brace-offset))))))
1871     (skip-chars-forward " \t")
1872     (setq shift-amt (- indent (current-column)))
1873     (if (zerop shift-amt)
1874         (if (> (- (point-max) pos) (point))
1875             (goto-char (- (point-max) pos)))
1876       (delete-region beg (point))
1877       (indent-to indent)
1878       ;; If initial point was within line's indentation,
1879       ;; position after the indentation.  Else stay at same point in text.
1880       (if (> (- (point-max) pos) (point))
1881           (goto-char (- (point-max) pos))))
1882     shift-amt))
1883
1884 (defun cperl-after-label ()
1885   ;; Returns true if the point is after label. Does not do save-excursion.
1886   (and (eq (preceding-char) ?:)
1887        (memq (char-syntax (char-after (- (point) 2)))
1888              '(?w ?_))
1889        (progn
1890          (backward-sexp)
1891          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))
1892
1893 (defun cperl-get-state (&optional parse-start start-state)
1894   ;; returns list (START STATE DEPTH PRESTART), START is a good place
1895   ;; to start parsing, STATE is what is returned by
1896   ;; `parse-partial-sexp'. DEPTH is true is we are immediately after
1897   ;; end of block which contains START. PRESTART is the position
1898   ;; basing on which START was found.
1899   (save-excursion
1900     (let ((start-point (point)) depth state start prestart)
1901       (if parse-start
1902           (goto-char parse-start)
1903         (beginning-of-defun))
1904       (setq prestart (point))
1905       (if start-state nil
1906         ;; Try to go out, if sub is not on the outermost level
1907         (while (< (point) start-point)
1908           (setq start (point) parse-start start depth nil
1909                 state (parse-partial-sexp start start-point -1))
1910           (if (> (car state) -1) nil
1911             ;; The current line could start like }}}, so the indentation
1912             ;; corresponds to a different level than what we reached
1913             (setq depth t)
1914             (beginning-of-line 2)))     ; Go to the next line.
1915         (if start (goto-char start)))   ; Not at the start of file
1916       (setq start (point))
1917       (if (< start start-point) (setq parse-start start))
1918       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
1919       (list start state depth prestart))))
1920
1921 (defun cperl-block-p ()                 ; Do not C-M-q ! One string contains ";" !
1922   ;; Positions is before ?\{. Checks whether it starts a block.
1923   ;; No save-excursion!
1924   (cperl-backward-to-noncomment (point-min))
1925   ;;(skip-chars-backward " \t\n\f")
1926   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label! \C-@ at bobp
1927                                         ; Label may be mixed up with `$blah :'
1928       (save-excursion (cperl-after-label))
1929       (and (memq (char-syntax (preceding-char)) '(?w ?_))
1930            (progn
1931              (backward-sexp)
1932              ;; Need take into account `bless', `return', `tr',...
1933              (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
1934                       (not (looking-at "\\(bless\\|return\\|qw\\|tr\\|[smy]\\)\\>")))
1935                  (progn
1936                    (skip-chars-backward " \t\n\f")
1937                    (and (memq (char-syntax (preceding-char)) '(?w ?_))
1938                         (progn
1939                           (backward-sexp)
1940                           (looking-at 
1941                            "sub[ \t]+[a-zA-Z0-9_:]+[ \t\n\f]*\\(([^()]*)[ \t\n\f]*\\)?[#{]")))))))))
1942
1943 (defvar cperl-look-for-prop '((pod in-pod) (here-doc-delim here-doc-group)))
1944
1945 (defun cperl-calculate-indent (&optional parse-start symbol)
1946   "Return appropriate indentation for current line as Perl code.
1947 In usual case returns an integer: the column to indent to.
1948 Returns nil if line starts inside a string, t if in a comment."
1949   (save-excursion
1950     (if (or
1951          (memq (get-text-property (point) 'syntax-type) 
1952                '(pod here-doc here-doc-delim format))
1953          ;; before start of POD - whitespace found since do not have 'pod!
1954          (and (looking-at "[ \t]*\n=")
1955               (error "Spaces before pod section!"))
1956          (and (not cperl-indent-left-aligned-comments)
1957               (looking-at "^#")))
1958         nil
1959      (beginning-of-line)
1960      (let ((indent-point (point))
1961            (char-after (save-excursion
1962                            (skip-chars-forward " \t")
1963                            (following-char)))
1964            (in-pod (get-text-property (point) 'in-pod))
1965            (pre-indent-point (point))
1966            p prop look-prop)
1967       (cond
1968        (in-pod                          
1969         ;; In the verbatim part, probably code example. What to do???
1970         )
1971        (t 
1972         (save-excursion
1973           ;; Not in pod
1974           (cperl-backward-to-noncomment nil)
1975           (setq p (max (point-min) (1- (point)))
1976                 prop (get-text-property p 'syntax-type)
1977                 look-prop (or (nth 1 (assoc prop cperl-look-for-prop))
1978                               'syntax-type))
1979           (if (memq prop '(pod here-doc format here-doc-delim))
1980               (progn
1981                 (goto-char (or (previous-single-property-change p look-prop) 
1982                                (point-min)))
1983                 (beginning-of-line)
1984                 (setq pre-indent-point (point)))))))
1985       (goto-char pre-indent-point)
1986       (let* ((case-fold-search nil)
1987              (s-s (cperl-get-state))
1988              (start (nth 0 s-s))
1989              (state (nth 1 s-s))
1990              (containing-sexp (car (cdr state)))
1991              (start-indent (save-excursion
1992                              (goto-char start)
1993                              (- (current-indentation)
1994                                 (if (nth 2 s-s) cperl-indent-level 0))))
1995              old-indent)
1996         ;;      (or parse-start (null symbol)
1997         ;;        (setq parse-start (symbol-value symbol) 
1998         ;;              start-indent (nth 2 parse-start) 
1999         ;;              parse-start (car parse-start)))
2000         ;;      (if parse-start
2001         ;;        (goto-char parse-start)
2002         ;;      (beginning-of-defun))
2003         ;;      ;; Try to go out
2004         ;;      (while (< (point) indent-point)
2005         ;;      (setq start (point) parse-start start moved nil
2006         ;;            state (parse-partial-sexp start indent-point -1))
2007         ;;      (if (> (car state) -1) nil
2008         ;;        ;; The current line could start like }}}, so the indentation
2009         ;;        ;; corresponds to a different level than what we reached
2010         ;;        (setq moved t)
2011         ;;        (beginning-of-line 2)))       ; Go to the next line.
2012         ;;      (if start                               ; Not at the start of file
2013         ;;        (progn
2014         ;;          (goto-char start)
2015         ;;          (setq start-indent (current-indentation))
2016         ;;          (if moved                   ; Should correct...
2017         ;;              (setq start-indent (- start-indent cperl-indent-level))))
2018         ;;      (setq start-indent 0))
2019         ;;      (if (< (point) indent-point) (setq parse-start (point)))
2020         ;;      (or state (setq state (parse-partial-sexp 
2021         ;;                           (point) indent-point -1 nil start-state)))
2022         ;;      (setq containing-sexp 
2023         ;;          (or (car (cdr state)) 
2024         ;;              (and (>= (nth 6 state) 0) old-containing-sexp))
2025         ;;          old-containing-sexp nil start-state nil)
2026 ;;;;      (while (< (point) indent-point)
2027 ;;;;    (setq parse-start (point))
2028 ;;;;    (setq state (parse-partial-sexp (point) indent-point -1 nil start-state))
2029 ;;;;    (setq containing-sexp 
2030 ;;;;          (or (car (cdr state)) 
2031 ;;;;              (and (>= (nth 6 state) 0) old-containing-sexp))
2032 ;;;;          old-containing-sexp nil start-state nil))
2033         ;;      (if symbol (set symbol (list indent-point state start-indent)))
2034         ;;      (goto-char indent-point)
2035         (cond ((or (nth 3 state) (nth 4 state))
2036                ;; return nil or t if should not change this line
2037                (nth 4 state))
2038               ((null containing-sexp)
2039                ;; Line is at top level.  May be data or function definition,
2040                ;; or may be function argument declaration.
2041                ;; Indent like the previous top level line
2042                ;; unless that ends in a closeparen without semicolon,
2043                ;; in which case this line is the first argument decl.
2044                (skip-chars-forward " \t")
2045                (+ start-indent
2046                   (if (= (following-char) ?{) cperl-continued-brace-offset 0)
2047                   (progn
2048                     (cperl-backward-to-noncomment (or parse-start (point-min)))
2049                     ;;(skip-chars-backward " \t\f\n")
2050                     ;; Look at previous line that's at column 0
2051                     ;; to determine whether we are in top-level decls
2052                     ;; or function's arg decls.  Set basic-indent accordingly.
2053                     ;; Now add a little if this is a continuation line.
2054                     (if (or (bobp)
2055                             (memq (preceding-char) (append " ;}" nil)) ; Was ?\)
2056                             (memq char-after (append ")]}" nil))
2057                             (and (eq (preceding-char) ?\:) ; label
2058                                  (progn
2059                                    (forward-sexp -1)
2060                                    (skip-chars-backward " \t")
2061                                    (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*[ \t]*:")))) 
2062                         0
2063                       cperl-continued-statement-offset))))
2064               ((/= (char-after containing-sexp) ?{)
2065                ;; line is expression, not statement:
2066                ;; indent to just after the surrounding open,
2067                ;; skip blanks if we do not close the expression.
2068                (goto-char (1+ containing-sexp))
2069                (or (memq char-after (append ")]}" nil))
2070                    (looking-at "[ \t]*\\(#\\|$\\)")
2071                    (skip-chars-forward " \t"))
2072                (current-column))
2073               ((progn
2074                  ;; Containing-expr starts with \{. Check whether it is a hash.
2075                  (goto-char containing-sexp)
2076                  (not (cperl-block-p)))
2077                (goto-char (1+ containing-sexp))
2078                (or (eq char-after ?\})
2079                    (looking-at "[ \t]*\\(#\\|$\\)")
2080                    (skip-chars-forward " \t"))
2081                (+ (current-column)      ; Correct indentation of trailing ?\}
2082                   (if (eq char-after ?\}) (+ cperl-indent-level
2083                                              cperl-close-paren-offset) 
2084                     0)))
2085               (t
2086                ;; Statement level.  Is it a continuation or a new statement?
2087                ;; Find previous non-comment character.
2088                (goto-char pre-indent-point)
2089                (cperl-backward-to-noncomment containing-sexp)
2090                ;; Back up over label lines, since they don't
2091                ;; affect whether our line is a continuation.
2092                (while (or (eq (preceding-char) ?\,)
2093                           (and (eq (preceding-char) ?:)
2094                                (or;;(eq (char-after (- (point) 2)) ?\') ; ????
2095                                 (memq (char-syntax (char-after (- (point) 2)))
2096                                       '(?w ?_)))))
2097                  (if (eq (preceding-char) ?\,)
2098                      ;; Will go to beginning of line, essentially.
2099                      ;; Will ignore embedded sexpr XXXX.
2100                      (cperl-backward-to-start-of-continued-exp containing-sexp))
2101                  (beginning-of-line)
2102                  (cperl-backward-to-noncomment containing-sexp))
2103                ;; Now we get the answer.
2104                (if (not (memq (preceding-char) (append ", ;}{" '(nil)))) ; Was ?\,
2105                    ;; This line is continuation of preceding line's statement;
2106                    ;; indent  `cperl-continued-statement-offset'  more than the
2107                    ;; previous line of the statement.
2108                    (progn
2109                      (cperl-backward-to-start-of-continued-exp containing-sexp)
2110                      (+ (if (memq char-after (append "}])" nil))
2111                             0           ; Closing parenth
2112                           cperl-continued-statement-offset)
2113                         (current-column)
2114                         (if (eq char-after ?\{)
2115                             cperl-continued-brace-offset 0)))
2116                  ;; This line starts a new statement.
2117                  ;; Position following last unclosed open.
2118                  (goto-char containing-sexp)
2119                  ;; Is line first statement after an open-brace?
2120                  (or
2121                   ;; If no, find that first statement and indent like
2122                   ;; it.  If the first statement begins with label, do
2123                   ;; not believe when the indentation of the label is too
2124                   ;; small.
2125                   (save-excursion
2126                     (forward-char 1)
2127                     (setq old-indent (current-indentation))
2128                     (let ((colon-line-end 0))
2129                       (while (progn (skip-chars-forward " \t\n")
2130                                     (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]"))
2131                         ;; Skip over comments and labels following openbrace.
2132                         (cond ((= (following-char) ?\#)
2133                                (forward-line 1))
2134                               ;; label:
2135                               (t
2136                                (save-excursion (end-of-line)
2137                                                (setq colon-line-end (point)))
2138                                (search-forward ":"))))
2139                       ;; The first following code counts
2140                       ;; if it is before the line we want to indent.
2141                       (and (< (point) indent-point)
2142                            (if (> colon-line-end (point)) ; After label
2143                                (if (> (current-indentation) 
2144                                       cperl-min-label-indent)
2145                                    (- (current-indentation) cperl-label-offset)
2146                                  ;; Do not believe: `max' is involved
2147                                  (+ old-indent cperl-indent-level))
2148                              (current-column)))))
2149                   ;; If no previous statement,
2150                   ;; indent it relative to line brace is on.
2151                   ;; For open brace in column zero, don't let statement
2152                   ;; start there too.  If cperl-indent-level is zero,
2153                   ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
2154                   ;; For open-braces not the first thing in a line,
2155                   ;; add in cperl-brace-imaginary-offset.
2156
2157                   ;; If first thing on a line:  ?????
2158                   (+ (if (and (bolp) (zerop cperl-indent-level))
2159                          (+ cperl-brace-offset cperl-continued-statement-offset)
2160                        cperl-indent-level)
2161                      ;; Move back over whitespace before the openbrace.
2162                      ;; If openbrace is not first nonwhite thing on the line,
2163                      ;; add the cperl-brace-imaginary-offset.
2164                      (progn (skip-chars-backward " \t")
2165                             (if (bolp) 0 cperl-brace-imaginary-offset))
2166                      ;; If the openbrace is preceded by a parenthesized exp,
2167                      ;; move to the beginning of that;
2168                      ;; possibly a different line
2169                      (progn
2170                        (if (eq (preceding-char) ?\))
2171                            (forward-sexp -1))
2172                        ;; In the case it starts a subroutine, indent with
2173                        ;; respect to `sub', not with respect to the the
2174                        ;; first thing on the line, say in the case of
2175                        ;; anonymous sub in a hash.
2176                        ;;
2177                        (skip-chars-backward " \t")
2178                        (if (and (eq (preceding-char) ?b)
2179                                 (progn
2180                                   (forward-sexp -1)
2181                                   (looking-at "sub\\>"))
2182                                 (setq old-indent 
2183                                       (nth 1 
2184                                            (parse-partial-sexp 
2185                                             (save-excursion (beginning-of-line) (point)) 
2186                                             (point)))))
2187                            (progn (goto-char (1+ old-indent))
2188                                   (skip-chars-forward " \t")
2189                                   (current-column))
2190                          ;; Get initial indentation of the line we are on.
2191                          ;; If line starts with label, calculate label indentation
2192                          (if (save-excursion
2193                                (beginning-of-line)
2194                                (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
2195                              (if (> (current-indentation) cperl-min-label-indent)
2196                                  (- (current-indentation) cperl-label-offset)
2197                                (cperl-calculate-indent 
2198                                 (if (and parse-start (<= parse-start (point)))
2199                                     parse-start)))
2200                            (current-indentation))))))))))))))
2201
2202 (defvar cperl-indent-alist
2203   '((string nil)
2204     (comment nil)
2205     (toplevel 0)
2206     (toplevel-after-parenth 2)
2207     (toplevel-continued 2)
2208     (expression 1))
2209   "Alist of indentation rules for CPerl mode.
2210 The values mean:
2211   nil: do not indent;
2212   number: add this amount of indentation.")
2213
2214 (defun cperl-where-am-i (&optional parse-start start-state)
2215   ;; Unfinished
2216   "Return a list of lists ((TYPE POS)...) of good points before the point.
2217 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'."
2218   (save-excursion
2219     (let* ((start-point (point))
2220            (s-s (cperl-get-state))
2221            (start (nth 0 s-s))
2222            (state (nth 1 s-s))
2223            (prestart (nth 3 s-s))
2224            (containing-sexp (car (cdr state)))
2225            (case-fold-search nil)
2226            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
2227       (cond ((nth 3 state)              ; In string
2228              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
2229             ((nth 4 state)              ; In comment
2230              (setq res (cons '(comment) res)))
2231             ((null containing-sexp)
2232              ;; Line is at top level.  
2233              ;; Indent like the previous top level line
2234              ;; unless that ends in a closeparen without semicolon,
2235              ;; in which case this line is the first argument decl.
2236              (cperl-backward-to-noncomment (or parse-start (point-min)))
2237              ;;(skip-chars-backward " \t\f\n")
2238              (cond
2239               ((or (bobp)
2240                    (memq (preceding-char) (append ";}" nil)))
2241                (setq res (cons (list 'toplevel start) res)))
2242               ((eq (preceding-char) ?\) )
2243                (setq res (cons (list 'toplevel-after-parenth start) res)))
2244               (t 
2245                (setq res (cons (list 'toplevel-continued start) res)))))
2246             ((/= (char-after containing-sexp) ?{)
2247              ;; line is expression, not statement:
2248              ;; indent to just after the surrounding open.
2249              ;; skip blanks if we do not close the expression.
2250              (setq res (cons (list 'expression-blanks
2251                                    (progn
2252                                      (goto-char (1+ containing-sexp))
2253                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
2254                                          (skip-chars-forward " \t"))
2255                                      (point)))
2256                              (cons (list 'expression containing-sexp) res))))
2257             ((progn
2258               ;; Containing-expr starts with \{. Check whether it is a hash.
2259               (goto-char containing-sexp)
2260               (not (cperl-block-p)))
2261              (setq res (cons (list 'expression-blanks
2262                                    (progn
2263                                      (goto-char (1+ containing-sexp))
2264                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
2265                                          (skip-chars-forward " \t"))
2266                                      (point)))
2267                              (cons (list 'expression containing-sexp) res))))
2268             (t
2269              ;; Statement level.
2270              (setq res (cons (list 'in-block containing-sexp) res))
2271              ;; Is it a continuation or a new statement?
2272              ;; Find previous non-comment character.
2273              (cperl-backward-to-noncomment containing-sexp)
2274              ;; Back up over label lines, since they don't
2275              ;; affect whether our line is a continuation.
2276              ;; Back up comma-delimited lines too ?????
2277              (while (or (eq (preceding-char) ?\,)
2278                         (save-excursion (cperl-after-label)))
2279                (if (eq (preceding-char) ?\,)
2280                    ;; Will go to beginning of line, essentially
2281                      ;; Will ignore embedded sexpr XXXX.
2282                    (cperl-backward-to-start-of-continued-exp containing-sexp))
2283                (beginning-of-line)
2284                (cperl-backward-to-noncomment containing-sexp))
2285              ;; Now we get the answer.
2286              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
2287                  ;; This line is continuation of preceding line's statement.
2288                  (list (list 'statement-continued containing-sexp))
2289                ;; This line starts a new statement.
2290                ;; Position following last unclosed open.
2291                (goto-char containing-sexp)
2292                ;; Is line first statement after an open-brace?
2293                (or
2294                 ;; If no, find that first statement and indent like
2295                 ;; it.  If the first statement begins with label, do
2296                 ;; not believe when the indentation of the label is too
2297                 ;; small.
2298                 (save-excursion
2299                   (forward-char 1)
2300                   (let ((colon-line-end 0))
2301                     (while (progn (skip-chars-forward " \t\n" start-point)
2302                                   (and (< (point) start-point)
2303                                        (looking-at
2304                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
2305                       ;; Skip over comments and labels following openbrace.
2306                       (cond ((= (following-char) ?\#)
2307                              ;;(forward-line 1)
2308                              (end-of-line))
2309                             ;; label:
2310                             (t
2311                              (save-excursion (end-of-line)
2312                                              (setq colon-line-end (point)))
2313                              (search-forward ":"))))
2314                     ;; Now at the point, after label, or at start 
2315                     ;; of first statement in the block.
2316                     (and (< (point) start-point)
2317                          (if (> colon-line-end (point)) 
2318                              ;; Before statement after label
2319                              (if (> (current-indentation) 
2320                                     cperl-min-label-indent)
2321                                  (list (list 'label-in-block (point)))
2322                                ;; Do not believe: `max' is involved
2323                                (list
2324                                 (list 'label-in-block-min-indent (point))))
2325                            ;; Before statement
2326                            (list 'statement-in-block (point))))))
2327                 ;; If no previous statement,
2328                 ;; indent it relative to line brace is on.
2329                 ;; For open brace in column zero, don't let statement
2330                 ;; start there too.  If cperl-indent-level is zero,
2331                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
2332                 ;; For open-braces not the first thing in a line,
2333                 ;; add in cperl-brace-imaginary-offset.
2334
2335                 ;; If first thing on a line:  ?????
2336                 (+ (if (and (bolp) (zerop cperl-indent-level))
2337                        (+ cperl-brace-offset cperl-continued-statement-offset)
2338                      cperl-indent-level)
2339                    ;; Move back over whitespace before the openbrace.
2340                    ;; If openbrace is not first nonwhite thing on the line,
2341                    ;; add the cperl-brace-imaginary-offset.
2342                    (progn (skip-chars-backward " \t")
2343                           (if (bolp) 0 cperl-brace-imaginary-offset))
2344                    ;; If the openbrace is preceded by a parenthesized exp,
2345                    ;; move to the beginning of that;
2346                    ;; possibly a different line
2347                    (progn
2348                      (if (eq (preceding-char) ?\))
2349                          (forward-sexp -1))
2350                      ;; Get initial indentation of the line we are on.
2351                      ;; If line starts with label, calculate label indentation
2352                      (if (save-excursion
2353                            (beginning-of-line)
2354                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_0-9]*:[^:]"))
2355                          (if (> (current-indentation) cperl-min-label-indent)
2356                              (- (current-indentation) cperl-label-offset)
2357                            (cperl-calculate-indent 
2358                             (if (and parse-start (<= parse-start (point)))
2359                                 parse-start)))
2360                        (current-indentation))))))))
2361       res)))
2362
2363 (defun cperl-calculate-indent-within-comment ()
2364   "Return the indentation amount for line, assuming that
2365 the current line is to be regarded as part of a block comment."
2366   (let (end star-start)
2367     (save-excursion
2368       (beginning-of-line)
2369       (skip-chars-forward " \t")
2370       (setq end (point))
2371       (and (= (following-char) ?#)
2372            (forward-line -1)
2373            (cperl-to-comment-or-eol)
2374            (setq end (point)))
2375       (goto-char end)
2376       (current-column))))
2377
2378
2379 (defun cperl-to-comment-or-eol ()
2380   "Goes to position before comment on the current line, or to end of line.
2381 Returns true if comment is found."
2382   (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
2383       (beginning-of-line)
2384       (if (or 
2385            (eq (get-text-property (point) 'syntax-type) 'pod)
2386            (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t))
2387           (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
2388         ;; Else
2389         (while (not stop-in)
2390           (setq state (parse-partial-sexp (point) lim nil nil nil t))
2391                                         ; stop at comment
2392           ;; If fails (beginning-of-line inside sexp), then contains not-comment
2393           ;; Do simplified processing
2394           ;;(if (re-search-forward "[^$]#" lim 1)
2395           ;;      (progn
2396           ;;    (forward-char -1)
2397           ;;    (skip-chars-backward " \t\n\f" lim))
2398           ;;    (goto-char lim))                ; No `#' at all
2399           ;;)
2400           (if (nth 4 state)             ; After `#';
2401                                         ; (nth 2 state) can be
2402                                         ; beginning of m,s,qq and so
2403                                         ; on
2404               (if (nth 2 state)
2405                   (progn
2406                     (setq cpoint (point))
2407                     (goto-char (nth 2 state))
2408                     (cond
2409                      ((looking-at "\\(s\\|tr\\)\\>")
2410                       (or (re-search-forward
2411                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
2412                            lim 'move)
2413                           (setq stop-in t)))
2414                      ((looking-at "\\(m\\|q\\([qxw]\\)?\\)\\>")
2415                       (or (re-search-forward
2416                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
2417                            lim 'move)
2418                           (setq stop-in t)))
2419                      (t                 ; It was fair comment
2420                       (setq stop-in t)  ; Finish
2421                       (goto-char (1- cpoint)))))
2422                 (setq stop-in t)        ; Finish
2423                 (forward-char -1))
2424             (setq stop-in t))           ; Finish
2425           )
2426         (nth 4 state))))
2427
2428 (defsubst cperl-1- (p)
2429   (max (point-min) (1- p)))
2430
2431 (defsubst cperl-1+ (p)
2432   (min (point-max) (1+ p)))
2433
2434 (defvar cperl-st-cfence '(14))          ; Comment-fence
2435 (defvar cperl-st-sfence '(15))          ; String-fence
2436 (defvar cperl-st-punct '(1))
2437 (defvar cperl-st-word '(2))
2438
2439 (defun cperl-protect-defun-start (s e)
2440   ;; C code looks for "^\\s(" to skip comment backward in "hard" situations
2441   (save-excursion
2442     (goto-char s)
2443     (while (re-search-forward "^\\s(" e 'to-end)
2444       (put-text-property (1- (point)) (point) 'syntax-table cperl-st-punct))))
2445
2446 (defun cperl-commentify (bb e string)
2447   (if cperl-use-syntax-table-text-property 
2448       (progn
2449         ;; We suppose that e is _after_ the end of construction, as after eol.
2450         (setq string (if string cperl-st-sfence cperl-st-cfence))
2451         (put-text-property bb (1+ bb) 'syntax-table string)
2452         (put-text-property bb (1+ bb) 'rear-nonsticky t)
2453         (put-text-property (1- e) e 'syntax-table string)
2454         (put-text-property (1- e) e 'rear-nonsticky t)
2455         (if (and (eq string cperl-st-sfence) (> (- e 2) bb))
2456             (put-text-property (1+ bb) (1- e) 
2457                                'syntax-table cperl-string-syntax-table))
2458         (cperl-protect-defun-start bb e))))
2459
2460 (defun cperl-forward-re (is-2arg set-st st-l err-l argument
2461                                  &optional ostart oend)
2462   ;; Unfinished
2463   ;; Works *before* syntax recognition is done
2464   ;; May modify syntax-type text property if the situation is too hard
2465   (let (b starter ender st i i2)
2466     (skip-chars-forward " \t")
2467     ;; ender means matching-char matcher.
2468     (setq b (point) 
2469           starter (char-after b)
2470           ;; ender:
2471           ender (cdr (assoc starter '(( ?\( . ?\) )
2472                                       ( ?\[ . ?\] )
2473                                       ( ?\{ . ?\} )
2474                                       ( ?\< . ?\> )
2475                                       ))))
2476     ;; What if starter == ?\\  ????
2477     (if set-st
2478         (if (car st-l)
2479             (setq st (car st-l))
2480           (setcar st-l (make-syntax-table))
2481           (setq i 0 st (car st-l))
2482           (while (< i 256)
2483             (modify-syntax-entry i "." st)
2484             (setq i (1+ i)))
2485           (modify-syntax-entry ?\\ "\\" st)))
2486     (setq set-st t)
2487     ;; Whether we have an intermediate point
2488     (setq i nil)
2489     ;; Prepare the syntax table:
2490     (and set-st
2491          (if (not ender)                ; m/blah/, s/x//, s/x/y/
2492              (modify-syntax-entry starter "$" st)
2493            (modify-syntax-entry starter (concat "(" (list ender)) st)
2494            (modify-syntax-entry ender  (concat ")" (list starter)) st)))
2495     (condition-case bb
2496         (progn
2497           (if (and (eq starter (char-after (cperl-1+ b)))
2498                    (not ender))
2499               ;; $ has TeXish matching rules, so $$ equiv $...
2500               (forward-char 2)
2501             (set-syntax-table st)
2502             (forward-sexp 1)
2503             (set-syntax-table cperl-mode-syntax-table)
2504             ;; Now the problem is with m;blah;;
2505             (and (not ender)
2506                  (eq (preceding-char)
2507                      (char-after (- (point) 2)))
2508                  (save-excursion
2509                    (forward-char -2)
2510                    (= 0 (% (skip-chars-backward "\\\\") 2)))
2511                  (forward-char -1)))
2512           (and is-2arg                  ; Have trailing part
2513                (not ender)
2514                (eq (following-char) starter) ; Empty trailing part
2515                (if (eq (char-syntax (following-char)) ?.)
2516                    (setq is-2arg nil)   ; Ignore the tail
2517                  ;; Make trailing letter into punctuation
2518                  (setq is-2arg nil)     ; Ignore the tail
2519                  (put-text-property (point) (1+ (point))
2520                                     'syntax-table cperl-st-punct)
2521                  (put-text-property (point) (1+ (point)) 'rear-nonsticky t)))
2522           (if is-2arg                   ; Not number => have second part
2523               (progn
2524                 (setq i (point) i2 i)
2525                 (if ender
2526                     (if (eq (char-syntax (following-char)) ?\ )
2527                         (progn
2528                           (while (looking-at "\\s *#")
2529                             (beginning-of-line 2))
2530                           (skip-chars-forward " \t\n\f")
2531                           (setq i2 (point))))
2532                   (forward-char -1))
2533                 (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
2534                 (if ender (modify-syntax-entry ender "." st))           
2535                 (setq set-st nil)
2536                 (setq 
2537                  ender
2538                  (cperl-forward-re nil t st-l err-l argument starter ender)
2539                  ender (nth 2 ender)))))
2540       (error (goto-char (point-max))
2541              (message
2542               "End of `%s%s%c ... %c' string not found: %s"
2543               argument
2544               (if ostart (format "%c ... %c" ostart (or oend ostart)) "")
2545               starter (or ender starter) bb)
2546              (or (car err-l) (setcar err-l b))))
2547     (if set-st
2548         (progn
2549           (modify-syntax-entry starter (if (eq starter ?\\) "\\" ".") st)
2550           (if ender (modify-syntax-entry ender "." st))))
2551     (list i i2 ender starter)))
2552
2553 (defun cperl-find-pods-heres (&optional min max)
2554   "Scans the buffer for hard-to-parse Perl constructions.
2555 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify 
2556 the sections using `cperl-pod-head-face', `cperl-pod-face', 
2557 `cperl-here-face'."
2558   (interactive)
2559   (or min (setq min (point-min)))
2560   (or max (setq max (point-max)))
2561   (let (face head-face here-face b e bb tag qtag b1 e1 argument i c tail state 
2562              (cperl-pod-here-fontify (eval cperl-pod-here-fontify))
2563              (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
2564              (modified (buffer-modified-p))
2565              (after-change-functions nil)
2566              (state-point (point-min)) 
2567              (st-l '(nil)) (err-l '(nil)) i2
2568              ;; Somehow font-lock may be not loaded yet...
2569              (font-lock-string-face (if (boundp 'font-lock-string-face)
2570                                         font-lock-string-face
2571                                       'font-lock-string-face))
2572              (search
2573               (concat
2574                "\\(\\`\n?\\|\n\n\\)=" 
2575                "\\|"
2576                ;; One extra () before this:
2577                "<<" 
2578                  "\\(" 
2579                  ;; First variant "BLAH" or just ``.
2580                     "\\([\"'`]\\)"
2581                     "\\([^\"'`\n]*\\)"
2582                     "\\3"
2583                  "\\|"
2584                  ;; Second variant: Identifier or empty
2585                    "\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)"
2586                    ;; Check that we do not have <<= or << 30 or << $blah.
2587                    "\\([^= \t$@%&]\\|[ \t]+[^ \t\n0-9$@%&]\\)"
2588                  "\\)"
2589                "\\|"
2590                ;; 1+6 extra () before this:
2591                "^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
2592                (if cperl-use-syntax-table-text-property
2593                    (concat
2594                     "\\|"
2595                     ;; 1+6+2=9 extra () before this:
2596                     "\\<\\(q[wxq]?\\|[msy]\\|tr\\)\\>"
2597                     "\\|"
2598                     ;; 1+6+2+1=10 extra () before this:
2599                     "\\([?/]\\)"        ; /blah/ or ?blah?
2600                     "\\|"
2601                     ;; 1+6+2+1+1=11 extra () before this:
2602                     "\\<sub\\>[ \t]*\\([a-zA-Z_:'0-9]+[ \t]*\\)?\\(([^()]*)\\)"
2603                     "\\|"
2604                     ;; 1+6+2+1+1+2=13 extra () before this:
2605                     "\\$\\(['{]\\)"
2606                     "\\|"
2607                     ;; 1+6+2+1+1+2+1=14 extra () before this:
2608                     "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'"
2609                     ;; 1+6+2+1+1+2+1+1=15 extra () before this:
2610                     "\\|"
2611                     "__\\(END\\|DATA\\)__"  ; Commented - does not help with indent...
2612                     )
2613                  ""))))
2614     (unwind-protect
2615         (progn
2616           (save-excursion
2617             (message "Scanning for \"hard\" Perl constructions...")
2618             (if cperl-pod-here-fontify
2619                 ;; We had evals here, do not know why...
2620                 (setq face cperl-pod-face
2621                       head-face cperl-pod-head-face
2622                       here-face cperl-here-face))
2623             (remove-text-properties min max 
2624                                     '(syntax-type t in-pod t syntax-table t))
2625             ;; Need to remove face as well...
2626             (goto-char min)
2627             (if (and (eq system-type 'emx)
2628                      (looking-at "extproc[ \t]")) ; Analogue of #!
2629                 (cperl-commentify min 
2630                                   (save-excursion (end-of-line) (point))
2631                                   nil))
2632             (while (re-search-forward search max t)
2633               (cond 
2634                ((match-beginning 1)     ; POD section
2635                 ;;  "\\(\\`\n?\\|\n\n\\)=" 
2636                 (if (looking-at "\n*cut\\>")
2637                     (progn
2638                       (message "=cut is not preceded by a pod section")
2639                       (or (car err-l) (setcar err-l (point))))
2640                   (beginning-of-line)
2641                 
2642                   (setq b (point) bb b)
2643                   (or (re-search-forward "\n\n=cut\\>" max 'toend)
2644                       (progn
2645                         (message "Cannot find the end of a pod section")
2646                         (or (car err-l) (setcar err-l b))))
2647                   (beginning-of-line 2) ; An empty line after =cut is not POD!
2648                   (setq e (point))
2649                   (put-text-property b e 'in-pod t)
2650                   (goto-char b)
2651                   (while (re-search-forward "\n\n[ \t]" e t)
2652                     ;; We start 'pod 1 char earlier to include the preceding line
2653                     (beginning-of-line)
2654                     (put-text-property (cperl-1- b) (point) 'syntax-type 'pod)
2655                     (cperl-put-do-not-fontify b (point))
2656                     ;;(put-text-property (max (point-min) (1- b))
2657                     ;;               (point) cperl-do-not-fontify t)
2658                     (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
2659                     (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
2660                     (beginning-of-line)
2661                     (setq b (point)))
2662                   (put-text-property (cperl-1- (point)) e 'syntax-type 'pod)
2663                   (cperl-put-do-not-fontify (point) e)
2664                   ;;(put-text-property (max (point-min) (1- (point)))
2665                   ;;               e cperl-do-not-fontify t)
2666                   (if cperl-pod-here-fontify 
2667                       (progn (put-text-property (point) e 'face face)
2668                              (goto-char bb)
2669                              (if (looking-at 
2670                                   "=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
2671                                  (put-text-property 
2672                                   (match-beginning 1) (match-end 1)
2673                                   'face head-face))
2674                              (while (re-search-forward
2675                                      ;; One paragraph
2676                                      "\n\n=[a-zA-Z0-9_]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
2677                                      e 'toend)
2678                                (put-text-property 
2679                                 (match-beginning 1) (match-end 1)
2680                                 'face head-face))))
2681                   (cperl-commentify bb e nil)
2682                   (goto-char e)
2683                   (or (eq e (point-max))
2684                       (forward-char -1)))) ; Prepare for immediate pod start.
2685                ;; Here document
2686                ;; We do only one here-per-line
2687                ;; 1 () ahead
2688                ;; "<<\\(\\([\"'`]\\)\\([^\"'`\n]*\\)\\3\\|\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)\\)"
2689                ((match-beginning 2)     ; 1 + 1
2690                 ;; Abort in comment:
2691                 (setq b (point))
2692                 (setq state (parse-partial-sexp state-point b nil nil state)
2693                       state-point b)
2694                 (if ;;(save-excursion
2695                     ;;  (beginning-of-line)
2696                     ;;  (search-forward "#" b t))
2697                     (or (nth 3 state) (nth 4 state))
2698                     (goto-char (match-end 2))
2699                   (if (match-beginning 5) ;4 + 1
2700                       (setq b1 (match-beginning 5) ; 4 + 1
2701                             e1 (match-end 5)) ; 4 + 1
2702                     (setq b1 (match-beginning 4) ; 3 + 1
2703                           e1 (match-end 4))) ; 3 + 1
2704                   (setq tag (buffer-substring b1 e1)
2705                         qtag (regexp-quote tag))
2706                   (cond (cperl-pod-here-fontify 
2707                          (put-text-property b1 e1 'face font-lock-reference-face)
2708                          (cperl-put-do-not-fontify b1 e1)))
2709                   (forward-line)
2710                   (setq b (point))
2711                   (cond ((re-search-forward (concat "^" qtag "$") max 'toend)
2712                          (if cperl-pod-here-fontify 
2713                              (progn
2714                                (put-text-property (match-beginning 0) (match-end 0) 
2715                                                   'face font-lock-reference-face)
2716                                (cperl-put-do-not-fontify b (match-end 0))
2717                                ;;(put-text-property (max (point-min) (1- b))
2718                                ;;                     (min (point-max)
2719                                ;;                          (1+ (match-end 0)))
2720                                ;;                     cperl-do-not-fontify t)
2721                                (put-text-property b (match-beginning 0) 
2722                                                   'face here-face)))
2723                          (setq e1 (cperl-1+ (match-end 0)))
2724                          (put-text-property b (match-beginning 0) 
2725                                             'syntax-type 'here-doc)
2726                          (put-text-property (match-beginning 0) e1
2727                                             'syntax-type 'here-doc-delim)
2728                          (put-text-property b e1
2729                                             'here-doc-group t)
2730                          (cperl-commentify b e1 nil)
2731                          (cperl-put-do-not-fontify b (match-end 0)))
2732                         (t (message "End of here-document `%s' not found." tag)
2733                            (or (car err-l) (setcar err-l b))))))
2734                ;; format
2735                ((match-beginning 8)
2736                 ;; 1+6=7 extra () before this:
2737                 ;;"^[ \t]*\\(format\\)[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$"
2738                 (setq b (point)
2739                       name (if (match-beginning 8) ; 7 + 1
2740                                (buffer-substring (match-beginning 8) ; 7 + 1
2741                                                  (match-end 8)) ; 7 + 1
2742                              ""))
2743                 (setq argument nil)
2744                 (if cperl-pod-here-fontify 
2745                     (while (and (eq (forward-line) 0)
2746                                 (not (looking-at "^[.;]$")))
2747                       (cond
2748                        ((looking-at "^#")) ; Skip comments
2749                        ((and argument   ; Skip argument multi-lines
2750                              (looking-at "^[ \t]*{")) 
2751                         (forward-sexp 1)
2752                         (setq argument nil))
2753                        (argument        ; Skip argument lines
2754                         (setq argument nil))
2755                        (t               ; Format line
2756                         (setq b1 (point))
2757                         (setq argument (looking-at "^[^\n]*[@^]"))
2758                         (end-of-line)
2759                         (put-text-property b1 (point) 
2760                                            'face font-lock-string-face)
2761                         (cperl-commentify b1 (point) nil)
2762                         (cperl-put-do-not-fontify b1 (point)))))
2763                   (re-search-forward (concat "^[.;]$") max 'toend))
2764                 (beginning-of-line)
2765                 (if (looking-at "^[.;]$")
2766                     (progn
2767                       (put-text-property (point) (+ (point) 2)
2768                                          'face font-lock-string-face)
2769                       (cperl-commentify (point) (+ (point) 2) nil)
2770                       (cperl-put-do-not-fontify (point) (+ (point) 2)))
2771                   (message "End of format `%s' not found." name)
2772                   (or (car err-l) (setcar err-l b)))
2773                 (forward-line)
2774                 (put-text-property b (point) 'syntax-type 'format)
2775 ;;;            (cond ((re-search-forward (concat "^[.;]$") max 'toend)
2776 ;;;                   (if cperl-pod-here-fontify 
2777 ;;;                       (progn
2778 ;;;                         (put-text-property b (match-end 0)
2779 ;;;                                            'face font-lock-string-face)
2780 ;;;                         (cperl-put-do-not-fontify b (match-end 0))))
2781 ;;;                   (put-text-property b (match-end 0) 
2782 ;;;                                      'syntax-type 'format)
2783 ;;;                   (cperl-put-do-not-fontify b (match-beginning 0)))
2784 ;;;                  (t (message "End of format `%s' not found." name)))
2785                 )
2786                ;; Regexp:
2787                ((or (match-beginning 10) (match-beginning 11))
2788                 ;; 1+6+2=9 extra () before this:
2789                 ;; "\\<\\(q[wxq]?\\|[msy]\\|tr\\)\\>"
2790                 ;; "\\|"
2791                 ;; "\\([?/]\\)" ; /blah/ or ?blah?
2792                 (setq b1 (if (match-beginning 10) 10 11)
2793                       argument (buffer-substring
2794                                 (match-beginning b1) (match-end b1))
2795                       b (point)
2796                       i b
2797                       c (char-after (match-beginning b1))
2798                       bb (char-after (1- (match-beginning b1))) ; tmp holder
2799                       bb (and           ; user variables/whatever
2800                           (match-beginning 10)
2801                           (or
2802                            (memq bb '(?\$ ?\@ ?\% ?\*))
2803                            (and (eq bb ?-) (eq c ?s)) ; -s file test
2804                            (and (eq bb ?\&) ; &&m/blah/
2805                                 (not (eq (char-after 
2806                                           (- (match-beginning b1) 2))
2807                                          ?\&))))))
2808                 (or bb
2809                     (if (eq b1 11)      ; bare /blah/ or ?blah?
2810                         (setq argument ""
2811                              bb         ; Not a regexp?
2812                              (progn
2813                                (goto-char (match-beginning b1))
2814                                (cperl-backward-to-noncomment (point-min))
2815                                (not (or (memq (preceding-char)
2816                                               (append (if (eq c ?\?)
2817                                                           ;; $a++ ? 1 : 2
2818                                                           "~{(=|&*!,;"
2819                                                         "~{(=|&+-*!,;") nil))
2820                                         (and (eq (preceding-char) ?\})
2821                                              (cperl-after-block-p (point-min)))
2822                                         (and (eq (char-syntax (preceding-char)) ?w)
2823                                              (progn
2824                                                (forward-sexp -1)
2825                                                (looking-at 
2826                                                 "\\(while\\|if\\|unless\\|until\\|and\\|or\\|not\\|xor\\|split\\|grep\\|map\\|print\\)\\>")))
2827                                         (and (eq (preceding-char) ?.)
2828                                              (eq (char-after (- (point) 2)) ?.))
2829                                         (bobp))))
2830                              b (1- b))))
2831                 (or bb (setq state (parse-partial-sexp 
2832                                     state-point b nil nil state)
2833                              state-point b))
2834                 (goto-char b)
2835                 (if (or bb (nth 3 state) (nth 4 state))
2836                     (goto-char i)
2837                   (skip-chars-forward " \t")
2838                   ;; qtag means two-arg matcher, may be reset to
2839                   ;;   2 or 3 later if some special quoting is needed.
2840                   ;; e1 means matching-char matcher.
2841                   (setq b (point)
2842                         i (cperl-forward-re 
2843                            (string-match "^\\([sy]\\|tr\\)$" argument)
2844                            t st-l err-l argument)
2845                         i2 (nth 1 i)    ; start of the second part
2846                         e1 (nth 2 i)    ; ender, true if matching second part
2847                         i (car i)       ; intermediate point
2848                         tail (if (and i (not e1)) (1- (point))))
2849                   ;; Commenting \\ is dangerous, what about ( ?
2850                   (and i tail
2851                        (eq (char-after i) ?\\)
2852                        (setq i nil tail nil))
2853                   (if (null i)
2854                       (cperl-commentify b (point) t)
2855                     (cperl-commentify b i t)
2856                     (if (looking-at "\\sw*e") ; s///e
2857                         (cperl-find-pods-heres i2 (1- (point)))
2858                       (cperl-commentify i2 (point) t)
2859                       (setq tail nil)))
2860                   (if (eq (char-syntax (following-char)) ?w)
2861                       (progn
2862                         (forward-word 1) ; skip modifiers s///s
2863                         (if tail (cperl-commentify tail (point) t))))))
2864                ((match-beginning 13)    ; sub with prototypes
2865                 (setq b (match-beginning 0))
2866                 (if (memq (char-after (1- b))
2867                           '(?\$ ?\@ ?\% ?\& ?\*))
2868                     nil
2869                   (setq state (parse-partial-sexp 
2870                                state-point (1- b) nil nil state)
2871                         state-point (1- b))
2872                   (if (or (nth 3 state) (nth 4 state))
2873                       nil
2874                     ;; Mark as string
2875                     (cperl-commentify (match-beginning 13) (match-end 13) t))
2876                   (goto-char (match-end 0))))
2877                ;; 1+6+2+1+1+2=13 extra () before this:
2878                ;;    "\\$\\(['{]\\)"
2879                ((and (match-beginning 14)
2880                  (eq (preceding-char) ?\')) ; $'
2881                 (setq b (1- (point))
2882                       state (parse-partial-sexp 
2883                              state-point (1- b) nil nil state)
2884                       state-point (1- b))
2885                 (if (nth 3 state)       ; in string
2886                     (progn
2887                       (put-text-property (1- b) b 'syntax-table cperl-st-punct)
2888                       (put-text-property (1- b) b 'rear-nonsticky t)))
2889                 (goto-char (1+ b)))
2890                ;; 1+6+2+1+1+2=13 extra () before this:
2891                ;;    "\\$\\(['{]\\)"
2892                ((match-beginning 14)    ; ${
2893                 (setq bb (match-beginning 0))
2894                 (put-text-property bb (1+ bb) 'syntax-table cperl-st-punct)
2895                 (put-text-property bb (1+ bb) 'rear-nonsticky t))
2896                ;; 1+6+2+1+1+2+1=14 extra () before this:
2897                ;;    "\\(\\<sub[ \t\n\f]+\\|[&*$@%]\\)[a-zA-Z0-9_]*'")
2898                ((match-beginning 15)    ; old $abc'efg syntax
2899                 (setq bb (match-end 0)
2900                       b (match-beginning 0)
2901                       state (parse-partial-sexp 
2902                              state-point b nil nil state)
2903                       state-point b)
2904                 (if (nth 3 state)       ; in string
2905                     nil
2906                   (put-text-property (1- bb) bb 'syntax-table cperl-st-word))
2907                 (goto-char bb))
2908                ;; 1+6+2+1+1+2+1+1=15 extra () before this:
2909                ;; "__\\(END\\|DATA\\)__"
2910                (t                       ; __END__, __DATA__
2911                 (setq bb (match-end 0)
2912                       b (match-beginning 0)
2913                       state (parse-partial-sexp 
2914                              state-point b nil nil state)
2915                       state-point b)
2916                 (if (or (nth 3 state) (nth 4 state))
2917                     nil
2918                   ;; (put-text-property b (1+ bb) 'syntax-type 'pod) ; Cheat
2919                   (cperl-commentify b bb nil)
2920                   )
2921                 (goto-char bb))))
2922 ;;;         (while (re-search-forward "\\(\\`\n?\\|\n\n\\)=" max t)
2923 ;;;           (if (looking-at "\n*cut\\>")
2924 ;;;               (progn
2925 ;;;                 (message "=cut is not preceded by a pod section")
2926 ;;;                 (setq err (point)))
2927 ;;;             (beginning-of-line)
2928                 
2929 ;;;             (setq b (point) bb b)
2930 ;;;             (or (re-search-forward "\n\n=cut\\>" max 'toend)
2931 ;;;                 (message "Cannot find the end of a pod section"))
2932 ;;;             (beginning-of-line 3)
2933 ;;;             (setq e (point))
2934 ;;;             (put-text-property b e 'in-pod t)
2935 ;;;             (goto-char b)
2936 ;;;             (while (re-search-forward "\n\n[ \t]" e t)
2937 ;;;               (beginning-of-line)
2938 ;;;               (put-text-property b (point) 'syntax-type 'pod)
2939 ;;;               (cperl-put-do-not-fontify b (point))
2940 ;;;               ;;(put-text-property (max (point-min) (1- b))
2941 ;;;               ;;                 (point) cperl-do-not-fontify t)
2942 ;;;               (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
2943 ;;;               (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
2944 ;;;               (beginning-of-line)
2945 ;;;               (setq b (point)))
2946 ;;;             (put-text-property (point) e 'syntax-type 'pod)
2947 ;;;             (cperl-put-do-not-fontify (point) e)
2948 ;;;             ;;(put-text-property (max (point-min) (1- (point)))
2949 ;;;             ;;                 e cperl-do-not-fontify t)
2950 ;;;             (if cperl-pod-here-fontify 
2951 ;;;                 (progn (put-text-property (point) e 'face face)
2952 ;;;                        (goto-char bb)
2953 ;;;                        (if (looking-at 
2954 ;;;                         "=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
2955 ;;;                            (put-text-property 
2956 ;;;                             (match-beginning 1) (match-end 1)
2957 ;;;                             'face head-face))
2958 ;;;                        (while (re-search-forward
2959 ;;;                                ;; One paragraph
2960 ;;;                                "\n\n=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
2961 ;;;                                e 'toend)
2962 ;;;                          (put-text-property 
2963 ;;;                           (match-beginning 1) (match-end 1)
2964 ;;;                           'face head-face))))
2965 ;;;             (goto-char e)))
2966 ;;;         (goto-char min)
2967 ;;;         (while (re-search-forward 
2968 ;;;                 ;; We exclude \n to avoid misrecognition inside quotes.
2969 ;;;                 "<<\\(\\([\"'`]\\)\\([^\"'`\n]*\\)\\2\\|\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)\\)"
2970 ;;;                 max t)
2971 ;;;           (if (match-beginning 4)
2972 ;;;               (setq b1 (match-beginning 4)
2973 ;;;                     e1 (match-end 4))
2974 ;;;             (setq b1 (match-beginning 3)
2975 ;;;                   e1 (match-end 3)))
2976 ;;;           (setq tag (buffer-substring b1 e1)
2977 ;;;                 qtag (regexp-quote tag))
2978 ;;;           (cond (cperl-pod-here-fontify 
2979 ;;;                  (put-text-property b1 e1 'face font-lock-reference-face)
2980 ;;;                  (cperl-put-do-not-fontify b1 e1)))
2981 ;;;           (forward-line)
2982 ;;;           (setq b (point))
2983 ;;;           (cond ((re-search-forward (concat "^" qtag "$") max 'toend)
2984 ;;;                  (if cperl-pod-here-fontify 
2985 ;;;                      (progn
2986 ;;;                        (put-text-property (match-beginning 0) (match-end 0) 
2987 ;;;                                           'face font-lock-reference-face)
2988 ;;;                        (cperl-put-do-not-fontify b (match-end 0))
2989 ;;;                        ;;(put-text-property (max (point-min) (1- b))
2990 ;;;                        ;;                 (min (point-max)
2991 ;;;                        ;;                      (1+ (match-end 0)))
2992 ;;;                        ;;                 cperl-do-not-fontify t)
2993 ;;;                        (put-text-property b (match-beginning 0) 
2994 ;;;                                           'face here-face)))
2995 ;;;                  (put-text-property b (match-beginning 0) 
2996 ;;;                                     'syntax-type 'here-doc)
2997 ;;;                  (cperl-put-do-not-fontify b (match-beginning 0)))
2998 ;;;                 (t (message "End of here-document `%s' not found." tag))))
2999 ;;;         (goto-char min)
3000 ;;;         (while (re-search-forward 
3001 ;;;                 "^[ \t]*format[ \t]*\\(\\([a-zA-Z0-9_]+[ \t]*\\)?\\)=[ \t]*$"
3002 ;;;                 max t)
3003 ;;;           (setq b (point)
3004 ;;;                 name (buffer-substring (match-beginning 1)
3005 ;;;                                        (match-end 1)))
3006 ;;;           (cond ((re-search-forward (concat "^[.;]$") max 'toend)
3007 ;;;                  (if cperl-pod-here-fontify 
3008 ;;;                      (progn
3009 ;;;                        (put-text-property b (match-end 0)
3010 ;;;                                           'face font-lock-string-face)
3011 ;;;                        (cperl-put-do-not-fontify b (match-end 0))))
3012 ;;;                  (put-text-property b (match-end 0) 
3013 ;;;                                     'syntax-type 'format)
3014 ;;;                  (cperl-put-do-not-fontify b (match-beginning 0)))
3015 ;;;                 (t (message "End of format `%s' not found." name))))
3016 )
3017           (if (car err-l) (goto-char (car err-l))
3018             (message "Scan for \"hard\" Perl constructions completed.")))
3019       (and (buffer-modified-p)
3020            (not modified)
3021            (set-buffer-modified-p nil))
3022       (set-syntax-table cperl-mode-syntax-table))))
3023
3024 (defun cperl-backward-to-noncomment (lim)
3025   ;; Stops at lim or after non-whitespace that is not in comment
3026   (let (stop p)
3027     (while (and (not stop) (> (point) (or lim 1)))
3028       (skip-chars-backward " \t\n\f" lim)
3029       (setq p (point))
3030       (beginning-of-line)
3031       (if (or (looking-at "^[ \t]*\\(#\\|$\\)")
3032               (progn (cperl-to-comment-or-eol) (bolp)))
3033           nil   ; Only comment, skip
3034         ;; Else
3035         (skip-chars-backward " \t")
3036         (if (< p (point)) (goto-char p))
3037         (setq stop t)))))
3038
3039 (defun cperl-after-block-p (lim)
3040   ;; We suppose that the preceding char is }.
3041   (save-excursion
3042     (condition-case nil
3043         (progn
3044           (forward-sexp -1)
3045           (cperl-backward-to-noncomment lim)
3046           (or (eq (preceding-char) ?\) ) ; if () {}
3047               (and (eq (char-syntax (preceding-char)) ?w) ; else {}
3048                    (progn
3049                      (forward-sexp -1)
3050                      (looking-at "\\(else\\|grep\\|map\\)\\>")))
3051               (cperl-after-expr-p lim)))
3052       (error nil))))
3053
3054 (defun cperl-after-expr-p (&optional lim chars test)
3055   "Returns true if the position is good for start of expression.
3056 TEST is the expression to evaluate at the found position. If absent,
3057 CHARS is a string that contains good characters to have before us (however,
3058 `}' is treated \"smartly\" if it is not in the list)."
3059   (let (stop p 
3060              (lim (or lim (point-min))))
3061     (save-excursion
3062       (while (and (not stop) (> (point) lim))
3063         (skip-chars-backward " \t\n\f" lim)
3064         (setq p (point))
3065         (beginning-of-line)
3066         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
3067           ;; Else: last iteration (What to do with labels?)
3068           (cperl-to-comment-or-eol) 
3069           (skip-chars-backward " \t")
3070           (if (< p (point)) (goto-char p))
3071           (setq stop t)))
3072       (or (bobp)
3073           (progn
3074             (if test (eval test)
3075               (or (memq (preceding-char) (append (or chars "{;") nil))
3076                   (and (eq (preceding-char) ?\})
3077                        (cperl-after-block-p lim)))))))))
3078
3079 (defun cperl-backward-to-start-of-continued-exp (lim)
3080   (if (memq (preceding-char) (append ")]}\"'`" nil))
3081       (forward-sexp -1))
3082   (beginning-of-line)
3083   (if (<= (point) lim)
3084       (goto-char (1+ lim)))
3085   (skip-chars-forward " \t"))
3086
3087 \f
3088 (defvar innerloop-done nil)
3089 (defvar last-depth nil)
3090
3091 (defun cperl-indent-exp ()
3092   "Simple variant of indentation of continued-sexp.
3093 Should be slow. Will not indent comment if it starts at `comment-indent'
3094 or looks like continuation of the comment on the previous line."
3095   (interactive)
3096   (save-excursion
3097     (let ((tmp-end (progn (end-of-line) (point))) top done)
3098       (save-excursion
3099         (beginning-of-line)
3100         (while (null done)
3101           (setq top (point))
3102           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
3103                                                -1)) -1)
3104             (setq top (point)))         ; Get the outermost parenths in line
3105           (goto-char top)
3106           (while (< (point) tmp-end)
3107             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
3108             (or (eolp) (forward-sexp 1)))
3109           (if (> (point) tmp-end) (progn (end-of-line) (setq tmp-end (point)))
3110             (setq done t)))
3111         (goto-char tmp-end)
3112         (setq tmp-end (point-marker)))
3113       (cperl-indent-region (point) tmp-end))))
3114
3115 (defun cperl-indent-region (start end)
3116   "Simple variant of indentation of region in CPerl mode.
3117 Should be slow. Will not indent comment if it starts at `comment-indent' 
3118 or looks like continuation of the comment on the previous line.
3119 Indents all the lines whose first character is between START and END 
3120 inclusive."
3121   (interactive "r")
3122   (save-excursion
3123     (let (st comm indent-info old-comm-indent new-comm-indent 
3124              (pm 0) (imenu-scanning-message "Indenting... (%3d%%)"))
3125       (goto-char start)
3126       (setq old-comm-indent (and (cperl-to-comment-or-eol)
3127                                  (current-column))
3128             new-comm-indent old-comm-indent)
3129       (goto-char start)
3130       (or (bolp) (beginning-of-line 2))
3131       (or (fboundp 'imenu-progress-message)
3132           (message "Indenting... For feedback load `imenu'..."))
3133       (while (and (<= (point) end) (not (eobp))) ; bol to check start
3134         (and (fboundp 'imenu-progress-message)
3135              (imenu-progress-message 
3136               pm (/ (* 100 (- (point) start)) (- end start -1))))
3137         (setq st (point) 
3138               indent-info nil
3139               ) ; Believe indentation of the current
3140         (if (and (setq comm (looking-at "[ \t]*#"))
3141                  (or (eq (current-indentation) (or old-comm-indent 
3142                                                    comment-column))
3143                      (setq old-comm-indent nil)))
3144             (if (and old-comm-indent
3145                      (= (current-indentation) old-comm-indent)
3146                      (not (eq (get-text-property (point) 'syntax-type) 'pod)))
3147                 (let ((comment-column new-comm-indent))
3148                   (indent-for-comment)))
3149           (progn 
3150             (cperl-indent-line 'indent-info)
3151             (or comm
3152                 (progn
3153                   (if (setq old-comm-indent (and (cperl-to-comment-or-eol)
3154                                                  (not (eq (get-text-property (point) 'syntax-type) 'pod))
3155                                                  (current-column)))
3156                       (progn (indent-for-comment)
3157                              (skip-chars-backward " \t")
3158                              (skip-chars-backward "#")
3159                              (setq new-comm-indent (current-column))))))))
3160         (beginning-of-line 2))
3161         (if (fboundp 'imenu-progress-message)
3162              (imenu-progress-message pm 100)
3163           (message nil)))))
3164
3165 ;;(defun cperl-slash-is-regexp (&optional pos)
3166 ;;  (save-excursion
3167 ;;    (goto-char (if pos pos (1- (point))))
3168 ;;    (and
3169 ;;     (not (memq (get-text-property (point) 'face)
3170 ;;              '(font-lock-string-face font-lock-comment-face)))
3171 ;;     (cperl-after-expr-p nil nil '
3172 ;;                     (or (looking-at "[^]a-zA-Z0-9_)}]")
3173 ;;                         (eq (get-text-property (point) 'face)
3174 ;;                             'font-lock-keyword-face))))))
3175
3176 ;; Stolen from lisp-mode with a lot of improvements
3177
3178 (defun cperl-fill-paragraph (&optional justify iteration)
3179   "Like \\[fill-paragraph], but handle CPerl comments.
3180 If any of the current line is a comment, fill the comment or the
3181 block of it that point is in, preserving the comment's initial
3182 indentation and initial hashes. Behaves usually outside of comment."
3183   (interactive "P")
3184   (let (
3185         ;; Non-nil if the current line contains a comment.
3186         has-comment
3187
3188         ;; If has-comment, the appropriate fill-prefix for the comment.
3189         comment-fill-prefix
3190         ;; Line that contains code and comment (or nil)
3191         start
3192         c spaces len dc (comment-column comment-column))
3193     ;; Figure out what kind of comment we are looking at.
3194     (save-excursion
3195       (beginning-of-line)
3196       (cond
3197
3198        ;; A line with nothing but a comment on it?
3199        ((looking-at "[ \t]*#[# \t]*")
3200         (setq has-comment t
3201               comment-fill-prefix (buffer-substring (match-beginning 0)
3202                                                     (match-end 0))))
3203
3204        ;; A line with some code, followed by a comment?  Remember that the
3205        ;; semi which starts the comment shouldn't be part of a string or
3206        ;; character.
3207        ((cperl-to-comment-or-eol)
3208         (setq has-comment t)
3209         (looking-at "#+[ \t]*")
3210         (setq start (point) c (current-column) 
3211               comment-fill-prefix
3212               (concat (make-string (current-column) ?\ )
3213                       (buffer-substring (match-beginning 0) (match-end 0)))
3214               spaces (progn (skip-chars-backward " \t") 
3215                             (buffer-substring (point) start))
3216               dc (- c (current-column)) len (- start (point)) 
3217               start (point-marker))
3218         (delete-char len)
3219         (insert (make-string dc ?-)))))
3220     (if (not has-comment)
3221         (fill-paragraph justify)        ; Do the usual thing outside of comment
3222       ;; Narrow to include only the comment, and then fill the region.
3223       (save-restriction
3224         (narrow-to-region
3225          ;; Find the first line we should include in the region to fill.
3226          (if start (progn (beginning-of-line) (point))
3227            (save-excursion
3228              (while (and (zerop (forward-line -1))
3229                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
3230              ;; We may have gone to far.  Go forward again.
3231              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
3232                  (forward-line 1))
3233              (point)))
3234          ;; Find the beginning of the first line past the region to fill.
3235          (save-excursion
3236            (while (progn (forward-line 1)
3237                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
3238            (point)))
3239         ;; Remove existing hashes
3240         (goto-char (point-min))
3241         (while (progn (forward-line 1) (< (point) (point-max)))
3242           (skip-chars-forward " \t")
3243           (and (looking-at "#+") 
3244                (delete-char (- (match-end 0) (match-beginning 0)))))
3245
3246         ;; Lines with only hashes on them can be paragraph boundaries.
3247         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
3248               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
3249               (fill-prefix comment-fill-prefix))
3250           (fill-paragraph justify)))
3251       (if (and start)
3252           (progn 
3253             (goto-char start)
3254             (if (> dc 0)
3255               (progn (delete-char dc) (insert spaces)))
3256             (if (or (= (current-column) c) iteration) nil
3257               (setq comment-column c)
3258               (indent-for-comment)
3259               ;; Repeat once more, flagging as iteration
3260               (cperl-fill-paragraph justify t)))))))
3261
3262 (defun cperl-do-auto-fill ()
3263   ;; Break out if the line is short enough
3264   (if (> (save-excursion
3265            (end-of-line)
3266            (current-column))
3267          fill-column)
3268   (let ((c (save-excursion (beginning-of-line)
3269                            (cperl-to-comment-or-eol) (point)))
3270         (s (memq (following-char) '(?\ ?\t))) marker)
3271     (if (>= c (point)) nil
3272       (setq marker (point-marker))
3273       (cperl-fill-paragraph)
3274       (goto-char marker)
3275       ;; Is not enough, sometimes marker is a start of line
3276       (if (bolp) (progn (re-search-forward "#+[ \t]*") 
3277                         (goto-char (match-end 0))))
3278       ;; Following space could have gone:
3279       (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
3280         (insert " ")
3281         (backward-char 1))
3282       ;; Previous space could have gone:
3283       (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
3284
3285 (defvar imenu-example--function-name-regexp-perl
3286   (concat 
3287    "^\\("
3288        "[ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*\\(([^()]*)[ \t]*\\)?"
3289      "\\|"
3290        "=head\\([12]\\)[ \t]+\\([^\n]+\\)$"
3291    "\\)"))
3292
3293 (defun cperl-imenu-addback (lst &optional isback name)
3294   ;; We suppose that the lst is a DAG, unless the first element only
3295   ;; loops back, and ISBACK is set. Thus this function cannot be
3296   ;; applied twice without ISBACK set.
3297   (cond ((not cperl-imenu-addback) lst)
3298         (t
3299          (or name 
3300              (setq name "+++BACK+++"))
3301          (mapcar (function (lambda (elt)
3302                              (if (and (listp elt) (listp (cdr elt)))
3303                                  (progn
3304                                    ;; In the other order it goes up
3305                                    ;; one level only ;-(
3306                                    (setcdr elt (cons (cons name lst)
3307                                                      (cdr elt)))
3308                                    (cperl-imenu-addback (cdr elt) t name)
3309                                    ))))
3310                  (if isback (cdr lst) lst))
3311          lst)))
3312
3313 (defun imenu-example--create-perl-index (&optional regexp)
3314   (require 'cl)
3315   (require 'imenu)                      ; May be called from TAGS creator
3316   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '()) 
3317         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
3318         (index-meth-alist '()) meth
3319         packages ends-ranges p
3320         (prev-pos 0) char fchar index index1 name (end-range 0) package)
3321     (goto-char (point-min))
3322     (imenu-progress-message prev-pos 0)
3323     ;; Search for the function
3324     (progn ;;save-match-data
3325       (while (re-search-forward
3326               (or regexp imenu-example--function-name-regexp-perl)
3327               nil t)
3328         (imenu-progress-message prev-pos)
3329         ;;(backward-up-list 1)
3330         (cond
3331          ((and                          ; Skip some noise if building tags
3332            (match-beginning 2)          ; package or sub
3333            (eq (char-after (match-beginning 2)) ?p) ; package
3334            (not (save-match-data
3335                   (looking-at "[ \t\n]*;"))))  ; Plain text word 'package'
3336           nil)
3337          ((and
3338            (match-beginning 2)          ; package or sub
3339            ;; Skip if quoted (will not skip multi-line ''-comments :-():
3340            (null (get-text-property (match-beginning 1) 'syntax-table))
3341            (null (get-text-property (match-beginning 1) 'syntax-type))
3342            (null (get-text-property (match-beginning 1) 'in-pod)))
3343           (save-excursion
3344             (goto-char (match-beginning 2))
3345             (setq fchar (following-char))
3346             )
3347           ;; (if (looking-at "([^()]*)[ \t\n\f]*")
3348           ;;    (goto-char (match-end 0)))      ; Messes what follows
3349           (setq char (following-char) 
3350                 meth nil
3351                 p (point))
3352           (while (and ends-ranges (>= p (car ends-ranges)))
3353             ;; delete obsolete entries
3354             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
3355           (setq package (or (car packages) "")
3356                 end-range (or (car ends-ranges) 0))
3357           (if (eq fchar ?p)
3358               (setq name (buffer-substring (match-beginning 3) (match-end 3))
3359                     name (progn
3360                            (set-text-properties 0 (length name) nil name)
3361                            name)
3362                     package (concat name "::") 
3363                     name (concat "package " name)
3364                     end-range 
3365                     (save-excursion
3366                       (parse-partial-sexp (point) (point-max) -1) (point))
3367                     ends-ranges (cons end-range ends-ranges)
3368                     packages (cons package packages)))
3369           ;;   )
3370           ;; Skip this function name if it is a prototype declaration.
3371           (if (and (eq fchar ?s) (eq char ?\;)) nil
3372             (setq index (imenu-example--name-and-position))
3373             (if (eq fchar ?p) nil
3374               (setq name (buffer-substring (match-beginning 3) (match-end 3)))
3375               (set-text-properties 0 (length name) nil name)
3376               (cond ((string-match "[:']" name)
3377                      (setq meth t))
3378                     ((> p end-range) nil)
3379                     (t 
3380                      (setq name (concat package name) meth t))))
3381             (setcar index name)
3382             (if (eq fchar ?p) 
3383                 (push index index-pack-alist)
3384               (push index index-alist))
3385             (if meth (push index index-meth-alist))
3386             (push index index-unsorted-alist)))
3387          ((match-beginning 5)           ; Pod section
3388           ;; (beginning-of-line)
3389           (setq index (imenu-example--name-and-position)
3390                 name (buffer-substring (match-beginning 6) (match-end 6)))
3391           (set-text-properties 0 (length name) nil name)
3392           (if (eq (char-after (match-beginning 5)) ?2)
3393               (setq name (concat "   " name)))
3394           (setcar index name)
3395           (setq index1 (cons (concat "=" name) (cdr index)))
3396           (push index index-pod-alist)
3397           (push index1 index-unsorted-alist)))))
3398     (imenu-progress-message prev-pos 100)
3399     (setq index-alist 
3400           (if (default-value 'imenu-sort-function)
3401               (sort index-alist (default-value 'imenu-sort-function))
3402               (nreverse index-alist)))
3403     (and index-pod-alist
3404          (push (cons "+POD headers+..."
3405                      (nreverse index-pod-alist))
3406                index-alist))
3407     (and (or index-pack-alist index-meth-alist)
3408          (let ((lst index-pack-alist) hier-list pack elt group name)
3409            ;; Remove "package ", reverse and uniquify.
3410            (while lst
3411              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
3412              (if (assoc name hier-list) nil
3413                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
3414            (setq lst index-meth-alist)
3415            (while lst
3416              (setq elt (car lst) lst (cdr lst))
3417              (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
3418                     (setq pack (substring (car elt) 0 (match-beginning 0)))
3419                     (if (setq group (assoc pack hier-list)) 
3420                         (if (listp (cdr group))
3421                             ;; Have some functions already
3422                             (setcdr group 
3423                                     (cons (cons (substring 
3424                                                  (car elt)
3425                                                  (+ 2 (match-beginning 0)))
3426                                                 (cdr elt))
3427                                           (cdr group)))
3428                           (setcdr group (list (cons (substring 
3429                                                      (car elt)
3430                                                      (+ 2 (match-beginning 0)))
3431                                                     (cdr elt)))))
3432                       (setq hier-list 
3433                             (cons (cons pack 
3434                                         (list (cons (substring 
3435                                                      (car elt)
3436                                                      (+ 2 (match-beginning 0)))
3437                                                     (cdr elt))))
3438                                   hier-list))))))
3439            (push (cons "+Hierarchy+..."
3440                        hier-list)
3441                  index-alist)))
3442     (and index-pack-alist
3443          (push (cons "+Packages+..."
3444                      (nreverse index-pack-alist))
3445                index-alist))
3446     (and (or index-pack-alist index-pod-alist 
3447              (default-value 'imenu-sort-function))
3448          index-unsorted-alist
3449          (push (cons "+Unsorted List+..."
3450                      (nreverse index-unsorted-alist))
3451                index-alist))
3452     (cperl-imenu-addback index-alist)))
3453
3454 (defvar cperl-compilation-error-regexp-alist 
3455   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
3456   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
3457      2 3))
3458   "Alist that specifies how to match errors in perl output.")
3459
3460 (if (fboundp 'eval-after-load)
3461     (eval-after-load
3462      "mode-compile"
3463      '(setq perl-compilation-error-regexp-alist
3464            cperl-compilation-error-regexp-alist)))
3465
3466
3467 (defvar cperl-faces-init nil)
3468
3469 (defun cperl-windowed-init ()
3470   "Initialization under windowed version."
3471   (add-hook 'font-lock-mode-hook
3472             (function
3473              (lambda ()
3474                (if (or
3475                     (eq major-mode 'perl-mode)
3476                     (eq major-mode 'cperl-mode))
3477                    (progn
3478                      (or cperl-faces-init (cperl-init-faces))))))))
3479
3480 (defvar perl-font-lock-keywords-1 nil
3481   "Additional expressions to highlight in Perl mode. Minimal set.")
3482 (defvar perl-font-lock-keywords nil
3483   "Additional expressions to highlight in Perl mode. Default set.")
3484 (defvar perl-font-lock-keywords-2 nil
3485   "Additional expressions to highlight in Perl mode. Maximal set")
3486
3487 (defun cperl-init-faces ()
3488   (condition-case nil
3489       (progn
3490         (require 'font-lock)
3491         (and (fboundp 'font-lock-fontify-anchored-keywords)
3492              (featurep 'font-lock-extra)
3493              (message "You have an obsolete package `font-lock-extra'. Install `choose-color'."))
3494         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
3495           ;;(defvar cperl-font-lock-enhanced nil
3496           ;;  "Set to be non-nil if font-lock allows active highlights.")
3497           (if (fboundp 'font-lock-fontify-anchored-keywords)
3498               (setq font-lock-anchored t))
3499           (setq 
3500            t-font-lock-keywords
3501            (list
3502             (cons
3503              (concat
3504               "\\(^\\|[^$@%&\\]\\)\\<\\("
3505               (mapconcat
3506                'identity
3507                '("if" "until" "while" "elsif" "else" "unless" "for"
3508                  "foreach" "continue" "exit" "die" "last" "goto" "next"
3509                  "redo" "return" "local" "exec" "sub" "do" "dump" "use"
3510                  "require" "package" "eval" "my" "BEGIN" "END")
3511                "\\|")                   ; Flow control
3512               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
3513                                         ; In what follows we use `type' style
3514                                         ; for overwritable builtins
3515             (list
3516              (concat
3517               "\\(^\\|[^$@%&\\]\\)\\<\\("
3518               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm"
3519               ;; "and" "atan2" "bind" "binmode" "bless" "caller"
3520               ;; "chdir" "chmod" "chown" "chr" "chroot" "close"
3521               ;; "closedir" "cmp" "connect" "continue" "cos" "crypt"
3522               ;; "dbmclose" "dbmopen" "die" "dump" "endgrent"
3523               ;; "endhostent" "endnetent" "endprotoent" "endpwent"
3524               ;; "endservent" "eof" "eq" "exec" "exit" "exp" "fcntl"
3525               ;; "fileno" "flock" "fork" "formline" "ge" "getc"
3526               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr"
3527               ;; "gethostbyname" "gethostent" "getlogin"
3528               ;; "getnetbyaddr" "getnetbyname" "getnetent"
3529               ;; "getpeername" "getpgrp" "getppid" "getpriority"
3530               ;; "getprotobyname" "getprotobynumber" "getprotoent"
3531               ;; "getpwent" "getpwnam" "getpwuid" "getservbyname"
3532               ;; "getservbyport" "getservent" "getsockname"
3533               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int"
3534               ;; "ioctl" "join" "kill" "lc" "lcfirst" "le" "length"
3535               ;; "link" "listen" "localtime" "log" "lstat" "lt"
3536               ;; "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd" "ne"
3537               ;; "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
3538               ;; "quotemeta" "rand" "read" "readdir" "readline"
3539               ;; "readlink" "readpipe" "recv" "ref" "rename" "require"
3540               ;; "reset" "reverse" "rewinddir" "rindex" "rmdir" "seek"
3541               ;; "seekdir" "select" "semctl" "semget" "semop" "send"
3542               ;; "setgrent" "sethostent" "setnetent" "setpgrp"
3543               ;; "setpriority" "setprotoent" "setpwent" "setservent"
3544               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite"
3545               ;; "shutdown" "sin" "sleep" "socket" "socketpair"
3546               ;; "sprintf" "sqrt" "srand" "stat" "substr" "symlink"
3547               ;; "syscall" "sysread" "system" "syswrite" "tell"
3548               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst"
3549               ;; "umask" "unlink" "unpack" "utime" "values" "vec"
3550               ;; "wait" "waitpid" "wantarray" "warn" "write" "x" "xor"
3551               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|" 
3552               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
3553               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
3554               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
3555               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
3556               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
3557               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
3558               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
3559               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
3560               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
3561               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
3562               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
3563               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
3564               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
3565               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
3566               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
3567               "\\(\\|ngth\\)\\|o\\(caltime\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
3568               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
3569               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
3570               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
3571               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
3572               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
3573               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
3574               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
3575               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
3576               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|tem\\|write\\)\\|"
3577               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
3578               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
3579               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
3580               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
3581               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\|PACKAGE__\\)"
3582               "\\)\\>") 2 'font-lock-type-face)
3583             ;; In what follows we use `other' style
3584             ;; for nonoverwritable builtins
3585             ;; Somehow 's', 'm' are not auto-generated???
3586             (list
3587              (concat
3588               "\\(^\\|[^$@%&\\]\\)\\<\\("
3589               ;; "AUTOLOAD" "BEGIN" "DESTROY" "END" "__END__" "chomp"
3590               ;; "chop" "defined" "delete" "do" "each" "else" "elsif"
3591               ;; "eval" "exists" "for" "foreach" "format" "goto"
3592               ;; "grep" "if" "keys" "last" "local" "map" "my" "next"
3593               ;; "no" "package" "pop" "pos" "print" "printf" "push"
3594               ;; "q" "qq" "qw" "qx" "redo" "return" "scalar" "shift"
3595               ;; "sort" "splice" "split" "study" "sub" "tie" "tr"
3596               ;; "undef" "unless" "unshift" "untie" "until" "use"
3597               ;; "while" "y"
3598               "AUTOLOAD\\|BEGIN\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
3599               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
3600               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|if\\|keys\\|"
3601               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|"
3602               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
3603               "q\\(\\|q\\|w\\|x\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
3604               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
3605               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
3606               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
3607               "\\|[sm]"                 ; Added manually
3608               "\\)\\>") 2 'font-lock-other-type-face)
3609             ;;          (mapconcat 'identity
3610             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
3611             ;;                       "#include" "#define" "#undef")
3612             ;;                     "\\|")
3613             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
3614               font-lock-function-name-face keep) ; Not very good, triggers at "[a-z]"
3615             '("\\<sub[ \t]+\\([^ \t{;]+\\)[ \t]*\\(([^()]*)[ \t]*\\)?[#{\n]" 1
3616               font-lock-function-name-face)
3617             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
3618               2 font-lock-function-name-face)
3619             '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
3620               1 font-lock-function-name-face)
3621             (cond ((featurep 'font-lock-extra)
3622                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}" 
3623                      (2 font-lock-string-face t)
3624                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
3625                   (font-lock-anchored
3626                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
3627                      (2 font-lock-string-face t)
3628                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
3629                       nil nil
3630                       (1 font-lock-string-face t))))
3631                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
3632                        2 font-lock-string-face t)))
3633             '("[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
3634               font-lock-string-face t)
3635             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1 
3636               font-lock-reference-face) ; labels
3637             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
3638               2 font-lock-reference-face)
3639             (cond ((featurep 'font-lock-extra)
3640                    '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
3641                      (3 font-lock-variable-name-face)
3642                      (4 '(another 4 nil
3643                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
3644                                    (1 font-lock-variable-name-face)
3645                                    (2 '(restart 2 nil) nil t))) 
3646                         nil t)))        ; local variables, multiple
3647                   (font-lock-anchored
3648                    '("^[ \t{}]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
3649                      (3 font-lock-variable-name-face)
3650                      ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)"
3651                       nil nil
3652                       (1 font-lock-variable-name-face))))
3653                   (t '("^[ \t{}]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
3654                        3 font-lock-variable-name-face)))
3655             '("\\<for\\(each\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
3656               2 font-lock-variable-name-face)))
3657           (setq 
3658            t-font-lock-keywords-1
3659            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
3660                 (not cperl-xemacs-p) ; not yet as of XEmacs 19.12
3661                 '(
3662                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
3663                    (if (eq (char-after (match-beginning 2)) ?%)
3664                        font-lock-other-emphasized-face
3665                      font-lock-emphasized-face)
3666                    t)                   ; arrays and hashes
3667                   ("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
3668                    1
3669                    (if (= (- (match-end 2) (match-beginning 2)) 1) 
3670                        (if (eq (char-after (match-beginning 3)) ?{)
3671                            font-lock-other-emphasized-face
3672                          font-lock-emphasized-face) ; arrays and hashes
3673                      font-lock-variable-name-face) ; Just to put something
3674                    t)
3675                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
3676                        ;;; Too much noise from \s* @s[ and friends
3677                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)" 
3678                   ;;(3 font-lock-function-name-face t t)
3679                   ;;(4
3680                   ;; (if (cperl-slash-is-regexp)
3681                   ;;    font-lock-function-name-face 'default) nil t))
3682                   )))
3683           (setq perl-font-lock-keywords-1 t-font-lock-keywords
3684                 perl-font-lock-keywords perl-font-lock-keywords-1
3685                 perl-font-lock-keywords-2 (append
3686                                            t-font-lock-keywords
3687                                            t-font-lock-keywords-1)))
3688         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
3689         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
3690             (font-lock-require-faces
3691              (list
3692               ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
3693               (list 'font-lock-comment-face
3694                     ["Firebrick"        "OrangeRed"     "DimGray"       "Gray80"]
3695                     nil
3696                     [nil                nil             t               t       t]
3697                     [nil                nil             t               t       t]
3698                     nil)
3699               (list 'font-lock-string-face
3700                     ["RosyBrown"        "LightSalmon"   "Gray50"        "LightGray"]
3701                     nil
3702                     nil
3703                     [nil                nil             t               t       t]
3704                     nil)
3705               (list 'font-lock-keyword-face
3706                     ["Purple"           "LightSteelBlue" "DimGray"      "Gray90"]
3707                     nil
3708                     [nil                nil             t               t       t]
3709                     nil
3710                     nil)
3711               (list 'font-lock-function-name-face
3712                     (vector
3713                      "Blue"             "LightSkyBlue"  "Gray50"        "LightGray"
3714                      (cdr (assq 'background-color ; if mono
3715                                 (frame-parameters))))
3716                     (vector
3717                      nil                nil             nil             nil
3718                      (cdr (assq 'foreground-color ; if mono
3719                                 (frame-parameters))))
3720                     [nil                nil             t               t       t]
3721                     nil
3722                     nil)
3723               (list 'font-lock-variable-name-face
3724                     ["DarkGoldenrod"    "LightGoldenrod" "DimGray"      "Gray90"]
3725                     nil
3726                     [nil                nil             t               t       t]
3727                     [nil                nil             t               t       t]
3728                     nil)
3729               (list 'font-lock-type-face
3730                     ["DarkOliveGreen"   "PaleGreen"     "DimGray"       "Gray80"]
3731                     nil
3732                     [nil                nil             t               t       t]
3733                     nil
3734                     [nil                nil             t               t       t]
3735                     )
3736               (list 'font-lock-reference-face
3737                     ["CadetBlue"        "Aquamarine"    "Gray50"        "LightGray"]
3738                     nil
3739                     [nil                nil             t               t       t]
3740                     nil
3741                     [nil                nil             t               t       t]
3742                     )
3743               (list 'font-lock-other-type-face
3744                     ["chartreuse3"      ("orchid1" "orange")
3745                      nil                "Gray80"]
3746                     [nil                nil             "gray90"]
3747                     [nil                nil             nil             t       t]
3748                     [nil                nil             t               t]
3749                     [nil                nil             t               t       t]
3750                     )
3751               (list 'font-lock-emphasized-face
3752                     ["blue"             "yellow"        nil             "Gray80"]
3753                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
3754                      "gray90"]
3755                     t
3756                     nil
3757                     nil)
3758               (list 'font-lock-other-emphasized-face
3759                     ["red"              "red"           nil             "Gray80"]
3760                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
3761                      "gray90"]
3762                     t
3763                     t
3764                     nil)))
3765           (defvar cperl-guessed-background nil
3766             "Display characteristics as guessed by cperl.")
3767           (or (fboundp 'x-color-defined-p)
3768               (defalias 'x-color-defined-p 
3769                 (cond ((fboundp 'color-defined-p) 'color-defined-p)
3770                       ;; XEmacs >= 19.12
3771                       ((fboundp 'valid-color-name-p) 'valid-color-name-p)
3772                       ;; XEmacs 19.11
3773                       (t 'x-valid-color-name-p))))
3774           (defvar font-lock-reference-face 'font-lock-reference-face)
3775           (defvar font-lock-variable-name-face 'font-lock-variable-name-face)
3776           (or (boundp 'font-lock-type-face)
3777               (defconst font-lock-type-face
3778                 'font-lock-type-face
3779                 "Face to use for data types.")
3780               )
3781           (or (boundp 'font-lock-other-type-face)
3782               (defconst font-lock-other-type-face
3783                 'font-lock-other-type-face
3784                 "Face to use for data types from another group.")
3785               )
3786           (if (not cperl-xemacs-p) nil
3787             (or (boundp 'font-lock-comment-face)
3788                 (defconst font-lock-comment-face
3789                   'font-lock-comment-face
3790                   "Face to use for comments.")
3791                 )
3792             (or (boundp 'font-lock-keyword-face)
3793                 (defconst font-lock-keyword-face
3794                   'font-lock-keyword-face
3795                   "Face to use for keywords.")
3796                 )
3797             (or (boundp 'font-lock-function-name-face)
3798                 (defconst font-lock-function-name-face
3799                   'font-lock-function-name-face
3800                   "Face to use for function names.")
3801                 )
3802             )
3803           ;;(if (featurep 'font-lock)
3804           (if (face-equal font-lock-type-face font-lock-comment-face)
3805               (defconst font-lock-type-face
3806                 'font-lock-type-face
3807                 "Face to use for basic data types.")
3808             )
3809 ;;;       (if (fboundp 'eval-after-load)
3810 ;;;           (eval-after-load "font-lock"
3811 ;;;                            '(if (face-equal font-lock-type-face
3812 ;;;                                             font-lock-comment-face)
3813 ;;;                                 (defconst font-lock-type-face
3814 ;;;                                   'font-lock-type-face
3815 ;;;                                   "Face to use for basic data types.")
3816 ;;;                               )))   ; This does not work :-( Why?!
3817 ;;;                                     ; Workaround: added to font-lock-m-h
3818 ;;;       )
3819           (or (boundp 'font-lock-other-emphasized-face)
3820               (defconst font-lock-other-emphasized-face
3821                 'font-lock-other-emphasized-face
3822                 "Face to use for another type of emphasizing.")
3823               )
3824           (or (boundp 'font-lock-emphasized-face)
3825               (defconst font-lock-emphasized-face
3826                 'font-lock-emphasized-face
3827                 "Face to use for emphasizing.")
3828               )
3829           ;; Here we try to guess background
3830           (let ((background
3831                  (if (boundp 'font-lock-background-mode)
3832                      font-lock-background-mode
3833                    'light)) 
3834                 (face-list (and (fboundp 'face-list) (face-list)))
3835                 is-face)
3836             (fset 'is-face
3837                   (cond ((fboundp 'find-face)
3838                          (symbol-function 'find-face))
3839                         (face-list
3840                          (function (lambda (face) (member face face-list))))
3841                         (t
3842                          (function (lambda (face) (boundp face))))))
3843             (defvar cperl-guessed-background
3844               (if (and (boundp 'font-lock-display-type)
3845                        (eq font-lock-display-type 'grayscale))
3846                   'gray
3847                 background)
3848               "Background as guessed by CPerl mode")
3849             (if (is-face 'font-lock-type-face) nil
3850               (copy-face 'default 'font-lock-type-face)
3851               (cond
3852                ((eq background 'light)
3853                 (set-face-foreground 'font-lock-type-face
3854                                      (if (x-color-defined-p "seagreen")
3855                                          "seagreen"
3856                                        "sea green")))
3857                ((eq background 'dark)
3858                 (set-face-foreground 'font-lock-type-face
3859                                      (if (x-color-defined-p "os2pink")
3860                                          "os2pink"
3861                                        "pink")))
3862                (t
3863                 (set-face-background 'font-lock-type-face "gray90"))))
3864             (if (is-face 'font-lock-other-type-face)
3865                 nil
3866               (copy-face 'font-lock-type-face 'font-lock-other-type-face)
3867               (cond
3868                ((eq background 'light)
3869                 (set-face-foreground 'font-lock-other-type-face
3870                                      (if (x-color-defined-p "chartreuse3")
3871                                          "chartreuse3"
3872                                        "chartreuse")))
3873                ((eq background 'dark)
3874                 (set-face-foreground 'font-lock-other-type-face
3875                                      (if (x-color-defined-p "orchid1")
3876                                          "orchid1"
3877                                        "orange")))))
3878             (if (is-face 'font-lock-other-emphasized-face) nil
3879               (copy-face 'bold-italic 'font-lock-other-emphasized-face)
3880               (cond
3881                ((eq background 'light)
3882                 (set-face-background 'font-lock-other-emphasized-face
3883                                      (if (x-color-defined-p "lightyellow2")
3884                                          "lightyellow2"
3885                                        (if (x-color-defined-p "lightyellow")
3886                                            "lightyellow"
3887                                          "light yellow"))))
3888                ((eq background 'dark)
3889                 (set-face-background 'font-lock-other-emphasized-face
3890                                      (if (x-color-defined-p "navy")
3891                                          "navy"
3892                                        (if (x-color-defined-p "darkgreen")
3893                                            "darkgreen"
3894                                          "dark green"))))
3895                (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
3896             (if (is-face 'font-lock-emphasized-face) nil
3897               (copy-face 'bold 'font-lock-emphasized-face)
3898               (cond
3899                ((eq background 'light)
3900                 (set-face-background 'font-lock-emphasized-face
3901                                      (if (x-color-defined-p "lightyellow2")
3902                                          "lightyellow2"
3903                                        "lightyellow")))
3904                ((eq background 'dark)
3905                 (set-face-background 'font-lock-emphasized-face
3906                                      (if (x-color-defined-p "navy")
3907                                          "navy"
3908                                        (if (x-color-defined-p "darkgreen")
3909                                            "darkgreen"
3910                                          "dark green"))))
3911                (t (set-face-background 'font-lock-emphasized-face "gray90"))))
3912             (if (is-face 'font-lock-variable-name-face) nil
3913               (copy-face 'italic 'font-lock-variable-name-face))
3914             (if (is-face 'font-lock-reference-face) nil
3915               (copy-face 'italic 'font-lock-reference-face))))
3916         (setq cperl-faces-init t))
3917     (error nil)))
3918
3919
3920 (defun cperl-ps-print-init ()
3921   "Initialization of `ps-print' components for faces used in CPerl."
3922   ;; Guard against old versions
3923   (defvar ps-underlined-faces nil)
3924   (defvar ps-bold-faces nil)
3925   (defvar ps-italic-faces nil)
3926   (setq ps-bold-faces
3927         (append '(font-lock-emphasized-face
3928                   font-lock-keyword-face 
3929                   font-lock-variable-name-face 
3930                   font-lock-reference-face 
3931                   font-lock-other-emphasized-face) 
3932                 ps-bold-faces))
3933   (setq ps-italic-faces
3934         (append '(font-lock-other-type-face
3935                   font-lock-reference-face 
3936                   font-lock-other-emphasized-face)
3937                 ps-italic-faces))
3938   (setq ps-underlined-faces
3939         (append '(font-lock-emphasized-face
3940                   font-lock-other-emphasized-face 
3941                   font-lock-other-type-face font-lock-type-face)
3942                 ps-underlined-faces))
3943   (cons 'font-lock-type-face ps-underlined-faces))
3944
3945
3946 (if (cperl-enable-font-lock) (cperl-windowed-init))
3947
3948 (defun cperl-set-style (style)
3949   "Set CPerl-mode variables to use one of several different indentation styles.
3950 The arguments are a string representing the desired style.
3951 Available styles are GNU, K&R, BSD and Whitesmith."
3952   (interactive 
3953    (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
3954                        c-style-alist)))
3955      (list (completing-read "Enter style: " list nil 'insist))))
3956   (let ((style (cdr (assoc style c-style-alist))) setting str sym)
3957     (while style
3958       (setq setting (car style) style (cdr style))
3959       (setq str (symbol-name (car setting)))
3960       (and (string-match "^c-" str)
3961            (setq str (concat "cperl-" (substring str 2)))
3962            (setq sym (intern-soft str))
3963            (boundp sym)
3964            (set sym (cdr setting))))))
3965
3966 (defun cperl-check-syntax ()
3967   (interactive)
3968   (require 'mode-compile)
3969   (let ((perl-dbg-flags "-wc"))
3970     (mode-compile)))
3971
3972 (defun cperl-info-buffer (type)
3973   ;; Returns buffer with documentation. Creates if missing.
3974   ;; If TYPE, this vars buffer.
3975   ;; Special care is taken to not stomp over an existing info buffer
3976   (let* ((bname (if type "*info-perl-var*" "*info-perl*"))
3977          (info (get-buffer bname))
3978          (oldbuf (get-buffer "*info*")))
3979     (if info info
3980       (save-window-excursion
3981         ;; Get Info running
3982         (require 'info)
3983         (cond (oldbuf
3984                (set-buffer oldbuf)
3985                (rename-buffer "*info-perl-tmp*")))
3986         (save-window-excursion
3987           (info))
3988         (Info-find-node cperl-info-page (if type "perlvar" "perlfunc"))
3989         (set-buffer "*info*")
3990         (rename-buffer bname)
3991         (cond (oldbuf
3992                (set-buffer "*info-perl-tmp*")
3993                (rename-buffer "*info*")
3994                (set-buffer bname)))
3995         (make-variable-buffer-local 'window-min-height)
3996         (setq window-min-height 2)
3997         (current-buffer)))))
3998
3999 (defun cperl-word-at-point (&optional p)
4000   ;; Returns the word at point or at P.
4001   (save-excursion
4002     (if p (goto-char p))
4003     (or (cperl-word-at-point-hard)
4004         (progn
4005           (require 'etags)
4006           (funcall (or (and (boundp 'find-tag-default-function)
4007                             find-tag-default-function)
4008                        (get major-mode 'find-tag-default-function)
4009                        ;; XEmacs 19.12 has `find-tag-default-hook'; it is
4010                        ;; automatically used within `find-tag-default':
4011                        'find-tag-default))))))
4012
4013 (defun cperl-info-on-command (command)
4014   "Shows documentation for Perl command in other window.
4015 If perl-info buffer is shown in some frame, uses this frame.
4016 Customized by setting variables `cperl-shrink-wrap-info-frame',
4017 `cperl-max-help-size'."
4018   (interactive 
4019    (let* ((default (cperl-word-at-point))
4020           (read (read-string 
4021                      (format "Find doc for Perl function (default %s): " 
4022                              default))))
4023      (list (if (equal read "") 
4024                    default 
4025                  read))))
4026
4027   (let ((buffer (current-buffer))
4028         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
4029         pos isvar height iniheight frheight buf win fr1 fr2 iniwin not-loner
4030         max-height char-height buf-list)
4031     (if (string-match "^-[a-zA-Z]$" command)
4032         (setq cmd-desc "^-X[ \t\n]"))
4033     (setq isvar (string-match "^[$@%]" command)
4034           buf (cperl-info-buffer isvar)
4035           iniwin (selected-window)
4036           fr1 (window-frame iniwin))
4037     (set-buffer buf)
4038     (beginning-of-buffer)
4039     (or isvar 
4040         (progn (re-search-forward "^-X[ \t\n]")
4041                (forward-line -1)))
4042     (if (re-search-forward cmd-desc nil t)
4043         (progn
4044           ;; Go back to beginning of the group (ex, for qq)
4045           (if (re-search-backward "^[ \t\n\f]")
4046               (forward-line 1))
4047           (beginning-of-line)
4048           ;; Get some of 
4049           (setq pos (point)
4050                 buf-list (list buf "*info-perl-var*" "*info-perl*"))
4051           (while (and (not win) buf-list)
4052             (setq win (get-buffer-window (car buf-list) t))
4053             (setq buf-list (cdr buf-list)))
4054           (or (not win)
4055               (eq (window-buffer win) buf)
4056               (set-window-buffer win buf))
4057           (and win (setq fr2 (window-frame win)))
4058           (if (or (not fr2) (eq fr1 fr2))
4059               (pop-to-buffer buf)
4060             (special-display-popup-frame buf) ; Make it visible
4061             (select-window win))
4062           (goto-char pos)               ; Needed (?!).
4063           ;; Resize
4064           (setq iniheight (window-height)
4065                 frheight (frame-height)
4066                 not-loner (< iniheight (1- frheight))) ; Are not alone
4067           (cond ((if not-loner cperl-max-help-size 
4068                    cperl-shrink-wrap-info-frame)
4069                  (setq height 
4070                        (+ 2 
4071                           (count-lines 
4072                            pos 
4073                            (save-excursion
4074                              (if (re-search-forward
4075                                   "^[ \t][^\n]*\n+\\([^ \t\n\f]\\|\\'\\)" nil t)
4076                                  (match-beginning 0) (point-max)))))
4077                        max-height 
4078                        (if not-loner
4079                            (/ (* (- frheight 3) cperl-max-help-size) 100)
4080                          (setq char-height (frame-char-height))
4081                          ;; Non-functioning under OS/2:
4082                          (if (eq char-height 1) (setq char-height 18))
4083                          ;; Title, menubar, + 2 for slack
4084                          (- (/ (x-display-pixel-height) char-height) 4)
4085                          ))
4086                  (if (> height max-height) (setq height max-height))
4087                  ;;(message "was %s doing %s" iniheight height)
4088                  (if not-loner
4089                      (enlarge-window (- height iniheight))
4090                    (set-frame-height (window-frame win) (1+ height)))))
4091           (set-window-start (selected-window) pos))
4092       (message "No entry for %s found." command))
4093     ;;(pop-to-buffer buffer)
4094     (select-window iniwin)))
4095
4096 (defun cperl-info-on-current-command ()
4097   "Shows documentation for Perl command at point in other window."
4098   (interactive)
4099   (cperl-info-on-command (cperl-word-at-point)))
4100
4101 (defun cperl-imenu-info-imenu-search ()
4102   (if (looking-at "^-X[ \t\n]") nil
4103     (re-search-backward
4104      "^\n\\([-a-zA-Z_]+\\)[ \t\n]")
4105     (forward-line 1)))
4106
4107 (defun cperl-imenu-info-imenu-name ()  
4108   (buffer-substring
4109    (match-beginning 1) (match-end 1)))
4110
4111 (defun cperl-imenu-on-info ()
4112   (interactive)
4113   (let* ((buffer (current-buffer))
4114          imenu-create-index-function
4115          imenu-prev-index-position-function 
4116          imenu-extract-index-name-function 
4117          (index-item (save-restriction
4118                        (save-window-excursion
4119                          (set-buffer (cperl-info-buffer nil))
4120                          (setq imenu-create-index-function 
4121                                'imenu-default-create-index-function
4122                                imenu-prev-index-position-function
4123                                'cperl-imenu-info-imenu-search
4124                                imenu-extract-index-name-function
4125                                'cperl-imenu-info-imenu-name)
4126                          (imenu-choose-buffer-index)))))
4127     (and index-item
4128          (progn
4129            (push-mark)
4130            (pop-to-buffer "*info-perl*")
4131            (cond
4132             ((markerp (cdr index-item))
4133              (goto-char (marker-position (cdr index-item))))
4134             (t
4135              (goto-char (cdr index-item))))
4136            (set-window-start (selected-window) (point))
4137            (pop-to-buffer buffer)))))
4138
4139 (defun cperl-lineup (beg end &optional step minshift)
4140   "Lineup construction in a region.
4141 Beginning of region should be at the start of a construction.
4142 All first occurrences of this construction in the lines that are
4143 partially contained in the region are lined up at the same column.
4144
4145 MINSHIFT is the minimal amount of space to insert before the construction.
4146 STEP is the tabwidth to position constructions.
4147 If STEP is `nil', `cperl-lineup-step' will be used 
4148 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
4149 Will not move the position at the start to the left."
4150   (interactive "r")
4151   (let (search col tcol seen b e)
4152     (save-excursion
4153       (goto-char end)
4154       (end-of-line)
4155       (setq end (point-marker))
4156       (goto-char beg)
4157       (skip-chars-forward " \t\f")
4158       (setq beg (point-marker))
4159       (indent-region beg end nil)
4160       (goto-char beg)
4161       (setq col (current-column))
4162       (if (looking-at "[a-zA-Z0-9_]")
4163           (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
4164               (setq search
4165                     (concat "\\<" 
4166                             (regexp-quote 
4167                              (buffer-substring (match-beginning 0)
4168                                                (match-end 0))) "\\>"))
4169             (error "Cannot line up in a middle of the word"))
4170         (if (looking-at "$")
4171             (error "Cannot line up end of line"))
4172         (setq search (regexp-quote (char-to-string (following-char)))))
4173       (setq step (or step cperl-lineup-step cperl-indent-level))
4174       (or minshift (setq minshift 1))
4175       (while (progn
4176                (beginning-of-line 2)
4177                (and (< (point) end) 
4178                     (re-search-forward search end t)
4179                     (goto-char (match-beginning 0))))
4180         (setq tcol (current-column) seen t)
4181         (if (> tcol col) (setq col tcol)))
4182       (or seen
4183           (error "The construction to line up occurred only once"))
4184       (goto-char beg)
4185       (setq col (+ col minshift))
4186       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
4187       (while 
4188           (progn
4189             (setq e (point))
4190             (skip-chars-backward " \t")
4191             (delete-region (point) e)
4192             (indent-to-column col); (make-string (- col (current-column)) ?\ ))
4193             (beginning-of-line 2) 
4194             (and (< (point) end) 
4195                  (re-search-forward search end t)
4196                  (goto-char (match-beginning 0)))))))) ; No body
4197
4198 (defun cperl-etags (&optional add all files)
4199   "Run etags with appropriate options for Perl files.
4200 If optional argument ALL is `recursive', will process Perl files
4201 in subdirectories too."
4202   (interactive)
4203   (let ((cmd "etags")
4204         (args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\(([^()]*)[ \t]*\\)?\\([{#]\\|$\\)\\)/\\4/"))
4205         res)
4206     (if add (setq args (cons "-a" args)))
4207     (or files (setq files (list buffer-file-name)))
4208     (cond
4209      ((eq all 'recursive)
4210       ;;(error "Not implemented: recursive")
4211       (setq args (append (list "-e" 
4212                                "sub wanted {push @ARGV, $File::Find::name if /\\.[pP][Llm]$/}
4213                                 use File::Find;
4214                                 find(\\&wanted, '.');
4215                                 exec @ARGV;" 
4216                                cmd) args)
4217             cmd "perl"))
4218      (all 
4219       ;;(error "Not implemented: all")
4220       (setq args (append (list "-e" 
4221                                "push @ARGV, <*.PL *.pl *.pm>;
4222                                 exec @ARGV;" 
4223                                cmd) args)
4224             cmd "perl"))
4225      (t
4226       (setq args (append args files))))
4227     (setq res (apply 'call-process cmd nil nil nil args))
4228     (or (eq res 0)
4229         (message "etags returned \"%s\"" res))))
4230
4231 (defun cperl-toggle-auto-newline ()
4232   "Toggle the state of `cperl-auto-newline'."
4233   (interactive)
4234   (setq cperl-auto-newline (not cperl-auto-newline))
4235   (message "Newlines will %sbe auto-inserted now." 
4236            (if cperl-auto-newline "" "not ")))
4237
4238 (defun cperl-toggle-abbrev ()
4239   "Toggle the state of automatic keyword expansion in CPerl mode."
4240   (interactive)
4241   (abbrev-mode (if abbrev-mode 0 1))
4242   (message "Perl control structure will %sbe auto-inserted now." 
4243            (if abbrev-mode "" "not ")))
4244
4245
4246 (defun cperl-toggle-electric ()
4247   "Toggle the state of parentheses doubling in CPerl mode."
4248   (interactive)
4249   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
4250   (message "Parentheses will %sbe auto-doubled now." 
4251            (if (cperl-val 'cperl-electric-parens) "" "not ")))
4252
4253 ;;;; Tags file creation.
4254
4255 (defvar cperl-tmp-buffer " *cperl-tmp*")
4256
4257 (defun cperl-setup-tmp-buf ()
4258   (set-buffer (get-buffer-create cperl-tmp-buffer))
4259   (set-syntax-table cperl-mode-syntax-table)
4260   (buffer-disable-undo)
4261   (auto-fill-mode 0)
4262   (if cperl-use-syntax-table-text-property-for-tags
4263       (progn
4264         (make-variable-buffer-local 'parse-sexp-lookup-properties)
4265         ;; Do not introduce variable if not needed, we check it!
4266         (set 'parse-sexp-lookup-properties t))))
4267
4268 (defun cperl-xsub-scan ()
4269   (require 'cl)
4270   (require 'imenu)
4271   (let ((index-alist '()) 
4272         (prev-pos 0) index index1 name package prefix)
4273     (goto-char (point-min))
4274     (imenu-progress-message prev-pos 0)
4275     ;; Search for the function
4276     (progn ;;save-match-data
4277       (while (re-search-forward
4278               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
4279               nil t)
4280         (imenu-progress-message prev-pos)
4281         (cond
4282          ((match-beginning 2)   ; SECTION
4283           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
4284           (goto-char (match-beginning 0))
4285           (skip-chars-forward " \t")
4286           (forward-char 1)
4287           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
4288               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
4289             (setq prefix nil)))
4290          ((not package) nil)            ; C language section
4291          ((match-beginning 3)           ; XSUB
4292           (goto-char (1+ (match-beginning 3)))
4293           (setq index (imenu-example--name-and-position))
4294           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
4295           (if (and prefix (string-match (concat "^" prefix) name))
4296               (setq name (substring name (length prefix))))
4297           (cond ((string-match "::" name) nil)
4298                 (t
4299                  (setq index1 (cons (concat package "::" name) (cdr index)))
4300                  (push index1 index-alist)))
4301           (setcar index name)
4302           (push index index-alist))
4303          (t                             ; BOOT: section
4304           ;; (beginning-of-line)
4305           (setq index (imenu-example--name-and-position))
4306           (setcar index (concat package "::BOOT:"))
4307           (push index index-alist)))))
4308     (imenu-progress-message prev-pos 100)
4309     ;;(setq index-alist 
4310     ;;      (if (default-value 'imenu-sort-function)
4311     ;;          (sort index-alist (default-value 'imenu-sort-function))
4312     ;;          (nreverse index-alist)))
4313     index-alist))
4314
4315 (defun cperl-find-tags (file xs)
4316   (let (ind (b (get-buffer cperl-tmp-buffer)) lst elt pos ret
4317             (cperl-pod-here-fontify nil))
4318     (save-excursion
4319       (if b (set-buffer b)
4320           (cperl-setup-tmp-buf))
4321       (erase-buffer)
4322       (setq file (car (insert-file-contents file)))
4323       (message "Scanning file %s..." file)
4324       (if cperl-use-syntax-table-text-property-for-tags
4325           (cperl-find-pods-heres))
4326       (if xs
4327           (setq lst (cperl-xsub-scan))
4328         (setq ind (imenu-example--create-perl-index))
4329         (setq lst (cdr (assoc "+Unsorted List+..." ind))))
4330       (setq lst 
4331             (mapcar 
4332              (function 
4333               (lambda (elt)
4334                 (cond ((string-match "^[_a-zA-Z]" (car elt))
4335                        (goto-char (cdr elt))
4336                        (list (car elt) 
4337                              (point) (count-lines 1 (point))
4338                              (buffer-substring (progn
4339                                                  (skip-chars-forward 
4340                                                   ":_a-zA-Z0-9")
4341                                                  (or (eolp) (forward-char 1))
4342                                                  (point))
4343                                                (progn
4344                                                  (beginning-of-line)
4345                                                  (point))))))))
4346                     lst))
4347       (erase-buffer)
4348       (while lst
4349         (setq elt (car lst) lst (cdr lst))
4350         (if elt
4351             (progn
4352               (insert (elt elt 3) 
4353                       127
4354                       (if (string-match "^package " (car elt))
4355                           (substring (car elt) 8)
4356                         (car elt) )
4357                       1
4358                       (number-to-string (elt elt 1))
4359                       ","
4360                       (number-to-string (elt elt 2))
4361                       "\n")
4362               (if (and (string-match "^[_a-zA-Z]+::" (car elt))
4363                        (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
4364                                      (elt elt 3)))
4365                   ;; Need to insert the name without package as well
4366                   (setq lst (cons (cons (substring (elt elt 3) 
4367                                                    (match-beginning 1)
4368                                                    (match-end 1))
4369                                         (cdr elt))
4370                                   lst))))))
4371       (setq pos (point))
4372       (goto-char 1)
4373       (insert "\f\n" file "," (number-to-string (1- pos)) "\n")
4374       (setq ret (buffer-substring 1 (point-max)))
4375       (erase-buffer)
4376       (message "Scanning file %s finished" file)
4377       ret)))
4378
4379 (defun cperl-write-tags (&optional file erase recurse dir inbuffer)
4380   ;; If INBUFFER, do not select buffer, and do not save
4381   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
4382   (require 'etags)
4383   (if file nil
4384     (setq file (if dir default-directory (buffer-file-name)))
4385     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
4386   (let ((tags-file-name "TAGS")
4387         (case-fold-search (eq system-type 'emx))
4388         xs)
4389     (save-excursion
4390       (cond (inbuffer nil)              ; Already there
4391             ((file-exists-p tags-file-name)
4392              (visit-tags-table-buffer tags-file-name))
4393             (t (set-buffer (find-file-noselect tags-file-name))))
4394       (cond
4395        (dir
4396         (cond ((eq erase 'ignore))
4397               (erase
4398                (erase-buffer)
4399                (setq erase 'ignore)))
4400         (let ((files 
4401                (directory-files file t 
4402                                 (if recurse nil cperl-scan-files-regexp)
4403                                 t)))
4404           (mapcar (function (lambda (file)
4405                               (cond
4406                                ((string-match cperl-noscan-files-regexp file)
4407                                 nil)
4408                                ((not (file-directory-p file))
4409                                 (if (string-match cperl-scan-files-regexp file)
4410                                     (cperl-write-tags file erase recurse nil t)))
4411                                ((not recurse) nil)
4412                                (t (cperl-write-tags file erase recurse t t)))))
4413                   files))
4414         )
4415        (t
4416         (setq xs (string-match "\\.xs$" file))
4417         (cond ((eq erase 'ignore) (goto-char (point-max)))
4418               (erase (erase-buffer))
4419               (t
4420                (goto-char 1)
4421                (if (search-forward (concat "\f\n" file ",") nil t)
4422                    (progn
4423                      (search-backward "\f\n")
4424                      (delete-region (point)
4425                                     (save-excursion
4426                                       (forward-char 1)
4427                                       (if (search-forward "\f\n" nil 'toend)
4428                                        (- (point) 2)
4429                                        (point-max)))))
4430                  (goto-char (point-max)))))
4431         (insert (cperl-find-tags file xs))))
4432       (if inbuffer nil          ; Delegate to the caller
4433         (save-buffer 0)         ; No backup
4434         (if (fboundp 'initialize-new-tags-table) ; Do we need something special in XEmacs?
4435             (initialize-new-tags-table))))))
4436
4437 (defvar cperl-tags-hier-regexp-list
4438   (concat 
4439    "^\\("
4440       "\\(package\\)\\>"
4441      "\\|"
4442       "sub\\>[^\n]+::"
4443      "\\|"
4444       "[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::" ; XSUB?
4445      "\\|"
4446       "[ \t]*BOOT:\C-?[^\n]+::"         ; BOOT section
4447    "\\)"))
4448
4449 (defvar cperl-hierarchy '(() ())
4450   "Global hierarchy of classes")
4451
4452 (defun cperl-tags-hier-fill ()
4453   ;; Suppose we are in a tag table cooked by cperl.
4454   (goto-char 1)
4455   (let (type pack name pos line chunk ord cons1 file str info fileind)
4456     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
4457       (setq pos (match-beginning 0) 
4458             pack (match-beginning 2))
4459       (beginning-of-line)
4460       (if (looking-at (concat
4461                        "\\([^\n]+\\)"
4462                        "\C-?"
4463                        "\\([^\n]+\\)"
4464                        "\C-a"
4465                        "\\([0-9]+\\)"
4466                        ","
4467                        "\\([0-9]+\\)"))
4468           (progn
4469             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
4470                   name (buffer-substring (match-beginning 2) (match-end 2))
4471                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
4472                   line (buffer-substring (match-beginning 4) (match-end 4))
4473                   ord (if pack 1 0)
4474                   info (etags-snarf-tag) ; Moves to beginning of the next line
4475                   file (file-of-tag)
4476                   fileind (format "%s:%s" file line))
4477             ;; Move back
4478             (forward-char -1)
4479             ;; Make new member of hierarchy name ==> file ==> pos if needed
4480             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
4481                 ;; Name known
4482                 (setcdr cons1 (cons (cons fileind (vector file info))
4483                                     (cdr cons1)))
4484               ;; First occurrence of the name, start alist
4485               (setq cons1 (cons name (list (cons fileind (vector file info)))))
4486               (if pack 
4487                   (setcar (cdr cperl-hierarchy)
4488                           (cons cons1 (nth 1 cperl-hierarchy)))
4489                 (setcar cperl-hierarchy
4490                         (cons cons1 (car cperl-hierarchy)))))))
4491       (end-of-line))))
4492
4493 (defun cperl-tags-hier-init (&optional update)
4494   "Show hierarchical menu of classes and methods.
4495 Finds info about classes by a scan of loaded TAGS files.
4496 Supposes that the TAGS files contain fully qualified function names.
4497 One may build such TAGS files from CPerl mode menu."
4498   (interactive)
4499   (require 'etags)
4500   (require 'imenu)
4501   (if (or update (null (nth 2 cperl-hierarchy)))
4502       (let (pack name cons1 to l1 l2 l3 l4
4503                  (remover (function (lambda (elt) ; (name (file1...) (file2..))
4504                                       (or (nthcdr 2 elt)
4505                                           ;; Only in one file
4506                                           (setcdr elt (cdr (nth 1 elt))))))))
4507         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
4508         (setq cperl-hierarchy (list l1 l2 l3))
4509         (or tags-table-list
4510             (call-interactively 'visit-tags-table))
4511         (message "Updating list of classes...")
4512         (mapcar 
4513          (function
4514           (lambda (tagsfile)
4515             (set-buffer (get-file-buffer tagsfile))
4516             (cperl-tags-hier-fill)))
4517          tags-table-list)
4518         (mapcar remover (car cperl-hierarchy))
4519         (mapcar remover (nth 1 cperl-hierarchy))
4520         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
4521                        (cons "Methods: " (car cperl-hierarchy))))
4522         (cperl-tags-treeify to 1)
4523         (setcar (nthcdr 2 cperl-hierarchy)
4524                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
4525         (message "Updating list of classes: done, requesting display...")
4526         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
4527         ))
4528   (or (nth 2 cperl-hierarchy)
4529       (error "No items found"))
4530   (setq update
4531 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
4532         (if window-system
4533             (x-popup-menu t (nth 2 cperl-hierarchy))
4534           (require 'tmm)
4535           (tmm-prompt (nth 2 cperl-hierarchy))))
4536   (if (and update (listp update))
4537       (progn (while (cdr update) (setq update (cdr update)))
4538              (setq update (car update)))) ; Get the last from the list
4539   (if (vectorp update) 
4540       (progn
4541         (find-file (elt update 0))
4542         (etags-goto-tag-location (elt update 1))))
4543   (if (eq update -999) (cperl-tags-hier-init t)))
4544
4545 (defun cperl-tags-treeify (to level)
4546   ;; cadr of `to' is read-write. On start it is a cons
4547   (let* ((regexp (concat "^\\(" (mapconcat 
4548                                  'identity
4549                                  (make-list level "[_a-zA-Z0-9]+")
4550                                  "::")
4551                          "\\)\\(::\\)?"))
4552          (packages (cdr (nth 1 to)))
4553          (methods (cdr (nth 2 to)))
4554          l1 head tail cons1 cons2 ord writeto packs recurse
4555          root-packages root-functions ms many_ms same_name ps
4556          (move-deeper
4557           (function 
4558            (lambda (elt)
4559              (cond ((and (string-match regexp (car elt))
4560                          (or (eq ord 1) (match-end 2)))
4561                     (setq head (substring (car elt) 0 (match-end 1))
4562                           tail (if (match-end 2) (substring (car elt) 
4563                                                             (match-end 2)))
4564                           recurse t)
4565                     (if (setq cons1 (assoc head writeto)) nil
4566                       ;; Need to init new head
4567                       (setcdr writeto (cons (list head (list "Packages: ")
4568                                                   (list "Methods: "))
4569                                             (cdr writeto)))
4570                       (setq cons1 (nth 1 writeto)))
4571                     (setq cons2 (nth ord cons1)) ; Either packs or meths
4572                     (setcdr cons2 (cons elt (cdr cons2))))
4573                    ((eq ord 2)
4574                     (setq root-functions (cons elt root-functions)))
4575                    (t
4576                     (setq root-packages (cons elt root-packages))))))))
4577     (setcdr to l1)                      ; Init to dynamic space
4578     (setq writeto to)
4579     (setq ord 1)
4580     (mapcar move-deeper packages)
4581     (setq ord 2)
4582     (mapcar move-deeper methods)
4583     (if recurse
4584         (mapcar (function (lambda (elt)
4585                           (cperl-tags-treeify elt (1+ level))))
4586                 (cdr to)))
4587     ;;Now clean up leaders with one child only
4588     (mapcar (function (lambda (elt)
4589                         (if (not (and (listp (cdr elt)) 
4590                                       (eq (length elt) 2))) nil
4591                             (setcar elt (car (nth 1 elt)))
4592                             (setcdr elt (cdr (nth 1 elt))))))
4593             (cdr to))
4594     ;; Sort the roots of subtrees
4595     (if (default-value 'imenu-sort-function)
4596         (setcdr to
4597                 (sort (cdr to) (default-value 'imenu-sort-function))))
4598     ;; Now add back functions removed from display
4599     (mapcar (function (lambda (elt)
4600                         (setcdr to (cons elt (cdr to)))))
4601             (if (default-value 'imenu-sort-function)
4602                 (nreverse
4603                  (sort root-functions (default-value 'imenu-sort-function)))
4604               root-functions))
4605     ;; Now add back packages removed from display
4606     (mapcar (function (lambda (elt)
4607                         (setcdr to (cons (cons (concat "package " (car elt)) 
4608                                                (cdr elt)) 
4609                                          (cdr to)))))
4610             (if (default-value 'imenu-sort-function)
4611                 (nreverse 
4612                  (sort root-packages (default-value 'imenu-sort-function)))
4613               root-packages))
4614     ))
4615
4616 ;;;(x-popup-menu t
4617 ;;;   '(keymap "Name1" 
4618 ;;;         ("Ret1" "aa")
4619 ;;;         ("Head1" "ab"  
4620 ;;;          keymap "Name2" 
4621 ;;;          ("Tail1" "x") ("Tail2" "y"))))
4622
4623 (defun cperl-list-fold (list name limit)
4624   (let (list1 list2 elt1 (num 0))
4625     (if (<= (length list) limit) list
4626       (setq list1 nil list2 nil)
4627       (while list
4628         (setq num (1+ num) 
4629               elt1 (car list)
4630               list (cdr list))
4631         (if (<= num imenu-max-items)
4632             (setq list2 (cons elt1 list2))
4633           (setq list1 (cons (cons name
4634                                   (nreverse list2))
4635                             list1)
4636                 list2 (list elt1)
4637                 num 1)))
4638       (nreverse (cons (cons name
4639                             (nreverse list2))
4640                       list1)))))
4641
4642 (defun cperl-menu-to-keymap (menu &optional name)
4643   (let (list)
4644     (cons 'keymap 
4645           (mapcar 
4646            (function 
4647             (lambda (elt)
4648               (cond ((listp (cdr elt))
4649                      (setq list (cperl-list-fold
4650                                  (cdr elt) (car elt) imenu-max-items))
4651                      (cons nil
4652                            (cons (car elt)
4653                                  (cperl-menu-to-keymap list))))
4654                     (t
4655                      (list (cdr elt) (car elt) t))))) ; t is needed in 19.34
4656            (cperl-list-fold menu "Root" imenu-max-items)))))
4657
4658 \f
4659 (defvar cperl-bad-style-regexp
4660   (mapconcat 'identity
4661    '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
4662      "[-<>=+^&|]+[^- \t\n=+<>~]"        ; sign+ char
4663      )
4664    "\\|")
4665   "Finds places such that insertion of a whitespace may help a lot.")
4666
4667 (defvar cperl-not-bad-style-regexp 
4668   (mapconcat 'identity
4669    '("[^-\t <>=+]\\(--\\|\\+\\+\\)"     ; var-- var++
4670      "[a-zA-Z0-9_][|&][a-zA-Z0-9_$]"    ; abc|def abc&def are often used.
4671      "&[(a-zA-Z0-9_$]"                  ; &subroutine &(var->field)
4672      "<\\$?\\sw+\\(\\.\\sw+\\)?>"       ; <IN> <stdin.h>
4673      "-[a-zA-Z][ \t]+[_$\"'`]"          ; -f file
4674      "-[0-9]"                           ; -5
4675      "\\+\\+"                           ; ++var
4676      "--"                               ; --var
4677      ".->"                              ; a->b
4678      "->"                               ; a SPACE ->b
4679      "\\[-"                             ; a[-1]
4680      "^="                               ; =head
4681      "||"
4682      "&&"
4683      "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
4684      "-[a-zA-Z_0-9]+[ \t]*=>"                   ; -option => value
4685      ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
4686      ;;"[*/+-|&<.]+="
4687      )
4688    "\\|")
4689   "If matches at the start of match found by `my-bad-c-style-regexp',
4690 insertion of a whitespace will not help.")
4691
4692 (defvar found-bad)
4693
4694 (defun cperl-find-bad-style ()
4695   "Find places in the buffer where insertion of a whitespace may help.
4696 Prompts user for insertion of spaces.
4697 Currently it is tuned to C and Perl syntax."
4698   (interactive)
4699   (let (found-bad (p (point)))
4700     (setq last-nonmenu-event 13)        ; To disable popup
4701     (beginning-of-buffer)
4702     (map-y-or-n-p "Insert space here? "
4703                   (function (lambda (arg) (insert " ")))
4704                   'cperl-next-bad-style
4705                   '("location" "locations" "insert a space into") 
4706                   '((?\C-r (lambda (arg)
4707                              (let ((buffer-quit-function
4708                                     'exit-recursive-edit))
4709                                (message "Exit with Esc Esc")
4710                                (recursive-edit)
4711                                t))      ; Consider acted upon
4712                            "edit, exit with Esc Esc") 
4713                     (?e (lambda (arg)
4714                           (let ((buffer-quit-function
4715                                  'exit-recursive-edit))
4716                             (message "Exit with Esc Esc")
4717                             (recursive-edit)
4718                             t))         ; Consider acted upon
4719                         "edit, exit with Esc Esc"))
4720                   t)
4721     (if found-bad (goto-char found-bad)
4722       (goto-char p)
4723       (message "No appropriate place found"))))
4724
4725 (defun cperl-next-bad-style ()
4726   (let (p (not-found t) (point (point)) found)
4727     (while (and not-found
4728                 (re-search-forward cperl-bad-style-regexp nil 'to-end))
4729       (setq p (point))
4730       (goto-char (match-beginning 0))
4731       (if (or
4732            (looking-at cperl-not-bad-style-regexp)
4733            ;; Check for a < -b and friends
4734            (and (eq (following-char) ?\-)
4735                 (save-excursion
4736                   (skip-chars-backward " \t\n")
4737                   (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\(, ?\[, ?\{))))
4738            ;; Now check for syntax type
4739            (save-match-data
4740              (setq found (point))
4741              (beginning-of-defun)
4742              (let ((pps (parse-partial-sexp (point) found)))
4743                (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
4744           (goto-char (match-end 0))
4745         (goto-char (1- p))
4746         (setq not-found nil
4747               found-bad found)))
4748     (not not-found)))
4749
4750 \ 6
4751 ;;; Getting help
4752 (defvar cperl-have-help-regexp 
4753   ;;(concat "\\("
4754   (mapconcat
4755    'identity
4756    '("[$@%*&][0-9a-zA-Z_:]+\\([ \t]*[[{]\\)?"           ; Usual variable
4757      "[$@]\\^[a-zA-Z]"                  ; Special variable
4758      "[$@][^ \n\t]"                     ; Special variable
4759      "-[a-zA-Z]"                        ; File test
4760      "\\\\[a-zA-Z0]"                    ; Special chars
4761      "^=[a-z][a-zA-Z0-9_]*"             ; Pod sections
4762      "[-!&*+,-./<=>?\\\\^|~]+"          ; Operator
4763      "[a-zA-Z_0-9:]+"                   ; symbol or number
4764      "x="
4765      "#!"
4766      )
4767    ;;"\\)\\|\\("
4768    "\\|"
4769    )
4770           ;;"\\)"
4771           ;;)
4772   "Matches places in the buffer we can find help for.")
4773
4774 (defvar cperl-message-on-help-error t)
4775 (defvar cperl-help-from-timer nil)
4776
4777 (defun cperl-word-at-point-hard ()
4778   ;; Does not save-excursion
4779   ;; Get to the something meaningful
4780   (or (eobp) (eolp) (forward-char 1))
4781   (re-search-backward "[-a-zA-Z0-9_:!&*+,-./<=>?\\\\^|~$%@]" 
4782                       (save-excursion (beginning-of-line) (point))
4783                       'to-beg)
4784   ;;  (cond
4785   ;;   ((or (eobp) (looking-at "[][ \t\n{}();,]")) ; Not at a symbol
4786   ;;    (skip-chars-backward " \n\t\r({[]});,")
4787   ;;    (or (bobp) (backward-char 1))))
4788   ;; Try to backtrace
4789   (cond
4790    ((looking-at "[a-zA-Z0-9_:]")        ; symbol
4791     (skip-chars-backward "a-zA-Z0-9_:")
4792     (cond 
4793      ((and (eq (preceding-char) ?^)     ; $^I
4794            (eq (char-after (- (point) 2)) ?\$))
4795       (forward-char -2))
4796      ((memq (preceding-char) (append "*$@%&\\" nil)) ; *glob
4797       (forward-char -1))
4798      ((and (eq (preceding-char) ?\=)
4799            (eq (current-column) 1))
4800       (forward-char -1)))               ; =head1
4801     (if (and (eq (preceding-char) ?\<)
4802              (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <FH>
4803         (forward-char -1)))
4804    ((and (looking-at "=") (eq (preceding-char) ?x)) ; x=
4805     (forward-char -1))
4806    ((and (looking-at "\\^") (eq (preceding-char) ?\$)) ; $^I
4807     (forward-char -1))
4808    ((looking-at "[-!&*+,-./<=>?\\\\^|~]")
4809     (skip-chars-backward "-!&*+,-./<=>?\\\\^|~")
4810     (cond
4811      ((and (eq (preceding-char) ?\$)
4812            (not (eq (char-after (- (point) 2)) ?\$))) ; $-
4813       (forward-char -1))
4814      ((and (eq (following-char) ?\>)
4815            (string-match "[a-zA-Z0-9_]" (char-to-string (preceding-char)))
4816            (save-excursion
4817              (forward-sexp -1)
4818              (and (eq (preceding-char) ?\<)
4819                   (looking-at "\\$?[a-zA-Z0-9_:]+>")))) ; <FH>
4820       (search-backward "<"))))
4821    ((and (eq (following-char) ?\$)
4822          (eq (preceding-char) ?\<)
4823          (looking-at "\\$?[a-zA-Z0-9_:]+>")) ; <$fh>
4824     (forward-char -1)))
4825   (if (looking-at cperl-have-help-regexp)
4826       (buffer-substring (match-beginning 0) (match-end 0))))
4827
4828 (defun cperl-get-help ()
4829   "Get one-line docs on the symbol at the point.
4830 The data for these docs is a little bit obsolete and may be in fact longer
4831 than a line. Your contribution to update/shorten it is appreciated."
4832   (interactive)
4833   (save-match-data                      ; May be called "inside" query-replace
4834     (save-excursion
4835       (let ((word (cperl-word-at-point-hard)))
4836         (if word
4837             (if (and cperl-help-from-timer ; Bail out if not in mainland
4838                      (not (string-match "^#!\\|\\\\\\|^=" word)) ; Show help even in comments/strings.
4839                      (or (memq (get-text-property (point) 'face)
4840                                '(font-lock-comment-face font-lock-string-face))
4841                          (memq (get-text-property (point) 'syntax-type)
4842                                '(pod here-doc format))))
4843                 nil
4844               (cperl-describe-perl-symbol word))
4845           (if cperl-message-on-help-error
4846               (message "Nothing found for %s..." 
4847                        (buffer-substring (point) (min (+ 5 (point)) (point-max))))))))))
4848
4849 ;;; Stolen from perl-descr.el by Johan Vromans:
4850
4851 (defvar cperl-doc-buffer " *perl-doc*"
4852   "Where the documentation can be found.")
4853
4854 (defun cperl-describe-perl-symbol (val)
4855   "Display the documentation of symbol at point, a Perl operator."
4856   (let ((enable-recursive-minibuffers t)
4857         args-file regexp)
4858     (cond
4859         ((string-match "^[&*][a-zA-Z_]" val)
4860          (setq val (concat (substring val 0 1) "NAME")))
4861         ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*\\[" val)
4862          (setq val (concat "@" (substring val 1 (match-end 1)))))
4863         ((string-match "^[$@]\\([a-zA-Z_:0-9]+\\)[ \t]*{" val)
4864          (setq val (concat "%" (substring val 1 (match-end 1)))))
4865         ((and (string= val "x") (string-match "^x=" val))
4866          (setq val "x="))
4867         ((string-match "^\\$[\C-a-\C-z]" val)
4868          (setq val (concat "$^" (char-to-string (+ ?A -1 (aref val 1))))))
4869         ((string-match "^CORE::" val)
4870          (setq val "CORE::"))
4871         ((string-match "^SUPER::" val)
4872          (setq val "SUPER::"))
4873         ((and (string= "<" val) (string-match "^<\\$?[a-zA-Z0-9_:]+>" val))
4874          (setq val "<NAME>")))
4875     (setq regexp (concat "^" 
4876                          "\\([^a-zA-Z0-9_:]+[ \t]+\\)?"
4877                          (regexp-quote val) 
4878                          "\\([ \t([/]\\|$\\)"))
4879
4880     ;; get the buffer with the documentation text
4881     (cperl-switch-to-doc-buffer)
4882
4883     ;; lookup in the doc
4884     (goto-char (point-min))
4885     (let ((case-fold-search nil))
4886       (list 
4887        (if (re-search-forward regexp (point-max) t)
4888            (save-excursion
4889              (beginning-of-line 1)
4890              (let ((lnstart (point)))
4891                (end-of-line)
4892                (message "%s" (buffer-substring lnstart (point)))))
4893          (if cperl-message-on-help-error
4894              (message "No definition for %s" val)))))))
4895
4896 (defvar cperl-short-docs "Ignore my value"
4897   ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl)
4898   "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5]
4899 ! ...   Logical negation.       
4900 ... != ...      Numeric inequality.
4901 ... !~ ...      Search pattern, substitution, or translation (negated).
4902 $!      In numeric context: errno. In a string context: error string.
4903 $\"     The separator which joins elements of arrays interpolated in strings.
4904 $#      The output format for printed numbers. Initial value is %.20g.
4905 $$      Process number of this script. Changes in the fork()ed child process.
4906 $%      The current page number of the currently selected output channel.
4907
4908         The following variables are always local to the current block:
4909
4910 $1      Match of the 1st set of parentheses in the last match (auto-local).
4911 $2      Match of the 2nd set of parentheses in the last match (auto-local).
4912 $3      Match of the 3rd set of parentheses in the last match (auto-local).
4913 $4      Match of the 4th set of parentheses in the last match (auto-local).
4914 $5      Match of the 5th set of parentheses in the last match (auto-local).
4915 $6      Match of the 6th set of parentheses in the last match (auto-local).
4916 $7      Match of the 7th set of parentheses in the last match (auto-local).
4917 $8      Match of the 8th set of parentheses in the last match (auto-local).
4918 $9      Match of the 9th set of parentheses in the last match (auto-local).
4919 $&      The string matched by the last pattern match (auto-local).
4920 $'      The string after what was matched by the last match (auto-local).
4921 $`      The string before what was matched by the last match (auto-local).
4922
4923 $(      The real gid of this process.
4924 $)      The effective gid of this process.
4925 $*      Deprecated: Set to 1 to do multiline matching within a string.
4926 $+      The last bracket matched by the last search pattern.
4927 $,      The output field separator for the print operator.
4928 $-      The number of lines left on the page.
4929 $.      The current input line number of the last filehandle that was read.
4930 $/      The input record separator, newline by default.
4931 $0      Name of the file containing the perl script being executed. May be set.
4932 $:     String may be broken after these characters to fill ^-lines in a format.
4933 $;      Subscript separator for multi-dim array emulation. Default \"\\034\".
4934 $<      The real uid of this process.
4935 $=      The page length of the current output channel. Default is 60 lines.
4936 $>      The effective uid of this process.
4937 $?      The status returned by the last ``, pipe close or `system'.
4938 $@      The perl error message from the last eval or do @var{EXPR} command.
4939 $ARGV   The name of the current file used with <> .
4940 $[      Deprecated: The index of the first element/char in an array/string.
4941 $\\     The output record separator for the print operator.
4942 $]      The perl version string as displayed with perl -v.
4943 $^      The name of the current top-of-page format.
4944 $^A     The current value of the write() accumulator for format() lines.
4945 $^D     The value of the perl debug (-D) flags.
4946 $^E     Information about the last system error other than that provided by $!.
4947 $^F     The highest system file descriptor, ordinarily 2.
4948 $^H     The current set of syntax checks enabled by `use strict'.
4949 $^I     The value of the in-place edit extension (perl -i option).
4950 $^L     What formats output to perform a formfeed. Default is \f.
4951 $^O     The operating system name under which this copy of Perl was built.
4952 $^P     Internal debugging flag.
4953 $^T     The time the script was started. Used by -A/-M/-C file tests.
4954 $^W     True if warnings are requested (perl -w flag).
4955 $^X     The name under which perl was invoked (argv[0] in C-speech).
4956 $_      The default input and pattern-searching space.
4957 $|      Auto-flush after write/print on the current output channel? Default 0. 
4958 $~      The name of the current report format.
4959 ... % ...       Modulo division.
4960 ... %= ...      Modulo division assignment.
4961 %ENV    Contains the current environment.
4962 %INC    List of files that have been require-d or do-ne.
4963 %SIG    Used to set signal handlers for various signals.
4964 ... & ...       Bitwise and.
4965 ... && ...      Logical and.
4966 ... &&= ...     Logical and assignment.
4967 ... &= ...      Bitwise and assignment.
4968 ... * ...       Multiplication.
4969 ... ** ...      Exponentiation.
4970 *NAME   Glob: all objects refered by NAME. *NAM1 = *NAM2 aliases NAM1 to NAM2.
4971 &NAME(arg0, ...)        Subroutine call. Arguments go to @_.
4972 ... + ...       Addition.               +EXPR   Makes EXPR into scalar context.
4973 ++      Auto-increment (magical on strings).    ++EXPR  EXPR++
4974 ... += ...      Addition assignment.
4975 ,       Comma operator.
4976 ... - ...       Subtraction.
4977 --      Auto-decrement (NOT magical on strings).        --EXPR  EXPR--
4978 ... -= ...      Subtraction assignment.
4979 -A      Access time in days since script started.
4980 -B      File is a non-text (binary) file.
4981 -C      Inode change time in days since script started.
4982 -M      Age in days since script started.
4983 -O      File is owned by real uid.
4984 -R      File is readable by real uid.
4985 -S      File is a socket .
4986 -T      File is a text file.
4987 -W      File is writable by real uid.
4988 -X      File is executable by real uid.
4989 -b      File is a block special file.
4990 -c      File is a character special file.
4991 -d      File is a directory.
4992 -e      File exists .
4993 -f      File is a plain file.
4994 -g      File has setgid bit set.
4995 -k      File has sticky bit set.
4996 -l      File is a symbolic link.
4997 -o      File is owned by effective uid.
4998 -p      File is a named pipe (FIFO).
4999 -r      File is readable by effective uid.
5000 -s      File has non-zero size.
5001 -t      Tests if filehandle (STDIN by default) is opened to a tty.
5002 -u      File has setuid bit set.
5003 -w      File is writable by effective uid.
5004 -x      File is executable by effective uid.
5005 -z      File has zero size.
5006 .       Concatenate strings.
5007 ..      Alternation, also range operator.
5008 .=      Concatenate assignment strings
5009 ... / ...       Division.       /PATTERN/ioxsmg Pattern match
5010 ... /= ...      Division assignment.
5011 /PATTERN/ioxsmg Pattern match.
5012 ... < ...       Numeric less than.      <pattern>       Glob.   See <NAME>, <> as well.
5013 <NAME>  Reads line from filehandle NAME. NAME must be bareword/dollar-bareword.
5014 <pattern>       Glob. (Unless pattern is bareword/dollar-bareword - see <NAME>)
5015 <>      Reads line from union of files in @ARGV (= command line) and STDIN.
5016 ... << ...      Bitwise shift left.     <<      start of HERE-DOCUMENT.
5017 ... <= ...      Numeric less than or equal to.
5018 ... <=> ...     Numeric compare.
5019 ... = ...       Assignment.
5020 ... == ...      Numeric equality.
5021 ... =~ ...      Search pattern, substitution, or translation
5022 ... > ...       Numeric greater than.
5023 ... >= ...      Numeric greater than or equal to.
5024 ... >> ...      Bitwise shift right.
5025 ... >>= ...     Bitwise shift right assignment.
5026 ... ? ... : ... Condition=if-then-else operator.   ?PAT? One-time pattern match.
5027 ?PATTERN?       One-time pattern match.
5028 @ARGV   Command line arguments (not including the command name - see $0).
5029 @INC    List of places to look for perl scripts during do/include/use.
5030 @_      Parameter array for subroutines. Also used by split unless in array context.
5031 \\  Creates reference to what follows, like \$var, or quotes non-\w in strings.
5032 \\0     Octal char, e.g. \\033.
5033 \\E     Case modification terminator. See \\Q, \\L, and \\U.
5034 \\L     Lowercase until \\E . See also \l, lc.
5035 \\U     Upcase until \\E . See also \u, uc.
5036 \\Q     Quote metacharacters until \\E . See also quotemeta.
5037 \\a     Alarm character (octal 007).
5038 \\b     Backspace character (octal 010).
5039 \\c     Control character, e.g. \\c[ .
5040 \\e     Escape character (octal 033).
5041 \\f     Formfeed character (octal 014).
5042 \\l     Lowercase the next character. See also \\L and \\u, lcfirst.
5043 \\n     Newline character (octal 012 on most systems).
5044 \\r     Return character (octal 015 on most systems).
5045 \\t     Tab character (octal 011).
5046 \\u     Upcase the next character. See also \\U and \\l, ucfirst.
5047 \\x     Hex character, e.g. \\x1b.
5048 ... ^ ...       Bitwise exclusive or.
5049 __END__ Ends program source.
5050 __DATA__        Ends program source.
5051 __FILE__        Current (source) filename.
5052 __LINE__        Current line in current source.
5053 __PACKAGE__     Current package.
5054 ARGV    Default multi-file input filehandle. <ARGV> is a synonym for <>.
5055 ARGVOUT Output filehandle with -i flag.
5056 BEGIN { ... }   Immediately executed (during compilation) piece of code.
5057 END { ... }     Pseudo-subroutine executed after the script finishes.
5058 DATA    Input filehandle for what follows after __END__ or __DATA__.
5059 accept(NEWSOCKET,GENERICSOCKET)
5060 alarm(SECONDS)
5061 atan2(X,Y)
5062 bind(SOCKET,NAME)
5063 binmode(FILEHANDLE)
5064 caller[(LEVEL)]
5065 chdir(EXPR)
5066 chmod(LIST)
5067 chop[(LIST|VAR)]
5068 chown(LIST)
5069 chroot(FILENAME)
5070 close(FILEHANDLE)
5071 closedir(DIRHANDLE)
5072 ... cmp ...     String compare.
5073 connect(SOCKET,NAME)
5074 continue of { block } continue { block }. Is executed after `next' or at end.
5075 cos(EXPR)
5076 crypt(PLAINTEXT,SALT)
5077 dbmclose(%HASH)
5078 dbmopen(%HASH,DBNAME,MODE)
5079 defined(EXPR)
5080 delete($HASH{KEY})
5081 die(LIST)
5082 do { ... }|SUBR while|until EXPR        executes at least once
5083 do(EXPR|SUBR([LIST]))   (with while|until executes at least once)
5084 dump LABEL
5085 each(%HASH)
5086 endgrent
5087 endhostent
5088 endnetent
5089 endprotoent
5090 endpwent
5091 endservent
5092 eof[([FILEHANDLE])]
5093 ... eq ...      String equality.
5094 eval(EXPR) or eval { BLOCK }
5095 exec(LIST)
5096 exit(EXPR)
5097 exp(EXPR)
5098 fcntl(FILEHANDLE,FUNCTION,SCALAR)
5099 fileno(FILEHANDLE)
5100 flock(FILEHANDLE,OPERATION)
5101 for (EXPR;EXPR;EXPR) { ... }
5102 foreach [VAR] (@ARRAY) { ... }
5103 fork
5104 ... ge ...      String greater than or equal.
5105 getc[(FILEHANDLE)]
5106 getgrent
5107 getgrgid(GID)
5108 getgrnam(NAME)
5109 gethostbyaddr(ADDR,ADDRTYPE)
5110 gethostbyname(NAME)
5111 gethostent
5112 getlogin
5113 getnetbyaddr(ADDR,ADDRTYPE)
5114 getnetbyname(NAME)
5115 getnetent
5116 getpeername(SOCKET)
5117 getpgrp(PID)
5118 getppid
5119 getpriority(WHICH,WHO)
5120 getprotobyname(NAME)
5121 getprotobynumber(NUMBER)
5122 getprotoent
5123 getpwent
5124 getpwnam(NAME)
5125 getpwuid(UID)
5126 getservbyname(NAME,PROTO)
5127 getservbyport(PORT,PROTO)
5128 getservent
5129 getsockname(SOCKET)
5130 getsockopt(SOCKET,LEVEL,OPTNAME)
5131 gmtime(EXPR)
5132 goto LABEL
5133 grep(EXPR,LIST)
5134 ... gt ...      String greater than.
5135 hex(EXPR)
5136 if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXPR if EXPR
5137 index(STR,SUBSTR[,OFFSET])
5138 int(EXPR)
5139 ioctl(FILEHANDLE,FUNCTION,SCALAR)
5140 join(EXPR,LIST)
5141 keys(%HASH)
5142 kill(LIST)
5143 last [LABEL]
5144 ... le ...      String less than or equal.
5145 length(EXPR)
5146 link(OLDFILE,NEWFILE)
5147 listen(SOCKET,QUEUESIZE)
5148 local(LIST)
5149 localtime(EXPR)
5150 log(EXPR)
5151 lstat(EXPR|FILEHANDLE|VAR)
5152 ... lt ...      String less than.
5153 m/PATTERN/iogsmx
5154 mkdir(FILENAME,MODE)
5155 msgctl(ID,CMD,ARG)
5156 msgget(KEY,FLAGS)
5157 msgrcv(ID,VAR,SIZE,TYPE.FLAGS)
5158 msgsnd(ID,MSG,FLAGS)
5159 my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, or %HASH).
5160 ... ne ...      String inequality.
5161 next [LABEL]
5162 oct(EXPR)
5163 open(FILEHANDLE[,EXPR])
5164 opendir(DIRHANDLE,EXPR)
5165 ord(EXPR)       ASCII value of the first char of the string.
5166 pack(TEMPLATE,LIST)
5167 package NAME    Introduces package context.
5168 pipe(READHANDLE,WRITEHANDLE)    Create a pair of filehandles on ends of a pipe.
5169 pop(ARRAY)
5170 print [FILEHANDLE] [(LIST)]
5171 printf [FILEHANDLE] (FORMAT,LIST)
5172 push(ARRAY,LIST)
5173 q/STRING/       Synonym for 'STRING'
5174 qq/STRING/      Synonym for \"STRING\"
5175 qx/STRING/      Synonym for `STRING`
5176 rand[(EXPR)]
5177 read(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
5178 readdir(DIRHANDLE)
5179 readlink(EXPR)
5180 recv(SOCKET,SCALAR,LEN,FLAGS)
5181 redo [LABEL]
5182 rename(OLDNAME,NEWNAME)
5183 require [FILENAME | PERL_VERSION]
5184 reset[(EXPR)]
5185 return(LIST)
5186 reverse(LIST)
5187 rewinddir(DIRHANDLE)
5188 rindex(STR,SUBSTR[,OFFSET])
5189 rmdir(FILENAME)
5190 s/PATTERN/REPLACEMENT/gieoxsm
5191 scalar(EXPR)
5192 seek(FILEHANDLE,POSITION,WHENCE)
5193 seekdir(DIRHANDLE,POS)
5194 select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT)
5195 semctl(ID,SEMNUM,CMD,ARG)
5196 semget(KEY,NSEMS,SIZE,FLAGS)
5197 semop(KEY,...)
5198 send(SOCKET,MSG,FLAGS[,TO])
5199 setgrent
5200 sethostent(STAYOPEN)
5201 setnetent(STAYOPEN)
5202 setpgrp(PID,PGRP)
5203 setpriority(WHICH,WHO,PRIORITY)
5204 setprotoent(STAYOPEN)
5205 setpwent
5206 setservent(STAYOPEN)
5207 setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
5208 shift[(ARRAY)]
5209 shmctl(ID,CMD,ARG)
5210 shmget(KEY,SIZE,FLAGS)
5211 shmread(ID,VAR,POS,SIZE)
5212 shmwrite(ID,STRING,POS,SIZE)
5213 shutdown(SOCKET,HOW)
5214 sin(EXPR)
5215 sleep[(EXPR)]
5216 socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
5217 socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
5218 sort [SUBROUTINE] (LIST)
5219 splice(ARRAY,OFFSET[,LENGTH[,LIST]])
5220 split[(/PATTERN/[,EXPR[,LIMIT]])]
5221 sprintf(FORMAT,LIST)
5222 sqrt(EXPR)
5223 srand(EXPR)
5224 stat(EXPR|FILEHANDLE|VAR)
5225 study[(SCALAR)]
5226 sub [NAME [(format)]] { BODY }  sub NAME [(format)];    sub [(format)] {...}
5227 substr(EXPR,OFFSET[,LEN])
5228 symlink(OLDFILE,NEWFILE)
5229 syscall(LIST)
5230 sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
5231 system(LIST)
5232 syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET])
5233 tell[(FILEHANDLE)]
5234 telldir(DIRHANDLE)
5235 time
5236 times
5237 tr/SEARCHLIST/REPLACEMENTLIST/cds
5238 truncate(FILE|EXPR,LENGTH)
5239 umask[(EXPR)]
5240 undef[(EXPR)]
5241 unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR
5242 unlink(LIST)
5243 unpack(TEMPLATE,EXPR)
5244 unshift(ARRAY,LIST)
5245 until (EXPR) { ... }                                    EXPR until EXPR
5246 utime(LIST)
5247 values(%HASH)
5248 vec(EXPR,OFFSET,BITS)
5249 wait
5250 waitpid(PID,FLAGS)
5251 wantarray       Returns true if the sub/eval is called in list context.
5252 warn(LIST)
5253 while  (EXPR) { ... }                                   EXPR while EXPR
5254 write[(EXPR|FILEHANDLE)]
5255 ... x ...       Repeat string or array.
5256 x= ...  Repetition assignment.
5257 y/SEARCHLIST/REPLACEMENTLIST/
5258 ... | ...       Bitwise or.
5259 ... || ...      Logical or.
5260 ~ ...           Unary bitwise complement.
5261 #!      OS interpreter indicator. If contains `perl', used for options, and -x.
5262 AUTOLOAD {...}  Shorthand for `sub AUTOLOAD {...}'.
5263 CORE::          Prefix to access builtin function if imported sub obscures it.
5264 SUPER::         Prefix to lookup for a method in @ISA classes.
5265 DESTROY         Shorthand for `sub DESTROY {...}'.
5266 ... EQ ...      Obsolete synonym of `eq'.
5267 ... GE ...      Obsolete synonym of `ge'.
5268 ... GT ...      Obsolete synonym of `gt'.
5269 ... LE ...      Obsolete synonym of `le'.
5270 ... LT ...      Obsolete synonym of `lt'.
5271 ... NE ...      Obsolete synonym of `ne'.
5272 abs [ EXPR ]    absolute value
5273 ... and ...             Low-precedence synonym for &&.
5274 bless REFERENCE [, PACKAGE]     Makes reference into an object of a package.
5275 chomp [LIST]    Strips $/ off LIST/$_. Returns count. Special if $/ eq ''!
5276 chr             Converts a number to char with the same ordinal.
5277 else            Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
5278 elsif           Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}.
5279 exists  $HASH{KEY}      True if the key exists.
5280 format [NAME] =  Start of output format. Ended by a single dot (.) on a line.
5281 formline PICTURE, LIST  Backdoor into \"format\" processing.
5282 glob EXPR       Synonym of <EXPR>.
5283 lc [ EXPR ]     Returns lowercased EXPR.
5284 lcfirst [ EXPR ]        Returns EXPR with lower-cased first letter.
5285 map EXPR, LIST  or map {BLOCK} LIST     Applies EXPR/BLOCK to elts of LIST.
5286 no PACKAGE [SYMBOL1, ...]  Partial reverse for `use'. Runs `unimport' method.
5287 not ...         Low-precedence synonym for ! - negation.
5288 ... or ...              Low-precedence synonym for ||.
5289 pos STRING    Set/Get end-position of the last match over this string, see \\G.
5290 quotemeta [ EXPR ]      Quote regexp metacharacters.
5291 qw/WORD1 .../           Synonym of split('', 'WORD1 ...')
5292 readline FH     Synonym of <FH>.
5293 readpipe CMD    Synonym of `CMD`.
5294 ref [ EXPR ]    Type of EXPR when dereferenced.
5295 sysopen FH, FILENAME, MODE [, PERM]     (MODE is numeric, see Fcntl.)
5296 tie VAR, PACKAGE, LIST  Hide an object behind a simple Perl variable.
5297 tied            Returns internal object for a tied data.
5298 uc [ EXPR ]     Returns upcased EXPR.
5299 ucfirst [ EXPR ]        Returns EXPR with upcased first letter.
5300 untie VAR       Unlink an object from a simple Perl variable.
5301 use PACKAGE [SYMBOL1, ...]  Compile-time `require' with consequent `import'.
5302 ... xor ...             Low-precedence synonym for exclusive or.
5303 prototype \&SUB Returns prototype of the function given a reference.
5304 =head1          Top-level heading.
5305 =head2          Second-level heading.
5306 =head3          Third-level heading (is there such?).
5307 =over [ NUMBER ]        Start list.
5308 =item [ TITLE ]         Start new item in the list.
5309 =back           End list.
5310 =cut            Switch from POD to Perl.
5311 =pod            Switch from Perl to POD.
5312 ")
5313
5314 (defun cperl-switch-to-doc-buffer ()
5315   "Go to the perl documentation buffer and insert the documentation."
5316   (interactive)
5317   (let ((buf (get-buffer-create cperl-doc-buffer)))
5318     (if (interactive-p)
5319         (switch-to-buffer-other-window buf)
5320       (set-buffer buf))
5321     (if (= (buffer-size) 0)
5322         (progn
5323           (insert (documentation-property 'cperl-short-docs
5324                                           'variable-documentation))
5325           (setq buffer-read-only t)))))
5326
5327 (defun cperl-beautify-regexp-piece (b e embed)
5328   ;; b is before the starting delimiter, e before the ending
5329   ;; e should be a marker, may be changed, but remains "correct".
5330   (let (s c tmp (m (make-marker)) (m1 (make-marker)) c1 spaces inline code)
5331     (if (not embed)
5332         (goto-char (1+ b))
5333       (goto-char b)
5334       (cond ((looking-at "(\\?\\\\#")   ; badly commented (?#)
5335              (forward-char 2)
5336              (delete-char 1)
5337              (forward-char 1))
5338             ((looking-at "(\\?[^a-zA-Z]")
5339              (forward-char 3))
5340             ((looking-at "(\\?")        ; (?i)
5341              (forward-char 2))
5342             (t
5343              (forward-char 1))))
5344     (setq c (if embed (current-indentation) (1- (current-column)))
5345           c1 (+ c (or cperl-regexp-indent-step cperl-indent-level)))
5346     (or (looking-at "[ \t]*[\n#]")
5347         (progn
5348           (insert "\n")))
5349     (goto-char e)
5350     (beginning-of-line)
5351     (if (re-search-forward "[^ \t]" e t)
5352         (progn
5353           (goto-char e)
5354           (insert "\n")
5355           (indent-to-column c)
5356           (set-marker e (point))))
5357     (goto-char b)
5358     (end-of-line 2)
5359     (while (< (point) (marker-position e))
5360       (beginning-of-line)
5361       (setq s (point)
5362             inline t)
5363       (skip-chars-forward " \t")
5364       (delete-region s (point))
5365       (indent-to-column c1)
5366       (while (and
5367               inline
5368               (looking-at 
5369                (concat "\\([a-zA-Z0-9]+[^*+{?]\\)" ; 1 word
5370                        "\\|"            ; Embedded variable
5371                        "\\$\\([a-zA-Z0-9_]+\\([[{]\\)?\\|[^\n \t)|]\\)" ; 2 3
5372                        "\\|"            ; $ ^
5373                        "[$^]"
5374                        "\\|"            ; simple-code simple-code*?
5375                        "\\(\\\\.\\|[^][()#|*+?\n]\\)\\([*+{?]\\??\\)?" ; 4 5
5376                        "\\|"            ; Class
5377                        "\\(\\[\\)"      ; 6
5378                        "\\|"            ; Grouping
5379                        "\\((\\(\\?\\)?\\)" ; 7 8
5380                        "\\|"            ; |
5381                        "\\(|\\)"        ; 9
5382                        )))
5383         (goto-char (match-end 0))
5384         (setq spaces t)
5385         (cond ((match-beginning 1)      ; Alphanum word + junk
5386                (forward-char -1))
5387               ((or (match-beginning 3)  ; $ab[12]
5388                    (and (match-beginning 5) ; X* X+ X{2,3}
5389                         (eq (preceding-char) ?\{)))
5390                (forward-char -1)
5391                (forward-sexp 1))
5392               ((match-beginning 6)      ; []
5393                (setq tmp (point))
5394                (if (looking-at "\\^?\\]")
5395                    (goto-char (match-end 0)))
5396                (or (re-search-forward "\\]\\([*+{?]\\)?" e t)
5397                    (progn
5398                      (goto-char (1- tmp))
5399                      (error "[]-group not terminated")))
5400                (if (not (eq (preceding-char) ?\{)) nil
5401                  (forward-char -1)
5402                  (forward-sexp 1)))
5403               ((match-beginning 7)      ; ()
5404                (goto-char (match-beginning 0))
5405                (or (eq (current-column) c1)
5406                    (progn
5407                      (insert "\n")
5408                      (indent-to-column c1)))
5409                (setq tmp (point))
5410                (forward-sexp 1)
5411                ;;              (or (forward-sexp 1)
5412                ;;                  (progn
5413                ;;                    (goto-char tmp)
5414                ;;                    (error "()-group not terminated")))
5415                (set-marker m (1- (point)))
5416                (set-marker m1 (point))
5417                (cond
5418                 ((not (match-beginning 8))
5419                  (cperl-beautify-regexp-piece tmp m t))
5420                 ((eq (char-after (+ 2 tmp)) ?\{) ; Code
5421                  t)
5422                 ((eq (char-after (+ 2 tmp)) ?\() ; Conditional
5423                  (goto-char (+ 2 tmp))
5424                  (forward-sexp 1)
5425                  (cperl-beautify-regexp-piece (point) m t))
5426                 (t
5427                  (cperl-beautify-regexp-piece tmp m t)))
5428                (goto-char m1)
5429                (cond ((looking-at "[*+?]\\??")
5430                       (goto-char (match-end 0)))
5431                      ((eq (following-char) ?\{)
5432                       (forward-sexp 1)
5433                       (if (eq (following-char) ?\?)
5434                           (forward-char))))
5435                (skip-chars-forward " \t")
5436                (setq spaces nil)
5437                (if (looking-at "[#\n]")
5438                    (progn
5439                      (or (eolp) (indent-for-comment))
5440                      (beginning-of-line 2))
5441                  (insert "\n"))
5442                (end-of-line)
5443                (setq inline nil))
5444               ((match-beginning 9)      ; |
5445                (forward-char -1)
5446                (setq tmp (point))
5447                (beginning-of-line)
5448                (if (re-search-forward "[^ \t]" tmp t)
5449                    (progn
5450                      (goto-char tmp)
5451                      (insert "\n"))
5452                  ;; first at line
5453                  (delete-region (point) tmp))
5454                (indent-to-column c)
5455                (forward-char 1)
5456                (skip-chars-forward " \t")
5457                (setq spaces nil)
5458                (if (looking-at "[#\n]")
5459                    (beginning-of-line 2)
5460                  (insert "\n"))
5461                (end-of-line)
5462                (setq inline nil)))
5463         (or (looking-at "[ \t\n]")
5464             (not spaces)
5465             (insert " "))
5466         (skip-chars-forward " \t"))
5467         (or (looking-at "[#\n]")
5468             (error "unknown code \"%s\" in a regexp" (buffer-substring (point)
5469                                                                         (1+ (point)))))
5470         (and inline (end-of-line 2)))
5471     ;; Special-case the last line of group
5472     (if (and (>= (point) (marker-position e))
5473              (/= (current-indentation) c))
5474         (progn
5475          (beginning-of-line)
5476          (setq s (point))
5477          (skip-chars-forward " \t")
5478          (delete-region s (point))
5479          (indent-to-column c)))
5480   ))
5481
5482 (defun cperl-make-regexp-x ()
5483   (save-excursion
5484     (or cperl-use-syntax-table-text-property
5485         (error "I need to have regex marked!"))
5486     ;; Find the start
5487     (re-search-backward "\\s|")         ; Assume it is scanned already.
5488     ;;(forward-char 1)
5489     (let ((b (point)) (e (make-marker)) have-x delim (c (current-column))
5490           (sub-p (eq (preceding-char) ?s)) s)
5491       (forward-sexp 1)
5492       (set-marker e (1- (point)))
5493       (setq delim (preceding-char))
5494       (if (and sub-p (eq delim (char-after (- (point) 2))))
5495           (error "Possible s/blah// - do not know how to deal with"))
5496       (if sub-p (forward-sexp 1))
5497       (if (looking-at "\\sw*x") 
5498           (setq have-x t)
5499         (insert "x"))
5500       ;; Protect fragile " ", "#"
5501       (if have-x nil
5502         (goto-char (1+ b))
5503         (while (re-search-forward "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*[ \t\n#]" e t) ; Need to include (?#) too?
5504           (forward-char -1)
5505           (insert "\\")
5506           (forward-char 1)))
5507       b)))
5508
5509 (defun cperl-beautify-regexp ()
5510   "do it. (Experimental, may change semantics, recheck the result.)
5511 We suppose that the regexp is scanned already."
5512   (interactive)
5513   (cperl-make-regexp-x)
5514   (re-search-backward "\\s|")           ; Assume it is scanned already.
5515   ;;(forward-char 1)
5516   (let ((b (point)) (e (make-marker)))
5517     (forward-sexp 1)
5518     (set-marker e (1- (point)))
5519     (cperl-beautify-regexp-piece b e nil)))
5520
5521 (defun cperl-contract-level ()
5522   "Find an enclosing group in regexp and contract it. (Experimental, may change semantics, recheck the result.) Unfinished.
5523 We suppose that the regexp is scanned already."
5524   (interactive)
5525   (let ((bb (cperl-make-regexp-x)) done)
5526     (while (not done)
5527       (or (eq (following-char) ?\()
5528           (search-backward "(" (1+ bb) t)
5529           (error "Cannot find `(' which starts a group"))
5530       (setq done
5531             (save-excursion
5532               (skip-chars-backward "\\")
5533               (looking-at "\\(\\\\\\\\\\)*(")))
5534       (or done (forward-char -1)))
5535     (let ((b (point)) (e (make-marker)) s c)
5536       (forward-sexp 1)
5537       (set-marker e (1- (point)))
5538       (goto-char b)
5539       (while (re-search-forward "\\(#\\)\\|\n" e t)
5540         (cond 
5541          ((match-beginning 1)           ; #-comment
5542           (or c (setq c (current-indentation)))
5543           (beginning-of-line 2)         ; Skip
5544           (setq s (point))
5545           (skip-chars-forward " \t")
5546           (delete-region s (point))
5547           (indent-to-column c))
5548          (t
5549           (delete-char -1)
5550           (just-one-space)))))))
5551
5552 (defun cperl-beautify-level ()
5553   "Find an enclosing group in regexp and beautify it. (Experimental, may change semantics, recheck the result.)
5554 We suppose that the regexp is scanned already."
5555   (interactive)
5556   (let ((bb (cperl-make-regexp-x)) done)
5557     (while (not done)
5558       (or (eq (following-char) ?\()
5559           (search-backward "(" (1+ bb) t)
5560           (error "Cannot find `(' which starts a group"))
5561       (setq done
5562             (save-excursion
5563               (skip-chars-backward "\\")
5564               (looking-at "\\(\\\\\\\\\\)*(")))
5565       (or done (forward-char -1)))
5566     (let ((b (point)) (e (make-marker)))
5567       (forward-sexp 1)
5568       (set-marker e (1- (point)))
5569       (cperl-beautify-regexp-piece b e nil))))
5570
5571 (if (fboundp 'run-with-idle-timer)
5572     (progn
5573       (defvar cperl-help-shown nil
5574         "Non-nil means that the help was already shown now.")
5575
5576       (defvar cperl-lazy-installed nil
5577         "Non-nil means that the lazy-help handlers are installed now.")
5578
5579       (defun cperl-lazy-install ()
5580         (interactive)
5581         (make-variable-buffer-local 'cperl-help-shown)
5582         (if (and (cperl-val 'cperl-lazy-help-time)
5583                  (not cperl-lazy-installed))
5584             (progn
5585               (add-hook 'post-command-hook 'cperl-lazy-hook)
5586               (run-with-idle-timer 
5587                (cperl-val 'cperl-lazy-help-time 1000000 5) 
5588                t 
5589                'cperl-get-help-defer)
5590               (setq cperl-lazy-installed t))))
5591
5592       (defun cperl-lazy-unstall ()
5593         (interactive)
5594         (remove-hook 'post-command-hook 'cperl-lazy-hook)
5595         (cancel-function-timers 'cperl-get-help-defer)
5596         (setq cperl-lazy-installed nil))
5597
5598       (defun cperl-lazy-hook ()
5599         (setq cperl-help-shown nil))
5600
5601       (defun cperl-get-help-defer ()
5602         (if (not (eq major-mode 'perl-mode)) nil
5603           (let ((cperl-message-on-help-error nil) (cperl-help-from-timer t))
5604             (cperl-get-help)
5605             (setq cperl-help-shown t))))
5606       (cperl-lazy-install)))
5607
5608 (provide 'cperl-mode)