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