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