perl 5.003_01: lib/File/Basename.pm
[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, 1986, 1987 Free Software Foundation, Inc.
10
11 ;; This file is not (yet) part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to
25 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
26
27 ;;; Corrections made by Ilya Zakharevich ilya@math.mps.ohio-state.edu
28 ;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de
29
30 ;; $Id: cperl-mode.el,v 1.24 1996/07/04 02:14:27 ilya Exp ilya $
31
32 ;;; To use this mode put the following into your .emacs file:
33
34 ;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)
35
36 ;;; You can either fine-tune the bells and whistles of this mode or
37 ;;; bulk enable them by putting
38
39 ;; (setq cperl-hairy t)
40
41 ;;; in your .emacs file. (Emacs rulers do not consider it politically
42 ;;; correct to make whistles enabled by default.)
43
44 ;;; Additional useful commands to put into your .emacs file:
45
46 ;; (setq auto-mode-alist
47 ;;       (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
48 ;; (setq interpreter-mode-alist (append interpreter-mode-alist
49 ;;                                      '(("miniperl" . perl-mode))))
50
51 ;;; The mode information (on C-h m) provides customization help.
52 ;;; If you use font-lock feature of this mode, it is advisable to use
53 ;;; eather lazy-lock-mode or fast-lock-mode (available on ELisp
54 ;;; archive in files lazy-lock.el and fast-lock.el). I prefer lazy-lock.
55
56 ;;; Faces used now: three faces for first-class and second-class keywords
57 ;;; and control flow words, one for each: comments, string, labels,
58 ;;; functions definitions and packages, arrays, hashes, and variable
59 ;;; definitions. If you do not see all these faces, your font-lock does
60 ;;; not define them, so you need to define them manually. Maybe you have 
61 ;;; an obsolete font-lock from 19.28 or earlier. Upgrade.
62
63 ;;; If you have grayscale monitor, and do not have the variable
64 ;;; font-lock-display-type bound to 'grayscale, insert 
65
66 ;;; (setq font-lock-display-type 'grayscale)
67
68 ;;; to your .emacs file.
69
70 ;;;; This mode supports font-lock, imenu and mode-compile. In the
71 ;;;; hairy version font-lock is on, but you should activate imenu
72 ;;;; yourself (note that mode-compile is not standard yet). Well, you
73 ;;;; can use imenu from keyboard anyway (M-x imenu), but it is better
74 ;;;; to bind it like that:
75
76 ;; (define-key global-map [M-S-down-mouse-3] 'imenu)
77
78 ;;; In fact the version of font-lock that this version supports can be
79 ;;; much newer than the version you actually have. This means that a
80 ;;; lot of faces can be set up, but are not visible on your screen
81 ;;; since the coloring rules for this faces are not defined.
82
83 ;;; Updates: ========================================
84
85 ;;; Made less hairy by default: parentheses not electric, 
86 ;;; linefeed not magic. Bug with abbrev-mode corrected.
87
88 ;;;; After 1.4:
89 ;;;  Better indentation:
90 ;;;  subs inside braces should work now, 
91 ;;;  Toplevel braces obey customization.
92 ;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
93 ;;;  moves cursor to a correct place.
94 ;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-( 
95 ;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
96 ;;;  Minor documentation fixes.
97 ;;;  Imenu understands packages as prefixes (including nested).
98 ;;;  Hairy options can be switched off one-by-one by setting to null.
99 ;;;  Names of functions and variables changed to conform to `cperl-' style.
100
101 ;;;; After 1.5:
102 ;;;  Some bugs with indentation of labels (and embedded subs) corrected.
103 ;;;  `cperl-indent-region' done (slow :-()).
104 ;;;  `cperl-fill-paragraph' done.
105 ;;;  Better package support for `imenu'.
106 ;;;  Progress indicator for indentation (with `imenu' loaded).
107 ;;;  `Cperl-set' was busted, now setting the individual hairy option 
108 ;;;     should be better.
109
110 ;;;; After 1.6:
111 ;;; `cperl-set-style' done.
112 ;;; `cperl-check-syntax' done.
113 ;;; Menu done.
114 ;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
115 ;;; Bugs with `cperl-auto-newline' corrected.
116 ;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation 
117 ;;; like $hash{.
118
119 ;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
120 ;;; - use `next-command-event', if `next-command-events' does not exist
121 ;;; - use `find-face' as def. of `is-face'
122 ;;; - corrected def. of `x-color-defined-p'
123 ;;; - added const defs for font-lock-comment-face,
124 ;;;   font-lock-keyword-face and font-lock-function-name-face
125 ;;; - added def. of font-lock-variable-name-face
126 ;;; - added (require 'easymenu) inside an `eval-when-compile'
127 ;;; - replaced 4-argument `substitute-key-definition' with ordinary
128 ;;;   `define-key's
129 ;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
130 ;;; Todo (at least):
131 ;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
132 ;;;   for portable code?
133 ;;; - should `cperl-mode' do a 
134 ;;;     (if (featurep 'easymenu) (easy-menu-add cperl-menu))
135 ;;;   or should this be left to the user's `cperl-mode-hook'?
136
137 ;;; Some bugs introduced by the above fix corrected (IZ ;-).
138 ;;; Some bugs under XEmacs introduced by the correction corrected.
139
140 ;;; Some more can remain since there are two many different variants. 
141 ;;; Please feedback!
142
143 ;;; We do not support fontification of arrays and hashes under 
144 ;;; obsolete font-lock any more. Upgrade.
145
146 ;;;; after 1.8 Minor bug with parentheses.
147 ;;;; after 1.9 Improvements from Joe Marzot.
148 ;;;; after 1.10
149 ;;;  Does not need easymenu to compile under XEmacs.
150 ;;;  `vc-insert-headers' should work better.
151 ;;;  Should work with 19.29 and 19.12.
152 ;;;  Small improvements to fontification.
153 ;;;  Expansion of keywords does not depend on C-? being backspace.
154
155 ;;; after 1.10+
156 ;;; 19.29 and 19.12 supported.
157 ;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
158 ;;; Support for font-lock-extra.el.
159
160 ;;;; After 1.11:
161 ;;; Tools submenu.
162 ;;; Support for perl5-info.
163 ;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
164 ;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
165 ;;; Fontifies `require a if b;', __DATA__.
166 ;;; Arglist for auto-fill-mode was incorrect.
167
168 ;;;; After 1.12:
169 ;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions 
170 ;;; vertically.
171 ;;; `cperl-do-auto-fill' updated for 19.29 style.
172 ;;; `cperl-info-on-command' now has a default.
173 ;;; Workaround for broken C-h on XEmacs.
174 ;;; VC strings escaped.
175 ;;; C-h f now may prompt for function name instead of going on,
176 ;;; controlled by `cperl-info-on-command-no-prompt'.
177
178 ;;;; After 1.13:
179 ;;; Msb buffer list includes perl files
180 ;;; Indent-for-comment uses indent-to
181 ;;; Can write tag files using etags.
182
183 ;;;; After 1.14:
184 ;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
185 ;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
186 ;;; Bug with auto-filling comments started with "##" corrected.
187
188 ;;;; Very slow now: on DB::DB 0.91, 486/66:
189
190 ;;;Function Name                             Call Count  Elapsed Time  Average Time
191 ;;;========================================  ==========  ============  ============
192 ;;;cperl-block-p                             469         3.7799999999  0.0080597014
193 ;;;cperl-get-state                           505         163.39000000  0.3235445544
194 ;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
195 ;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
196 ;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
197 ;;;cperl-indent-line                         505         172.88000000  0.3423366336
198 ;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
199 ;;;cperl-indent-exp                          1           177.97000000  177.97000000
200 ;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
201 ;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
202 ;;;cperl-indent-region                       1           177.94000000  177.94000000
203
204 ;;;; After 1.15:
205 ;;; Takes into account white space after opening parentheses during indent.
206 ;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
207 ;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
208 ;;; for indentation so far.
209 ;;; Fontification updated to 19.30 style. 
210 ;;; The change 19.29->30 did not add all the required functionality,
211 ;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
212 ;;;       ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
213
214 ;;;; After 1.16:
215 ;;;       else # comment
216 ;;;    recognized as a start of a block.
217 ;;;  Two different font-lock-levels provided.
218 ;;;  `cperl-pod-head-face' introduced. Used for highlighting.
219 ;;;  `imenu' marks pods, +Packages moved to the head. 
220
221 ;;;; After 1.17:
222 ;;;  Scan for pods highlights here-docs too.
223 ;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
224 ;;;  Only one here-doc-tag per line is supported, and one in comment
225 ;;;  or a string may break fontification.
226 ;;;  POD headers were supposed to fill one line only.
227
228 ;;;; After 1.18:
229 ;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme 
230 ;;;    may  break under XEmacs.
231 ;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
232 ;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
233 ;;;    compatibility with older lazy-lock.el) (older one overfontifies
234 ;;;    something nevertheless :-().
235 ;;;  Will not indent something inside pod and here-documents.
236 ;;;  Fontifies the package name after import/no/bootstrap.
237 ;;;  Added new entry to menu with meta-info about the mode.
238
239 ;;;; After 1.19:
240 ;;;  Prefontification works much better with 19.29. Should be checked
241 ;;;   with 19.30 as well.
242 ;;;  Some misprints in docs corrected.
243 ;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
244 ;;;  Now the pod search is much stricter, so it can help you to find
245 ;;;    pod sections which are broken because of whitespace before =blah
246 ;;;    - just observe the fontification.
247
248 ;;;; After 1.20
249 ;;;  Anonymous subs are indented with respect to the level of
250 ;;;    indentation of `sub' now.
251 ;;;  {} is recognized as hash after `bless' and `return'.
252 ;;;  Anonymous subs are split by `cperl-linefeed' as well.
253 ;;;  Electric parens embrace a region if present.
254 ;;;  To make `cperl-auto-newline' useful,
255 ;;;    `cperl-auto-newline-after-colon' is introduced.
256 ;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
257 ;;;  `cperl-electric-parens-string'.
258 ;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
259 ;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
260 ;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
261 ;;;  Beginning-of-defun-regexp was not anchored.
262
263 ;;;; After 1.21
264 ;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
265 ;;;    after ")".
266 ;;;  {} is recognized as expression after `tr' and friends.
267
268 ;;;; After 1.22
269 ;;;  Entry Hierarchy added to imenu. Very primitive so far.
270 ;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
271 ;;;  Writes its own TAGS files.
272 ;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
273 ;;;  19.31: Problems with scan for PODs corrected.
274 ;;;  First POD header correctly fontified.
275 ;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
276 ;;;  Apparently it makes a lot of hierarchy code obsolete...
277
278 ;;;; After 1.23
279 ;;;  Tags filler now scans *.xs as well.
280 ;;;  The info from *.xs scan is used by the hierarchy viewer.
281 ;;;  Hierarchy viewer documented.
282 ;;;  Bug in 19.31 imenu documented.
283
284 (defvar cperl-extra-newline-before-brace nil
285   "*Non-nil means that if, elsif, while, until, else, for, foreach
286 and do constructs look like:
287
288         if ()
289         {
290         }
291
292 instead of:
293
294         if () {
295         }
296 ")
297
298 (defvar cperl-indent-level 2
299   "*Indentation of CPerl statements with respect to containing block.")
300 (defvar cperl-lineup-step nil
301   "*`cperl-lineup' will always lineup at multiple of this number.
302 If `nil', the value of `cperl-indent-level' will be used.")
303 (defvar cperl-brace-imaginary-offset 0
304   "*Imagined indentation of a Perl open brace that actually follows a statement.
305 An open brace following other text is treated as if it were this far
306 to the right of the start of its line.")
307 (defvar cperl-brace-offset 0
308   "*Extra indentation for braces, compared with other text in same context.")
309 (defvar cperl-label-offset -2
310   "*Offset of CPerl label lines relative to usual indentation.")
311 (defvar cperl-min-label-indent 1
312   "*Minimal offset of CPerl label lines.")
313 (defvar cperl-continued-statement-offset 2
314   "*Extra indent for lines not starting new statements.")
315 (defvar cperl-continued-brace-offset 0
316   "*Extra indent for substatements that start with open-braces.
317 This is in addition to cperl-continued-statement-offset.")
318 (defvar cperl-close-paren-offset -1
319   "*Extra indent for substatements that start with close-parenthesis.")
320
321 (defvar cperl-auto-newline nil
322   "*Non-nil means automatically newline before and after braces,
323 and after colons and semicolons, inserted in CPerl code. The following
324 \\[cperl-electric-backspace] will remove the inserted whitespace.
325 Insertion after colons requires both this variable and 
326 `cperl-auto-newline-after-colon' set.")
327
328 (defvar cperl-auto-newline-after-colon nil
329   "*Non-nil means automatically newline even after colons.
330 Subject to `cperl-auto-newline' setting.")
331
332 (defvar cperl-tab-always-indent t
333   "*Non-nil means TAB in CPerl mode should always reindent the current line,
334 regardless of where in the line point is when the TAB command is used.")
335
336 (defvar cperl-font-lock nil
337   "*Non-nil (and non-null) means CPerl buffers will use font-lock-mode.
338 Can be overwritten by `cperl-hairy' if nil.")
339
340 (defvar cperl-electric-lbrace-space nil
341   "*Non-nil (and non-null) means { after $ in CPerl buffers should be preceeded by ` '.
342 Can be overwritten by `cperl-hairy' if nil.")
343
344 (defvar cperl-electric-parens-string "({[<"
345   "*String of parentheses that should be electric in CPerl.")
346
347 (defvar cperl-electric-parens nil
348   "*Non-nil (and non-null) means parentheses should be electric in CPerl.
349 Can be overwritten by `cperl-hairy' if nil.")
350 (defvar cperl-electric-parens-mark  
351   (and window-system
352        (or (and (boundp 'transient-mark-mode) ; For Emacs
353                 transient-mark-mode)
354            (and (boundp 'zmacs-regions) ; For XEmacs
355                 zmacs-regions)))
356   "*Not-nil means that electric parens look for active mark.
357 Default is yes if there is visual feedback on mark.")
358
359 (defvar cperl-electric-parens-mark (and window-system transient-mark-mode)
360   "*Not-nil means that electric parens look for active mark.
361 Default is yes if there is visual feedback on mark.")
362
363 (defvar cperl-electric-linefeed nil
364   "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
365 In any case these two mean plain and hairy linefeeds together.
366 Can be overwritten by `cperl-hairy' if nil.")
367
368 (defvar cperl-electric-keywords nil
369   "*Not-nil (and non-null) means keywords are electric in CPerl.
370 Can be overwritten by `cperl-hairy' if nil.")
371
372 (defvar cperl-hairy nil
373   "*Not-nil means all the bells and whistles are enabled in CPerl.")
374
375 (defvar cperl-comment-column 32
376   "*Column to put comments in CPerl (use \\[cperl-indent]' to lineup with code).")
377
378 (defvar cperl-vc-header-alist '((SCCS "$sccs = '%W\%' ;")
379                                 (RCS "$rcs = ' $Id\$ ' ;"))
380   "*What to use as `vc-header-alist' in CPerl.")
381
382 (defvar cperl-info-on-command-no-prompt nil
383   "*Not-nil (and non-null) means not to prompt on C-h f.
384 The opposite behaviour is always available if prefixed with C-c.
385 Can be overwritten by `cperl-hairy' if nil.")
386
387 (defvar cperl-pod-face 'font-lock-comment-face
388   "*The result of evaluation of this expression is used for pod highlighting.")
389
390 (defvar cperl-pod-head-face 'font-lock-variable-name-face
391   "*The result of evaluation of this expression is used for pod highlighting.
392 Font for POD headers.")
393
394 (defvar cperl-here-face 'font-lock-string-face
395   "*The result of evaluation of this expression is used for here-docs highlighting.")
396
397 (defvar cperl-pod-here-fontify '(featurep 'font-lock)
398   "*Not-nil after evaluation means to highlight pod and here-docs sections.")
399
400 (defvar cperl-pod-here-scan t
401   "*Not-nil means look for pod and here-docs sections during startup.
402 You can always make lookup from menu or using \\[cperl-find-pods-heres].")
403
404 (defvar cperl-imenu-addback nil
405   "*Not-nil means add backreferences to generated `imenu's.
406 May require patched `imenu' and `imenu-go'.")
407
408 \f
409
410 ;;; Short extra-docs.
411
412 (defvar cperl-tips 'please-ignore-this-line
413   "Get newest version of this package from
414   ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
415 and/or
416   ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
417
418 Get support packages choose-color.el (or font-lock-extra.el before
419 19.30), imenu-go.el from the same place.  \(Look for other files there
420 too... ;-) Get a patch for imenu.el in 19.29.  Note that for 19.30 and
421 later you should use choose-color.el *instead* of font-lock-extra.el 
422 \(and you will not get smart highlighting in C :-().
423
424 Note that to enable Compile choices in the menu you need to install
425 mode-compile.el.
426
427 Get perl5-info from 
428   http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz
429 \(may be quite obsolete, but still useful).
430
431 If you use imenu-go, run imenu on perl5-info buffer (you can do it
432 from CPerl menu). If many files are related, generate TAGS files from
433 Tools/Tags submenu in CPerl menu.
434
435 If some class structure is too complicated, use Tools/Hierarchy-view
436 from CPerl menu, or hierarchic view of imenu. The second one is very
437 rudimental, the first one requires generation of TAGS from
438 CPerl/Tools/Tags menu beforehand.
439
440 Before reporting (non-)problems look in the problem section on what I
441 know about them.")
442
443 (defvar cperl-problems 'please-ignore-this-line
444 "Emacs has a _very_ restricted syntax parsing engine. 
445
446 It may be corrected on the level of C code, please look in the
447 `non-problems' section if you want to volunteer.
448
449 CPerl mode tries to corrects some Emacs misunderstandings, however,
450 for effeciency reasons the degree of correction is different for
451 different operations. The partially corrected problems are: POD
452 sections, here-documents, regexps. The operations are: highlighting,
453 indentation, electric keywords, electric braces. 
454
455 This may be confusing, since the regexp s#//#/#\; may be highlighted
456 as a comment, but it will recognized as a regexp by the indentation
457 code. Or the opposite case, when a pod section is highlighted, but
458 breaks the indentation of the following code.
459
460 The main trick (to make $ a \"backslash\") makes constructions like
461 ${aaa} look like unbalanced braces. The only trick I can think out is
462 to insert it as $ {aaa} (legal in perl5, not in perl4). 
463
464 Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
465 as /($|\\s)/. Note that such a transpositinon is not always possible
466 :-(.  " )
467
468 (defvar cperl-non-problems 'please-ignore-this-line
469 "As you know from `problems' section, Perl syntax too hard for CPerl.
470
471 Most the time, if you write your own code, you may find an equivalent
472 \(and almost as readable) expression.
473
474 Try to help it: add comments with embedded quotes to fix CPerl
475 misunderstandings about the end of quotation:
476
477 $a='500$';      # ';
478
479 You won't need it too often. The reason: $ \"quotes\" the following
480 character (this saves a life a lot of times in CPerl), thus due to
481 Emacs parsing rules it does not consider tick after the dollar as a
482 closing one, but as a usual character.
483
484 Now the indentation code is pretty wise. The only drawback is that it
485 relies on Emacs parsing to find matching parentheses. And Emacs
486 *cannot* match parentheses in Perl 100% correctly. So
487         1 if s#//#/#;
488 will not break indentation, but
489         1 if ( s#//#/# );
490 will.
491
492 If you still get wrong indentation in situation that you think the
493 code should be able to parse, try:
494
495 a) Check what Emacs thinks about balance of your parentheses.
496 b) Supply the code to me (IZ).
497
498 Pods are treated _very_ rudimentally. Here-documents are not treated
499 at all (except highlighting and inhibiting indentation). (This may
500 change some time. RMS approved making syntax lookup recognize text
501 attributes, but volonteers are needed to change Emacs C code.)
502
503 To speed up coloring the following compromises exist:
504    a) sub in $mypackage::sub may be highlighted.
505    b) -z in [a-z] may be highlighted.
506    c) if your regexp contains a keyword (like \"s\"), it may be highlighted.
507
508
509 Imenu in 19.31 is broken. Set `imenu-use-keymap-menu' to t, and remove
510 `car' before `imenu-choose-buffer-index' in `imenu'.
511 ")
512
513 \f
514
515 ;;; Portability stuff:
516
517 (defsubst cperl-xemacs-p ()
518   (string-match "XEmacs\\|Lucid" emacs-version))
519
520 (defvar del-back-ch (car (append (where-is-internal 'delete-backward-char)
521                                  (where-is-internal 'backward-delete-char-untabify)))
522   "Character generated by key bound to delete-backward-char.")
523
524 (and (vectorp del-back-ch) (= (length del-back-ch) 1) 
525      (setq del-back-ch (aref del-back-ch 0)))
526
527 (if (cperl-xemacs-p)
528     (progn
529       ;; "Active regions" are on: use region only if active
530       ;; "Active regions" are off: use region unconditionally
531       (defun cperl-use-region-p ()
532         (if zmacs-regions (mark) t))
533       (defun cperl-mark-active () (mark)))
534   (defun cperl-use-region-p ()
535     (if transient-mark-mode mark-active t))
536   (defun cperl-mark-active () mark-active))
537
538 (defsubst cperl-enable-font-lock ()
539   (or (cperl-xemacs-p) window-system))
540
541 (if (boundp 'unread-command-events)
542     (if (cperl-xemacs-p)
543         (defun cperl-putback-char (c)   ; XEmacs >= 19.12
544           (setq unread-command-events (list (character-to-event c))))
545       (defun cperl-putback-char (c)     ; Emacs 19
546         (setq unread-command-events (list c))))
547   (defun cperl-putback-char (c)         ; XEmacs <= 19.11
548     (setq unread-command-event (character-to-event c))))
549
550 (or (fboundp 'uncomment-region)
551     (defun uncomment-region (beg end)
552       (interactive "r")
553       (comment-region beg end -1)))
554
555 (defvar cperl-do-not-fontify
556   (if (string< emacs-version "19.30")
557       'fontified
558     'lazy-lock)
559   "Text property which inhibits refontification.")
560
561 (defsubst cperl-put-do-not-fontify (from to)
562   (put-text-property (max (point-min) (1- from))
563                      to cperl-do-not-fontify t))
564
565 \f
566 ;;; Probably it is too late to set these guys already, but it can help later:
567
568 (setq auto-mode-alist
569       (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
570 (and (boundp 'interpreter-mode-alist)
571      (setq interpreter-mode-alist (append interpreter-mode-alist
572                                           '(("miniperl" . perl-mode)))))
573 (if (fboundp 'eval-when-compile)
574     (eval-when-compile
575       (condition-case nil
576           (require 'imenu)
577         (error nil))
578       (condition-case nil
579           (require 'easymenu)
580         (error nil))
581       ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
582       ;; macros instead of defsubsts don't work on Emacs, so we do the
583       ;; expansion manually. Any other suggestions?
584       (if (or (string-match "XEmacs\\|Lucid" emacs-version)
585               window-system)
586           (require 'font-lock))
587       (require 'cl)
588       ))
589
590 (defvar cperl-mode-abbrev-table nil
591   "Abbrev table in use in Cperl-mode buffers.")
592
593 (add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))
594
595 (defvar cperl-mode-map () "Keymap used in CPerl mode.")
596
597 (if cperl-mode-map nil
598   (setq cperl-mode-map (make-sparse-keymap))
599   (define-key cperl-mode-map "{" 'cperl-electric-lbrace)
600   (define-key cperl-mode-map "[" 'cperl-electric-paren)
601   (define-key cperl-mode-map "(" 'cperl-electric-paren)
602   (define-key cperl-mode-map "<" 'cperl-electric-paren)
603   (define-key cperl-mode-map "}" 'cperl-electric-brace)
604   (define-key cperl-mode-map ";" 'cperl-electric-semi)
605   (define-key cperl-mode-map ":" 'cperl-electric-terminator)
606   (define-key cperl-mode-map "\C-j" 'newline-and-indent)
607   (define-key cperl-mode-map "\C-c\C-j" 'cperl-linefeed)
608   (define-key cperl-mode-map "\C-c\C-a" 'cperl-toggle-auto-newline)
609   (define-key cperl-mode-map "\C-c\C-k" 'cperl-toggle-abbrev)
610   (define-key cperl-mode-map "\C-c\C-e" 'cperl-toggle-electric)
611   (define-key cperl-mode-map "\e\C-q" 'cperl-indent-exp) ; Usually not bound
612   ;;(define-key cperl-mode-map "\M-q" 'cperl-fill-paragraph)
613   ;;(define-key cperl-mode-map "\e;" 'cperl-indent-for-comment)
614   (define-key cperl-mode-map "\177" 'cperl-electric-backspace)
615   (define-key cperl-mode-map "\t" 'cperl-indent-command)
616   (if (cperl-xemacs-p)
617       ;; don't clobber the backspace binding:
618       (define-key cperl-mode-map [(control h) f] 'cperl-info-on-command)
619     (define-key cperl-mode-map "\C-hf" 'cperl-info-on-command))
620   (if (cperl-xemacs-p)
621       ;; don't clobber the backspace binding:
622       (define-key cperl-mode-map [(control c) (control h) f]
623         'cperl-info-on-current-command)
624     (define-key cperl-mode-map "\C-c\C-hf" 'cperl-info-on-current-command))
625   (if (and (cperl-xemacs-p) 
626            (<= emacs-minor-version 11) (<= emacs-major-version 19))
627       (progn
628         ;; substitute-key-definition is usefulness-deenhanced...
629         (define-key cperl-mode-map "\M-q" 'cperl-fill-paragraph)
630         (define-key cperl-mode-map "\e;" 'cperl-indent-for-comment)
631         (define-key cperl-mode-map "\e\C-\\" 'cperl-indent-region))
632     (substitute-key-definition
633      'indent-sexp 'cperl-indent-exp
634      cperl-mode-map global-map)
635     (substitute-key-definition
636      'fill-paragraph 'cperl-fill-paragraph
637      cperl-mode-map global-map)
638     (substitute-key-definition
639      'indent-region 'cperl-indent-region
640      cperl-mode-map global-map)
641     (substitute-key-definition
642      'indent-for-comment 'cperl-indent-for-comment
643      cperl-mode-map global-map)))
644
645 (condition-case nil
646     (progn
647       (require 'easymenu)
648       (easy-menu-define cperl-menu cperl-mode-map "Menu for CPerl mode"
649          '("Perl"
650            ["Beginning of function" beginning-of-defun t]
651            ["End of function" end-of-defun t]
652            ["Mark function" mark-defun t]
653            ["Indent expression" cperl-indent-exp t]
654            ["Fill paragraph/comment" cperl-fill-paragraph t]
655            ["Line up a construction" cperl-lineup (cperl-use-region-p)]
656            "----"
657            ["Indent region" cperl-indent-region (cperl-use-region-p)]
658            ["Comment region" comment-region (cperl-use-region-p)]
659            ["Uncomment region" uncomment-region (cperl-use-region-p)]
660            "----"
661            ["Run" mode-compile (fboundp 'mode-compile)]
662            ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
663                                           (get-buffer "*compilation*"))]
664            ["Next error" next-error (get-buffer "*compilation*")]
665            ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
666            "----"
667            ["Debugger" perldb t]
668            "----"
669            ("Tools"
670             ["Imenu" imenu (fboundp 'imenu)]
671             ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
672             ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
673             ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
674             ("Tags"
675 ;;;          ["Create tags for current file" cperl-etags t]
676 ;;;          ["Add tags for current file" (cperl-etags t) t]
677 ;;;          ["Create tags for Perl files in directory" (cperl-etags nil t) t]
678 ;;;          ["Add tags for Perl files in directory" (cperl-etags t t) t]
679 ;;;          ["Create tags for Perl files in (sub)directories" 
680 ;;;           (cperl-etags nil 'recursive) t]
681 ;;;          ["Add tags for Perl files in (sub)directories"
682 ;;;           (cperl-etags t 'recursive) t]) 
683 ;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
684              ["Create tags for current file" (cperl-write-tags nil t) t]
685              ["Add tags for current file" (cperl-write-tags) t]
686              ["Create tags for Perl files in directory" 
687               (cperl-write-tags nil t nil t) t]
688              ["Add tags for Perl files in directory" 
689               (cperl-write-tags nil nil nil t) t]
690              ["Create tags for Perl files in (sub)directories" 
691               (cperl-write-tags nil t t t) t]
692              ["Add tags for Perl files in (sub)directories"
693               (cperl-write-tags nil nil t t) t])
694             ["Recalculate PODs and HEREs" cperl-find-pods-heres t]
695             ["Define word at point" imenu-go-find-at-position 
696              (fboundp 'imenu-go-find-at-position)]
697             ["Help on function" cperl-info-on-command t]
698             ["Help on function at point" cperl-info-on-current-command t])
699            ("Toggle..."
700             ["Auto newline" cperl-toggle-auto-newline t]
701             ["Electric parens" cperl-toggle-electric t]
702             ["Electric keywords" cperl-toggle-abbrev t]
703             )
704            ("Indent styles..."
705             ["GNU" (cperl-set-style "GNU") t]
706             ["C++" (cperl-set-style "C++") t]
707             ["FSF" (cperl-set-style "FSF") t]
708             ["BSD" (cperl-set-style "BSD") t]
709             ["Whitesmith" (cperl-set-style "Whitesmith") t])
710            ("Micro-docs"
711             ["Tips" (describe-variable 'cperl-tips) t]
712             ["Problems" (describe-variable 'cperl-problems) t]
713             ["Non-problems" (describe-variable 'cperl-non-problems) t]))))
714   (error nil))
715
716 (autoload 'c-macro-expand "cmacexp"
717   "Display the result of expanding all C macros occurring in the region.
718 The expansion is entirely correct because it uses the C preprocessor."
719   t)
720
721 (defvar cperl-mode-syntax-table nil
722   "Syntax table in use in Cperl-mode buffers.")
723
724 (if cperl-mode-syntax-table
725     ()
726   (setq cperl-mode-syntax-table (make-syntax-table))
727   (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
728   (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
729   (modify-syntax-entry ?* "." cperl-mode-syntax-table)
730   (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
731   (modify-syntax-entry ?- "." cperl-mode-syntax-table)
732   (modify-syntax-entry ?= "." cperl-mode-syntax-table)
733   (modify-syntax-entry ?% "." cperl-mode-syntax-table)
734   (modify-syntax-entry ?< "." cperl-mode-syntax-table)
735   (modify-syntax-entry ?> "." cperl-mode-syntax-table)
736   (modify-syntax-entry ?& "." cperl-mode-syntax-table)
737   (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
738   (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
739   (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
740   (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
741   (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
742   (modify-syntax-entry ?_ "w" cperl-mode-syntax-table)
743   (modify-syntax-entry ?| "." cperl-mode-syntax-table))
744
745
746 \f
747 ;; Make customization possible "in reverse"
748 ;;(defun cperl-set (symbol to)
749 ;;  (or (eq (symbol-value symbol) 'null) (set symbol to)))
750 (defsubst cperl-val (symbol &optional default hairy)
751   (cond
752    ((eq (symbol-value symbol) 'null) default)
753    (cperl-hairy (or hairy t))
754    (t (symbol-value symbol))))
755 \f
756 ;; provide an alias for working with emacs 19.  the perl-mode that comes
757 ;; with it is really bad, and this lets us seamlessly replace it.
758 (fset 'perl-mode 'cperl-mode)
759 (defun cperl-mode ()
760   "Major mode for editing Perl code.
761 Expression and list commands understand all C brackets.
762 Tab indents for Perl code.
763 Paragraphs are separated by blank lines only.
764 Delete converts tabs to spaces as it moves back.
765
766 Various characters in Perl almost always come in pairs: {}, (), [],
767 sometimes <>. When the user types the first, she gets the second as
768 well, with optional special formatting done on {}.  (Disabled by
769 default.)  You can always quote (with \\[quoted-insert]) the left
770 \"paren\" to avoid the expansion. The processing of < is special,
771 since most the time you mean \"less\". Cperl mode tries to guess
772 whether you want to type pair <>, and inserts is if it
773 appropriate. You can set `cperl-electric-parens-string' to the string that
774 contains the parenths from the above list you want to be electrical.
775 Electricity of parenths is controlled by `cperl-electric-parens'.
776 You may also set `cperl-electric-parens-mark' to have electric parens
777 look for active mark and \"embrace\" a region if possible.'
778
779 CPerl mode provides expansion of the Perl control constructs:
780    if, else, elsif, unless, while, until, for, and foreach.
781 =========(Disabled by default, see `cperl-electric-keywords'.)
782 The user types the keyword immediately followed by a space, which causes
783 the construct to be expanded, and the user is positioned where she is most
784 likely to want to be.
785 eg. when the user types a space following \"if\" the following appears in
786 the buffer:
787             if () {     or   if ()
788             }                 {
789                               }
790 and the cursor is between the parentheses.  The user can then type some
791 boolean expression within the parens.  Having done that, typing
792 \\[cperl-linefeed] places you, appropriately indented on a new line
793 between the braces. If CPerl decides that you want to insert
794 \"English\" style construct like
795             bite if angry;
796 it will not do any expansion. See also help on variable 
797 `cperl-extra-newline-before-brace'.
798
799 \\[cperl-linefeed] is a convinience replacement for typing carriage
800 return. It places you in the next line with proper indentation, or if
801 you type it inside the inline block of control construct, like
802             foreach (@lines) {print; print}
803 and you are on a boundary of a statement inside braces, it will
804 transform the construct into a multiline and will place you into an
805 apporpriately indented blank line. If you need a usual 
806 `newline-and-indent' behaviour, it is on \\[newline-and-indent], 
807 see documentation on `cperl-electric-linefeed'.
808
809 \\{cperl-mode-map}
810
811 Setting the variable `cperl-font-lock' to t switches on
812 font-lock-mode, `cperl-electric-lbrace-space' to t switches on
813 electric space between $ and {, `cperl-electric-parens-string' is the
814 string that contains parentheses that should be electric in CPerl (see
815 also `cperl-electric-parens-mark' and `cperl-electric-parens'),
816 setting `cperl-electric-keywords' enables electric expansion of
817 control structures in CPerl. `cperl-electric-linefeed' governs which
818 one of two linefeed behavior is preferable. You can enable all these
819 options simultaneously (recommended mode of use) by setting
820 `cperl-hairy' to t. In this case you can switch separate options off
821 by setting them to `null'. Note that one may undo the extra whitespace
822 inserted by semis and braces in `auto-newline'-mode by consequent
823 \\[cperl-electric-backspace].
824
825 If your site has perl5 documentation in info format, you can use commands
826 \\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
827 These keys run commands `cperl-info-on-current-command' and
828 `cperl-info-on-command', which one is which is controlled by variable
829 `cperl-info-on-command-no-prompt' (in turn affected by `cperl-hairy').
830
831 Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
832 `cperl-pod-face', `cperl-pod-head-face' control processing of pod and
833 here-docs sections. In a future version results of scan may be used
834 for indentation too, currently they are used for highlighting only.
835
836 Variables controlling indentation style:
837  `cperl-tab-always-indent'
838     Non-nil means TAB in CPerl mode should always reindent the current line,
839     regardless of where in the line point is when the TAB command is used.
840  `cperl-auto-newline'
841     Non-nil means automatically newline before and after braces,
842     and after colons and semicolons, inserted in Perl code. The following
843     \\[cperl-electric-backspace] will remove the inserted whitespace.
844     Insertion after colons requires both this variable and 
845     `cperl-auto-newline-after-colon' set. 
846  `cperl-auto-newline-after-colon'
847     Non-nil means automatically newline even after colons.
848     Subject to `cperl-auto-newline' setting.
849  `cperl-indent-level'
850     Indentation of Perl statements within surrounding block.
851     The surrounding block's indentation is the indentation
852     of the line on which the open-brace appears.
853  `cperl-continued-statement-offset'
854     Extra indentation given to a substatement, such as the
855     then-clause of an if, or body of a while, or just a statement continuation.
856  `cperl-continued-brace-offset'
857     Extra indentation given to a brace that starts a substatement.
858     This is in addition to `cperl-continued-statement-offset'.
859  `cperl-brace-offset'
860     Extra indentation for line if it starts with an open brace.
861  `cperl-brace-imaginary-offset'
862     An open brace following other text is treated as if it the line started
863     this far to the right of the actual line indentation.
864  `cperl-label-offset'
865     Extra indentation for line that is a label.
866  `cperl-min-label-indent'
867     Minimal indentation for line that is a label.
868
869 Settings for K&R and BSD indentation styles are
870   `cperl-indent-level'                5    8
871   `cperl-continued-statement-offset'  5    8
872   `cperl-brace-offset'               -5   -8
873   `cperl-label-offset'               -5   -8
874
875 If `cperl-indent-level' is 0, the statement after opening brace in column 0 is indented on `cperl-brace-offset'+`cperl-continued-statement-offset'.
876
877 Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
878 with no args."
879   (interactive)
880   (kill-all-local-variables)
881   ;;(if cperl-hairy
882   ;;    (progn
883   ;;    (cperl-set 'cperl-font-lock cperl-hairy)
884   ;;    (cperl-set 'cperl-electric-lbrace-space cperl-hairy)
885   ;;    (cperl-set 'cperl-electric-parens "{[(<")
886   ;;    (cperl-set 'cperl-electric-keywords cperl-hairy)
887   ;;    (cperl-set 'cperl-electric-linefeed cperl-hairy)))
888   (use-local-map cperl-mode-map)
889   (if (cperl-val 'cperl-electric-linefeed)
890       (progn
891         (local-set-key "\C-J" 'cperl-linefeed)
892         (local-set-key "\C-C\C-J" 'newline-and-indent)))
893   (if (cperl-val 'cperl-info-on-command-no-prompt)
894       (progn
895         (if (cperl-xemacs-p)
896             ;; don't clobber the backspace binding:
897             (local-set-key [(control h) f] 'cperl-info-on-current-command)
898           (local-set-key "\C-hf" 'cperl-info-on-current-command))
899         (if (cperl-xemacs-p)
900             ;; don't clobber the backspace binding:
901             (local-set-key [(control c) (control h) f]
902                            'cperl-info-on-command)
903           (local-set-key "\C-c\C-hf" 'cperl-info-on-command))))
904   (setq major-mode 'perl-mode)
905   (setq mode-name "CPerl")
906   (if (not cperl-mode-abbrev-table)
907       (let ((prev-a-c abbrevs-changed))
908         (define-abbrev-table 'cperl-mode-abbrev-table '(
909                 ("if" "if" cperl-electric-keyword 0)
910                 ("elsif" "elsif" cperl-electric-keyword 0)
911                 ("while" "while" cperl-electric-keyword 0)
912                 ("until" "until" cperl-electric-keyword 0)
913                 ("unless" "unless" cperl-electric-keyword 0)
914                 ("else" "else" cperl-electric-else 0)
915                 ("for" "for" cperl-electric-keyword 0)
916                 ("foreach" "foreach" cperl-electric-keyword 0)
917                 ("do" "do" cperl-electric-keyword 0)))
918         (setq abbrevs-changed prev-a-c)))
919   (setq local-abbrev-table cperl-mode-abbrev-table)
920   (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
921   (set-syntax-table cperl-mode-syntax-table)
922   (make-local-variable 'paragraph-start)
923   (setq paragraph-start (concat "^$\\|" page-delimiter))
924   (make-local-variable 'paragraph-separate)
925   (setq paragraph-separate paragraph-start)
926   (make-local-variable 'paragraph-ignore-fill-prefix)
927   (setq paragraph-ignore-fill-prefix t)
928   (make-local-variable 'indent-line-function)
929   (setq indent-line-function 'cperl-indent-line)
930   (make-local-variable 'require-final-newline)
931   (setq require-final-newline t)
932   (make-local-variable 'comment-start)
933   (setq comment-start "# ")
934   (make-local-variable 'comment-end)
935   (setq comment-end "")
936   (make-local-variable 'comment-column)
937   (setq comment-column cperl-comment-column)
938   (make-local-variable 'comment-start-skip)
939   (setq comment-start-skip "#+ *")
940   (make-local-variable 'defun-prompt-regexp)
941   (setq defun-prompt-regexp "^[ \t]*sub\\s +\\([^ \t\n{;]+\\)\\s *")
942   (make-local-variable 'comment-indent-function)
943   (setq comment-indent-function 'cperl-comment-indent)
944   (make-local-variable 'parse-sexp-ignore-comments)
945   (setq parse-sexp-ignore-comments t)
946   (make-local-variable 'indent-region-function)
947   (setq indent-region-function 'cperl-indent-region)
948   ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
949   (make-local-variable 'imenu-create-index-function)
950   (setq imenu-create-index-function
951         (function imenu-example--create-perl-index))
952   (make-local-variable 'imenu-sort-function)
953   (setq imenu-sort-function nil)
954   (make-local-variable 'vc-header-alist)
955   (setq vc-header-alist cperl-vc-header-alist)
956   (make-local-variable 'font-lock-defaults)
957   (setq font-lock-defaults
958         (if (string< emacs-version "19.30")
959             '(perl-font-lock-keywords-2)
960           '((perl-font-lock-keywords
961              perl-font-lock-keywords-1
962              perl-font-lock-keywords-2))))
963   (or (fboundp 'cperl-old-auto-fill-mode)
964       (progn
965         (fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
966         (defun auto-fill-mode (&optional arg)
967           (interactive "P")
968           (cperl-old-auto-fill-mode arg)
969           (and auto-fill-function (eq major-mode 'perl-mode)
970                (setq auto-fill-function 'cperl-do-auto-fill)))))
971   (if (cperl-enable-font-lock)
972       (if (cperl-val 'cperl-font-lock) 
973           (progn (or cperl-faces-init (cperl-init-faces))
974                  (font-lock-mode 1))))
975   (and (boundp 'msb-menu-cond)
976        (not cperl-msb-fixed)
977        (cperl-msb-fix))
978   (run-hooks 'cperl-mode-hook)
979   ;; After hooks since fontification will break this
980   (if cperl-pod-here-scan (cperl-find-pods-heres)))
981 \f
982 ;; Fix for msb.el
983 (defvar cperl-msb-fixed nil)
984
985 (defun cperl-msb-fix ()
986   ;; Adds perl files to msb menu, supposes that msb is already loaded
987   (setq cperl-msb-fixed t)
988   (let* ((l (length msb-menu-cond))
989          (last (nth (1- l) msb-menu-cond))
990          (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
991          (handle (1- (nth 1 last))))
992     (setcdr precdr (list
993                     (list
994                      '(eq major-mode 'perl-mode)
995                      handle
996                      "Perl Files (%d)")
997                     last))))
998 \f
999 ;; This is used by indent-for-comment
1000 ;; to decide how much to indent a comment in CPerl code
1001 ;; based on its context. Do fallback if comment is found wrong.
1002
1003 (defvar cperl-wrong-comment)
1004
1005 (defun cperl-comment-indent ()
1006   (let ((p (point)) (c (current-column)) was)
1007     (if (looking-at "^#") 0             ; Existing comment at bol stays there.
1008       ;; Wrong comment found
1009       (save-excursion
1010         (setq was (cperl-to-comment-or-eol))
1011         (if (= (point) p)
1012             (progn
1013               (skip-chars-backward " \t")
1014               (max (1+ (current-column)) ; Else indent at comment column
1015                    comment-column))
1016           (if was nil
1017             (insert comment-start)
1018             (backward-char (length comment-start)))
1019           (setq cperl-wrong-comment t)
1020           (indent-to comment-column 1)  ; Indent minimum 1
1021           c)))))                        ; except leave at least one space.
1022
1023 ;;;(defun cperl-comment-indent-fallback ()
1024 ;;;  "Is called if the standard comment-search procedure fails.
1025 ;;;Point is at start of real comment."
1026 ;;;  (let ((c (current-column)) target cnt prevc)
1027 ;;;    (if (= c comment-column) nil
1028 ;;;      (setq cnt (skip-chars-backward "[ \t]"))
1029 ;;;      (setq target (max (1+ (setq prevc 
1030 ;;;                          (current-column))) ; Else indent at comment column
1031 ;;;                comment-column))
1032 ;;;      (if (= c comment-column) nil
1033 ;;;     (delete-backward-char cnt)
1034 ;;;     (while (< prevc target)
1035 ;;;       (insert "\t")
1036 ;;;       (setq prevc (current-column)))
1037 ;;;     (if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
1038 ;;;     (while (< prevc target)
1039 ;;;       (insert " ")
1040 ;;;       (setq prevc (current-column)))))))
1041
1042 (defun cperl-indent-for-comment ()
1043   "Substite for `indent-for-comment' in CPerl."
1044   (interactive)
1045   (let (cperl-wrong-comment)
1046     (indent-for-comment)
1047     (if cperl-wrong-comment
1048         (progn (cperl-to-comment-or-eol)
1049                (forward-char (length comment-start))))))
1050
1051 (defun cperl-electric-brace (arg &optional only-before)
1052   "Insert character and correct line's indentation.
1053 If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
1054 place (even in empty line), but not after. If after \")\" and the inserted
1055 char is \"{\", insert extra newline before only if 
1056 `cperl-extra-newline-before-brace'."
1057   (interactive "P")
1058   (let (insertpos)
1059     (if (and (not arg)                  ; No args, end (of empty line or auto)
1060              (eolp)
1061              (or (and (null only-before)
1062                       (save-excursion
1063                         (skip-chars-backward " \t")
1064                         (bolp)))
1065                  (and (eq last-command-char ?\{) ; Do not insert newline
1066                       ;; if after ")" and `cperl-extra-newline-before-brace'
1067                       ;; is nil, do not insert extra newline.
1068                       (not cperl-extra-newline-before-brace)
1069                       (save-excursion
1070                         (skip-chars-backward " \t")
1071                         (eq (preceding-char) ?\))))
1072                  (if cperl-auto-newline 
1073                      (progn (cperl-indent-line) (newline) t) nil)))
1074         (progn
1075           (if cperl-auto-newline
1076               (setq insertpos (point)))
1077           (insert last-command-char)
1078           (cperl-indent-line)
1079           (if (and cperl-auto-newline (null only-before))
1080               (progn
1081                 (newline)
1082                 (cperl-indent-line)))
1083           (save-excursion
1084             (if insertpos (progn (goto-char insertpos)
1085                                  (search-forward (make-string 
1086                                                   1 last-command-char))
1087                                  (setq insertpos (1- (point)))))
1088             (delete-char -1))))
1089     (if insertpos
1090         (save-excursion
1091           (goto-char insertpos)
1092           (self-insert-command (prefix-numeric-value arg)))
1093       (self-insert-command (prefix-numeric-value arg)))))
1094
1095 (defun cperl-electric-lbrace (arg)
1096   "Insert character, correct line's indentation, correct quoting by space."
1097   (interactive "P")
1098   (let (pos after 
1099             (cperl-auto-newline cperl-auto-newline)
1100             (other-end (if (and cperl-electric-parens-mark
1101                                 (cperl-mark-active)
1102                                 (> (mark) (point)))
1103                            (save-excursion
1104                              (goto-char (mark))
1105                              (point-marker)) 
1106                          nil)))
1107     (and (cperl-val 'cperl-electric-lbrace-space)
1108          (eq (preceding-char) ?$)
1109          (save-excursion
1110            (skip-chars-backward "$")
1111            (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
1112          (insert ? ))
1113     (if (cperl-after-expr-p nil "{};)") nil (setq cperl-auto-newline nil))
1114     (cperl-electric-brace arg)
1115     (and (cperl-val 'cperl-electric-parens)
1116          (eq last-command-char ?{)
1117          (memq last-command-char 
1118                (append cperl-electric-parens-string nil))
1119          (or (if other-end (goto-char (marker-position other-end)))
1120              t)
1121          (setq last-command-char ?} pos (point))
1122          (progn (cperl-electric-brace arg t)
1123                 (goto-char pos)))))
1124
1125 (defun cperl-electric-paren (arg)
1126   "Insert a matching pair of parentheses."
1127   (interactive "P")
1128   (let ((beg (save-excursion (beginning-of-line) (point)))
1129         (other-end (if (and cperl-electric-parens-mark
1130                             (cperl-mark-active) 
1131                             (> (mark) (point)))
1132                            (save-excursion
1133                              (goto-char (mark))
1134                              (point-marker)) 
1135                      nil)))
1136     (if (and (cperl-val 'cperl-electric-parens)
1137              (memq last-command-char
1138                    (append cperl-electric-parens-string nil))
1139              (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
1140              ;;(not (save-excursion (search-backward "#" beg t)))
1141              (if (eq last-command-char ?<)
1142                  (cperl-after-expr-p nil "{};(,:=")
1143                1))
1144         (progn
1145           (insert last-command-char)
1146           (if other-end (goto-char (marker-position other-end)))
1147           (insert (cdr (assoc last-command-char '((?{ .?})
1148                                                   (?[ . ?])
1149                                                   (?( . ?))
1150                                                   (?< . ?>)))))
1151           (forward-char -1))
1152       (insert last-command-char)
1153       )))
1154
1155 (defun cperl-electric-keyword ()
1156   "Insert a construction appropriate after a keyword."
1157   (let ((beg (save-excursion (beginning-of-line) (point))) 
1158         (dollar (eq (preceding-char) ?$)))
1159     (and (save-excursion
1160            (backward-sexp 1)
1161            (cperl-after-expr-p nil "{};:"))
1162          (save-excursion 
1163            (not 
1164             (re-search-backward
1165              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
1166              beg t)))
1167          (save-excursion (or (not (re-search-backward "^=" nil t))
1168                              (looking-at "=cut")))
1169          (progn
1170            (and dollar (insert " $"))
1171            (cperl-indent-line)
1172            ;;(insert " () {\n}")
1173            (cond
1174             (cperl-extra-newline-before-brace
1175              (insert " ()\n")
1176              (insert "{")
1177              (cperl-indent-line)
1178              (insert "\n")
1179              (cperl-indent-line)
1180              (insert "\n}"))
1181             (t
1182              (insert " () {\n}"))
1183             )
1184            (or (looking-at "[ \t]\\|$") (insert " "))
1185            (cperl-indent-line)
1186            (if dollar (progn (search-backward "$")
1187                              (forward-char 1))
1188              (search-backward ")"))
1189            (cperl-putback-char del-back-ch)))))
1190
1191 (defun cperl-electric-else ()
1192   "Insert a construction appropriate after a keyword."
1193   (let ((beg (save-excursion (beginning-of-line) (point))))
1194     (and (save-excursion
1195            (backward-sexp 1)
1196            (cperl-after-expr-p nil "{};:"))
1197          (save-excursion 
1198            (not 
1199             (re-search-backward
1200              "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
1201              beg t)))
1202          (save-excursion (or (not (re-search-backward "^=" nil t))
1203                              (looking-at "=cut")))
1204          (progn
1205            (cperl-indent-line)
1206            ;;(insert " {\n\n}")
1207            (cond
1208             (cperl-extra-newline-before-brace
1209              (insert "\n")
1210              (insert "{")
1211              (cperl-indent-line)
1212              (insert "\n\n}"))
1213             (t
1214              (insert " {\n\n}"))
1215             )
1216            (or (looking-at "[ \t]\\|$") (insert " "))
1217            (cperl-indent-line)
1218            (forward-line -1)
1219            (cperl-indent-line)
1220            (cperl-putback-char del-back-ch)))))
1221
1222 (defun cperl-linefeed ()
1223   "Go to end of line, open a new line and indent appropriately."
1224   (interactive)
1225   (let ((beg (save-excursion (beginning-of-line) (point)))
1226         (end (save-excursion (end-of-line) (point)))
1227         (pos (point)) start)
1228     (if (and                            ; Check if we need to split:
1229                                         ; i.e., on a boundary and inside "{...}" 
1230          (save-excursion (cperl-to-comment-or-eol)
1231            (>= (point) pos))
1232          (or (save-excursion
1233                (skip-chars-backward " \t" beg)
1234                (forward-char -1)
1235                (looking-at "[;{]"))
1236              (looking-at "[ \t]*}")
1237              (re-search-forward "\\=[ \t]*;" end t))
1238          (save-excursion
1239            (and
1240             (eq (car (parse-partial-sexp pos end -1)) -1)
1241             (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
1242             (progn
1243               (backward-sexp 1)
1244               (setq start (point-marker))
1245               (<= start pos)))))
1246         (progn
1247           (skip-chars-backward " \t")
1248           (or (memq (preceding-char) (append ";{" nil))
1249               (insert ";"))
1250           (insert "\n")
1251           (forward-line -1)
1252           (cperl-indent-line)
1253           (goto-char start)
1254           (or (looking-at "{[ \t]*$")   ; If there is a statement
1255                                         ; before, move it to separate line
1256               (progn
1257                 (forward-char 1)
1258                 (insert "\n")
1259                 (cperl-indent-line)))
1260           (forward-line 1)              ; We are on the target line
1261           (cperl-indent-line)
1262           (beginning-of-line)
1263           (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
1264                                             ; after, move it to separate line
1265               (progn
1266                 (end-of-line)
1267                 (search-backward "}" beg)
1268                 (skip-chars-backward " \t")
1269                 (or (memq (preceding-char) (append ";{" nil))
1270                     (insert ";"))
1271                 (insert "\n")
1272                 (cperl-indent-line)
1273                 (forward-line -1)))
1274           (forward-line -1)             ; We are on the line before target 
1275           (end-of-line)
1276           (newline-and-indent))
1277       (end-of-line)                     ; else
1278       (if (not (looking-at "\n[ \t]*$"))
1279           (newline-and-indent)
1280         (forward-line 1)
1281         (cperl-indent-line)))))
1282
1283 (defun cperl-electric-semi (arg)
1284   "Insert character and correct line's indentation."
1285   (interactive "P")
1286   (if cperl-auto-newline
1287       (cperl-electric-terminator arg)
1288     (self-insert-command (prefix-numeric-value arg))))
1289
1290 (defun cperl-electric-terminator (arg)
1291   "Insert character and correct line's indentation."
1292   (interactive "P")
1293   (let (insertpos (end (point)) 
1294                   (auto (and cperl-auto-newline
1295                              (or (not (eq last-command-char ?:))
1296                                  cperl-auto-newline-after-colon))))
1297     (if (and (not arg) (eolp)
1298              (not (save-excursion
1299                     (beginning-of-line)
1300                     (skip-chars-forward " \t")
1301                     (or
1302                      ;; Ignore in comment lines
1303                      (= (following-char) ?#)
1304                      ;; Colon is special only after a label
1305                      ;; So quickly rule out most other uses of colon
1306                      ;; and do no indentation for them.
1307                      (and (eq last-command-char ?:)
1308                           (save-excursion
1309                             (forward-word 1)
1310                             (skip-chars-forward " \t")
1311                             (and (< (point) end)
1312                                  (progn (goto-char (- end 1))
1313                                         (not (looking-at ":"))))))
1314                      (progn
1315                        (beginning-of-defun)
1316                        (let ((pps (parse-partial-sexp (point) end)))
1317                          (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
1318         (progn
1319           (insert last-command-char)
1320           (forward-char -1)
1321           (if auto (setq insertpos (point-marker)))
1322           (forward-char 1)
1323           (cperl-indent-line)
1324           (if auto
1325               (progn
1326                 (newline)
1327                 (cperl-indent-line)))
1328 ;;        (save-excursion
1329 ;;          (if insertpos (progn (goto-char (marker-position insertpos))
1330 ;;                               (search-forward (make-string 
1331 ;;                                                1 last-command-char))
1332 ;;                               (setq insertpos (1- (point)))))
1333 ;;          (delete-char -1))))
1334           (save-excursion
1335             (if insertpos (goto-char (marker-position insertpos))
1336               (forward-char -1))
1337             (delete-char 1))))
1338     (if insertpos
1339         (save-excursion
1340           (goto-char insertpos)
1341           (self-insert-command (prefix-numeric-value arg)))
1342       (self-insert-command (prefix-numeric-value arg)))))
1343
1344 (defun cperl-electric-backspace (arg)
1345   "Backspace-untabify, or remove the whitespace inserted by an electric key."
1346   (interactive "p")
1347   (if (and cperl-auto-newline 
1348            (memq last-command '(cperl-electric-semi 
1349                                 cperl-electric-terminator
1350                                 cperl-electric-lbrace))
1351            (memq (preceding-char) '(?  ?\t ?\n)))
1352       (let (p)
1353         (if (eq last-command 'cperl-electric-lbrace) 
1354             (skip-chars-forward " \t\n"))
1355         (setq p (point))
1356         (skip-chars-backward " \t\n")
1357         (delete-region (point) p))
1358     (backward-delete-char-untabify arg)))
1359
1360 (defun cperl-inside-parens-p ()
1361   (condition-case ()
1362       (save-excursion
1363         (save-restriction
1364           (narrow-to-region (point)
1365                             (progn (beginning-of-defun) (point)))
1366           (goto-char (point-max))
1367           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
1368     (error nil)))
1369 \f
1370 (defun cperl-indent-command (&optional whole-exp)
1371   "Indent current line as Perl code, or in some cases insert a tab character.
1372 If `cperl-tab-always-indent' is non-nil (the default), always indent current line.
1373 Otherwise, indent the current line only if point is at the left margin
1374 or in the line's indentation; otherwise insert a tab.
1375
1376 A numeric argument, regardless of its value,
1377 means indent rigidly all the lines of the expression starting after point
1378 so that this line becomes properly indented.
1379 The relative indentation among the lines of the expression are preserved."
1380   (interactive "P")
1381   (if whole-exp
1382       ;; If arg, always indent this line as Perl
1383       ;; and shift remaining lines of expression the same amount.
1384       (let ((shift-amt (cperl-indent-line))
1385             beg end)
1386         (save-excursion
1387           (if cperl-tab-always-indent
1388               (beginning-of-line))
1389           (setq beg (point))
1390           (forward-sexp 1)
1391           (setq end (point))
1392           (goto-char beg)
1393           (forward-line 1)
1394           (setq beg (point)))
1395         (if (> end beg)
1396             (indent-code-rigidly beg end shift-amt "#")))
1397     (if (and (not cperl-tab-always-indent)
1398              (save-excursion
1399                (skip-chars-backward " \t")
1400                (not (bolp))))
1401         (insert-tab)
1402       (cperl-indent-line))))
1403
1404 (defun cperl-indent-line (&optional symbol)
1405   "Indent current line as Perl code.
1406 Return the amount the indentation changed by."
1407   (let (indent
1408         beg shift-amt
1409         (case-fold-search nil)
1410         (pos (- (point-max) (point))))
1411     (setq indent (cperl-calculate-indent nil symbol))
1412     (beginning-of-line)
1413     (setq beg (point))
1414     (cond ((eq indent nil)
1415            (setq indent (current-indentation)))
1416           ;;((eq indent t)    ; Never?
1417           ;; (setq indent (cperl-calculate-indent-within-comment)))
1418           ;;((looking-at "[ \t]*#")
1419           ;; (setq indent 0))
1420           (t
1421            (skip-chars-forward " \t")
1422            (if (listp indent) (setq indent (car indent)))
1423            (cond ((looking-at "[A-Za-z]+:[^:]")
1424                   (and (> indent 0)
1425                        (setq indent (max cperl-min-label-indent
1426                                          (+ indent cperl-label-offset)))))
1427                  ((= (following-char) ?})
1428                   (setq indent (- indent cperl-indent-level)))
1429                  ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
1430                   (setq indent (+ indent cperl-close-paren-offset)))
1431                  ((= (following-char) ?{)
1432                   (setq indent (+ indent cperl-brace-offset))))))
1433     (skip-chars-forward " \t")
1434     (setq shift-amt (- indent (current-column)))
1435     (if (zerop shift-amt)
1436         (if (> (- (point-max) pos) (point))
1437             (goto-char (- (point-max) pos)))
1438       (delete-region beg (point))
1439       (indent-to indent)
1440       ;; If initial point was within line's indentation,
1441       ;; position after the indentation.  Else stay at same point in text.
1442       (if (> (- (point-max) pos) (point))
1443           (goto-char (- (point-max) pos))))
1444     shift-amt))
1445
1446 (defun cperl-after-label ()
1447   ;; Returns true if the point is after label. Does not do save-excursion.
1448   (and (eq (preceding-char) ?:)
1449        (memq (char-syntax (char-after (- (point) 2)))
1450              '(?w ?_))
1451        (progn
1452          (backward-sexp)
1453          (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:"))))
1454
1455 (defun cperl-get-state (&optional parse-start start-state)
1456   ;; returns list (START STATE DEPTH PRESTART), START is a good place
1457   ;; to start parsing, STATE is what is returned by
1458   ;; `parse-partial-sexp'. DEPTH is true is we are immediately after
1459   ;; end of block which contains START. PRESTART is the position
1460   ;; basing on which START was found.
1461   (save-excursion
1462     (let ((start-point (point)) depth state start prestart)
1463       (if parse-start
1464           (goto-char parse-start)
1465         (beginning-of-defun))
1466       (setq prestart (point))
1467       (if start-state nil
1468         ;; Try to go out, if sub is not on the outermost level
1469         (while (< (point) start-point)
1470           (setq start (point) parse-start start depth nil
1471                 state (parse-partial-sexp start start-point -1))
1472           (if (> (car state) -1) nil
1473             ;; The current line could start like }}}, so the indentation
1474             ;; corresponds to a different level than what we reached
1475             (setq depth t)
1476             (beginning-of-line 2)))     ; Go to the next line.
1477         (if start (goto-char start)))   ; Not at the start of file
1478       (setq start (point))
1479       (if (< start start-point) (setq parse-start start))
1480       (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
1481       (list start state depth prestart))))
1482
1483 (defun cperl-block-p ()                 ; Do not C-M-q ! One string contains ";" !
1484   ;; Positions is before ?\{. Checks whether it starts a block.
1485   ;; No save-excursion!
1486   (cperl-backward-to-noncomment (point-min))
1487   ;;(skip-chars-backward " \t\n\f")
1488   (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label! \C-@ at bobp
1489                                         ; Label may be mixed up with `$blah :'
1490       (save-excursion (cperl-after-label))
1491       (and (eq (char-syntax (preceding-char)) ?w)
1492            (progn
1493              (backward-sexp)
1494              ;; Need take into account `bless', `return', `tr',...
1495              (or (and (looking-at "\\sw+[ \t\n\f]*[{#]") ; Method call syntax
1496                       (not (looking-at "\\(bless\\|return\\|qw\\|tr\\|[smy]\\)\\>")))
1497                  (progn
1498                    (skip-chars-backward " \t\n\f")
1499                    (and (eq (char-syntax (preceding-char)) ?w)
1500                         (progn
1501                           (backward-sexp)
1502                           (looking-at 
1503                            "sub[ \t]+\\sw+[ \t\n\f]*[#{]")))))))))
1504
1505 (defun cperl-calculate-indent (&optional parse-start symbol)
1506   "Return appropriate indentation for current line as Perl code.
1507 In usual case returns an integer: the column to indent to.
1508 Returns nil if line starts inside a string, t if in a comment."
1509   (save-excursion
1510     (if (memq (get-text-property (point) 'syntax-type) '(pod here-doc)) nil
1511       (beginning-of-line)
1512       (let* ((indent-point (point))
1513              (case-fold-search nil)
1514              (s-s (cperl-get-state))
1515              (start (nth 0 s-s))
1516              (state (nth 1 s-s))
1517              (containing-sexp (car (cdr state)))
1518              (char-after (save-excursion
1519                            (skip-chars-forward " \t")
1520                            (following-char)))
1521              (start-indent (save-excursion
1522                              (goto-char start)
1523                              (- (current-indentation)
1524                                 (if (nth 2 s-s) cperl-indent-level 0))))
1525              old-indent)
1526         ;;      (or parse-start (null symbol)
1527         ;;        (setq parse-start (symbol-value symbol) 
1528         ;;              start-indent (nth 2 parse-start) 
1529         ;;              parse-start (car parse-start)))
1530         ;;      (if parse-start
1531         ;;        (goto-char parse-start)
1532         ;;      (beginning-of-defun))
1533         ;;      ;; Try to go out
1534         ;;      (while (< (point) indent-point)
1535         ;;      (setq start (point) parse-start start moved nil
1536         ;;            state (parse-partial-sexp start indent-point -1))
1537         ;;      (if (> (car state) -1) nil
1538         ;;        ;; The current line could start like }}}, so the indentation
1539         ;;        ;; corresponds to a different level than what we reached
1540         ;;        (setq moved t)
1541         ;;        (beginning-of-line 2)))       ; Go to the next line.
1542         ;;      (if start                               ; Not at the start of file
1543         ;;        (progn
1544         ;;          (goto-char start)
1545         ;;          (setq start-indent (current-indentation))
1546         ;;          (if moved                   ; Should correct...
1547         ;;              (setq start-indent (- start-indent cperl-indent-level))))
1548         ;;      (setq start-indent 0))
1549         ;;      (if (< (point) indent-point) (setq parse-start (point)))
1550         ;;      (or state (setq state (parse-partial-sexp 
1551         ;;                           (point) indent-point -1 nil start-state)))
1552         ;;      (setq containing-sexp 
1553         ;;          (or (car (cdr state)) 
1554         ;;              (and (>= (nth 6 state) 0) old-containing-sexp))
1555         ;;          old-containing-sexp nil start-state nil)
1556 ;;;;      (while (< (point) indent-point)
1557 ;;;;    (setq parse-start (point))
1558 ;;;;    (setq state (parse-partial-sexp (point) indent-point -1 nil start-state))
1559 ;;;;    (setq containing-sexp 
1560 ;;;;          (or (car (cdr state)) 
1561 ;;;;              (and (>= (nth 6 state) 0) old-containing-sexp))
1562 ;;;;          old-containing-sexp nil start-state nil))
1563         ;;      (if symbol (set symbol (list indent-point state start-indent)))
1564         ;;      (goto-char indent-point)
1565         (cond ((or (nth 3 state) (nth 4 state))
1566                ;; return nil or t if should not change this line
1567                (nth 4 state))
1568               ((null containing-sexp)
1569                ;; Line is at top level.  May be data or function definition,
1570                ;; or may be function argument declaration.
1571                ;; Indent like the previous top level line
1572                ;; unless that ends in a closeparen without semicolon,
1573                ;; in which case this line is the first argument decl.
1574                (skip-chars-forward " \t")
1575                (+ start-indent
1576                   (if (= (following-char) ?{) cperl-continued-brace-offset 0)
1577                   (progn
1578                     (cperl-backward-to-noncomment (or parse-start (point-min)))
1579                     ;;(skip-chars-backward " \t\f\n")
1580                     ;; Look at previous line that's at column 0
1581                     ;; to determine whether we are in top-level decls
1582                     ;; or function's arg decls.  Set basic-indent accordingly.
1583                     ;; Now add a little if this is a continuation line.
1584                     (if (or (bobp)
1585                             (memq (preceding-char) (append " ;}" nil)) ; Was ?\)
1586                             (memq char-after (append ")]}" nil))) 
1587                         0
1588                       cperl-continued-statement-offset))))
1589               ((/= (char-after containing-sexp) ?{)
1590                ;; line is expression, not statement:
1591                ;; indent to just after the surrounding open,
1592                ;; skip blanks if we do not close the expression.
1593                (goto-char (1+ containing-sexp))
1594                (or (memq char-after (append ")]}" nil))
1595                    (looking-at "[ \t]*\\(#\\|$\\)")
1596                    (skip-chars-forward " \t"))
1597                (current-column))
1598               ((progn
1599                  ;; Containing-expr starts with \{. Check whether it is a hash.
1600                  (goto-char containing-sexp)
1601                  (not (cperl-block-p)))
1602                (goto-char (1+ containing-sexp))
1603                (or (eq char-after ?\})
1604                    (looking-at "[ \t]*\\(#\\|$\\)")
1605                    (skip-chars-forward " \t"))
1606                (+ (current-column)      ; Correct indentation of trailing ?\}
1607                   (if (eq char-after ?\}) (+ cperl-indent-level
1608                                              cperl-close-paren-offset) 
1609                     0)))
1610               (t
1611                ;; Statement level.  Is it a continuation or a new statement?
1612                ;; Find previous non-comment character.
1613                (goto-char indent-point)
1614                (cperl-backward-to-noncomment containing-sexp)
1615                ;; Back up over label lines, since they don't
1616                ;; affect whether our line is a continuation.
1617                (while (or (eq (preceding-char) ?\,)
1618                           (and (eq (preceding-char) ?:)
1619                                (or;;(eq (char-after (- (point) 2)) ?\') ; ????
1620                                 (memq (char-syntax (char-after (- (point) 2)))
1621                                       '(?w ?_)))))
1622                  (if (eq (preceding-char) ?\,)
1623                      ;; Will go to beginning of line, essentially.
1624                      ;; Will ignore embedded sexpr XXXX.
1625                      (cperl-backward-to-start-of-continued-exp containing-sexp))
1626                  (beginning-of-line)
1627                  (cperl-backward-to-noncomment containing-sexp))
1628                ;; Now we get the answer.
1629                (if (not (memq (preceding-char) (append ", ;}{" '(nil)))) ; Was ?\,
1630                    ;; This line is continuation of preceding line's statement;
1631                    ;; indent  `cperl-continued-statement-offset'  more than the
1632                    ;; previous line of the statement.
1633                    (progn
1634                      (cperl-backward-to-start-of-continued-exp containing-sexp)
1635                      (+ (if (memq char-after (append "}])" nil))
1636                             0           ; Closing parenth
1637                           cperl-continued-statement-offset)
1638                         (current-column)
1639                         (if (eq char-after ?\{)
1640                             cperl-continued-brace-offset 0)))
1641                  ;; This line starts a new statement.
1642                  ;; Position following last unclosed open.
1643                  (goto-char containing-sexp)
1644                  ;; Is line first statement after an open-brace?
1645                  (or
1646                   ;; If no, find that first statement and indent like
1647                   ;; it.  If the first statement begins with label, do
1648                   ;; not belive when the indentation of the label is too
1649                   ;; small.
1650                   (save-excursion
1651                     (forward-char 1)
1652                     (setq old-indent (current-indentation))
1653                     (let ((colon-line-end 0))
1654                       (while (progn (skip-chars-forward " \t\n")
1655                                     (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]"))
1656                         ;; Skip over comments and labels following openbrace.
1657                         (cond ((= (following-char) ?\#)
1658                                (forward-line 1))
1659                               ;; label:
1660                               (t
1661                                (save-excursion (end-of-line)
1662                                                (setq colon-line-end (point)))
1663                                (search-forward ":"))))
1664                       ;; The first following code counts
1665                       ;; if it is before the line we want to indent.
1666                       (and (< (point) indent-point)
1667                            (if (> colon-line-end (point)) ; After label
1668                                (if (> (current-indentation) 
1669                                       cperl-min-label-indent)
1670                                    (- (current-indentation) cperl-label-offset)
1671                                  ;; Do not belive: `max' is involved
1672                                  (+ old-indent cperl-indent-level))
1673                              (current-column)))))
1674                   ;; If no previous statement,
1675                   ;; indent it relative to line brace is on.
1676                   ;; For open brace in column zero, don't let statement
1677                   ;; start there too.  If cperl-indent-level is zero,
1678                   ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
1679                   ;; For open-braces not the first thing in a line,
1680                   ;; add in cperl-brace-imaginary-offset.
1681
1682                   ;; If first thing on a line:  ?????
1683                   (+ (if (and (bolp) (zerop cperl-indent-level))
1684                          (+ cperl-brace-offset cperl-continued-statement-offset)
1685                        cperl-indent-level)
1686                      ;; Move back over whitespace before the openbrace.
1687                      ;; If openbrace is not first nonwhite thing on the line,
1688                      ;; add the cperl-brace-imaginary-offset.
1689                      (progn (skip-chars-backward " \t")
1690                             (if (bolp) 0 cperl-brace-imaginary-offset))
1691                      ;; If the openbrace is preceded by a parenthesized exp,
1692                      ;; move to the beginning of that;
1693                      ;; possibly a different line
1694                      (progn
1695                        (if (eq (preceding-char) ?\))
1696                            (forward-sexp -1))
1697                        ;; In the case it starts a subroutine, indent with
1698                        ;; respect to `sub', not with respect to the the
1699                        ;; first thing on the line, say in the case of
1700                        ;; anonymous sub in a hash.
1701                        ;;
1702                        (skip-chars-backward " \t")
1703                        (if (and (eq (preceding-char) ?b)
1704                                 (progn
1705                                   (forward-word -1)
1706                                   (looking-at "sub\\>"))
1707                                 (setq old-indent 
1708                                       (nth 1 
1709                                            (parse-partial-sexp 
1710                                             (save-excursion (beginning-of-line) (point)) 
1711                                             (point)))))
1712                            (progn (goto-char (1+ old-indent))
1713                                   (skip-chars-forward " \t")
1714                                   (current-column))
1715                          ;; Get initial indentation of the line we are on.
1716                          ;; If line starts with label, calculate label indentation
1717                          (if (save-excursion
1718                                (beginning-of-line)
1719                                (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_]*:[^:]"))
1720                              (if (> (current-indentation) cperl-min-label-indent)
1721                                  (- (current-indentation) cperl-label-offset)
1722                                (cperl-calculate-indent 
1723                                 (if (and parse-start (<= parse-start (point)))
1724                                     parse-start)))
1725                            (current-indentation)))))))))))))
1726
1727 (defvar cperl-indent-alist
1728   '((string nil)
1729     (comment nil)
1730     (toplevel 0)
1731     (toplevel-after-parenth 2)
1732     (toplevel-continued 2)
1733     (expression 1))
1734   "Alist of indentation rules for CPerl mode.
1735 The values mean:
1736   nil: do not indent;
1737   number: add this amount of indentation.")
1738
1739 (defun cperl-where-am-i (&optional parse-start start-state)
1740   ;; Unfinished
1741   "Return a list of lists ((TYPE POS)...) of good points before the point.
1742 POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'."
1743   (save-excursion
1744     (let* ((start-point (point))
1745            (s-s (cperl-get-state))
1746            (start (nth 0 s-s))
1747            (state (nth 1 s-s))
1748            (prestart (nth 3 s-s))
1749            (containing-sexp (car (cdr state)))
1750            (case-fold-search nil)
1751            (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
1752       (cond ((nth 3 state)              ; In string
1753              (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
1754             ((nth 4 state)              ; In comment
1755              (setq res (cons '(comment) res)))
1756             ((null containing-sexp)
1757              ;; Line is at top level.  
1758              ;; Indent like the previous top level line
1759              ;; unless that ends in a closeparen without semicolon,
1760              ;; in which case this line is the first argument decl.
1761              (cperl-backward-to-noncomment (or parse-start (point-min)))
1762              ;;(skip-chars-backward " \t\f\n")
1763              (cond
1764               ((or (bobp)
1765                    (memq (preceding-char) (append ";}" nil)))
1766                (setq res (cons (list 'toplevel start) res)))
1767               ((eq (preceding-char) ?\) )
1768                (setq res (cons (list 'toplevel-after-parenth start) res)))
1769               (t 
1770                (setq res (cons (list 'toplevel-continued start) res)))))
1771             ((/= (char-after containing-sexp) ?{)
1772              ;; line is expression, not statement:
1773              ;; indent to just after the surrounding open.
1774              ;; skip blanks if we do not close the expression.
1775              (setq res (cons (list 'expression-blanks
1776                                    (progn
1777                                      (goto-char (1+ containing-sexp))
1778                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
1779                                          (skip-chars-forward " \t"))
1780                                      (point)))
1781                              (cons (list 'expression containing-sexp) res))))
1782             ((progn
1783               ;; Containing-expr starts with \{. Check whether it is a hash.
1784               (goto-char containing-sexp)
1785               (not (cperl-block-p)))
1786              (setq res (cons (list 'expression-blanks
1787                                    (progn
1788                                      (goto-char (1+ containing-sexp))
1789                                      (or (looking-at "[ \t]*\\(#\\|$\\)")
1790                                          (skip-chars-forward " \t"))
1791                                      (point)))
1792                              (cons (list 'expression containing-sexp) res))))
1793             (t
1794              ;; Statement level.
1795              (setq res (cons (list 'in-block containing-sexp) res))
1796              ;; Is it a continuation or a new statement?
1797              ;; Find previous non-comment character.
1798              (cperl-backward-to-noncomment containing-sexp)
1799              ;; Back up over label lines, since they don't
1800              ;; affect whether our line is a continuation.
1801              ;; Back up comma-delimited lines too ?????
1802              (while (or (eq (preceding-char) ?\,)
1803                         (save-excursion (cperl-after-label)))
1804                (if (eq (preceding-char) ?\,)
1805                    ;; Will go to beginning of line, essentially
1806                      ;; Will ignore embedded sexpr XXXX.
1807                    (cperl-backward-to-start-of-continued-exp containing-sexp))
1808                (beginning-of-line)
1809                (cperl-backward-to-noncomment containing-sexp))
1810              ;; Now we get the answer.
1811              (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
1812                  ;; This line is continuation of preceding line's statement.
1813                  (list (list 'statement-continued containing-sexp))
1814                ;; This line starts a new statement.
1815                ;; Position following last unclosed open.
1816                (goto-char containing-sexp)
1817                ;; Is line first statement after an open-brace?
1818                (or
1819                 ;; If no, find that first statement and indent like
1820                 ;; it.  If the first statement begins with label, do
1821                 ;; not belive when the indentation of the label is too
1822                 ;; small.
1823                 (save-excursion
1824                   (forward-char 1)
1825                   (let ((colon-line-end 0))
1826                     (while (progn (skip-chars-forward " \t\n" start-point)
1827                                   (and (< (point) start-point)
1828                                        (looking-at
1829                                         "#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
1830                       ;; Skip over comments and labels following openbrace.
1831                       (cond ((= (following-char) ?\#)
1832                              ;;(forward-line 1)
1833                              (end-of-line))
1834                             ;; label:
1835                             (t
1836                              (save-excursion (end-of-line)
1837                                              (setq colon-line-end (point)))
1838                              (search-forward ":"))))
1839                     ;; Now at the point, after label, or at start 
1840                     ;; of first statement in the block.
1841                     (and (< (point) start-point)
1842                          (if (> colon-line-end (point)) 
1843                              ;; Before statement after label
1844                              (if (> (current-indentation) 
1845                                     cperl-min-label-indent)
1846                                  (list (list 'label-in-block (point)))
1847                                ;; Do not belive: `max' is involved
1848                                (list
1849                                 (list 'label-in-block-min-indent (point))))
1850                            ;; Before statement
1851                            (list 'statement-in-block (point))))))
1852                 ;; If no previous statement,
1853                 ;; indent it relative to line brace is on.
1854                 ;; For open brace in column zero, don't let statement
1855                 ;; start there too.  If cperl-indent-level is zero,
1856                 ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
1857                 ;; For open-braces not the first thing in a line,
1858                 ;; add in cperl-brace-imaginary-offset.
1859
1860                 ;; If first thing on a line:  ?????
1861                 (+ (if (and (bolp) (zerop cperl-indent-level))
1862                        (+ cperl-brace-offset cperl-continued-statement-offset)
1863                      cperl-indent-level)
1864                    ;; Move back over whitespace before the openbrace.
1865                    ;; If openbrace is not first nonwhite thing on the line,
1866                    ;; add the cperl-brace-imaginary-offset.
1867                    (progn (skip-chars-backward " \t")
1868                           (if (bolp) 0 cperl-brace-imaginary-offset))
1869                    ;; If the openbrace is preceded by a parenthesized exp,
1870                    ;; move to the beginning of that;
1871                    ;; possibly a different line
1872                    (progn
1873                      (if (eq (preceding-char) ?\))
1874                          (forward-sexp -1))
1875                      ;; Get initial indentation of the line we are on.
1876                      ;; If line starts with label, calculate label indentation
1877                      (if (save-excursion
1878                            (beginning-of-line)
1879                            (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_]*:[^:]"))
1880                          (if (> (current-indentation) cperl-min-label-indent)
1881                              (- (current-indentation) cperl-label-offset)
1882                            (cperl-calculate-indent 
1883                             (if (and parse-start (<= parse-start (point)))
1884                                 parse-start)))
1885                        (current-indentation))))))))
1886       res)))
1887
1888 (defun cperl-calculate-indent-within-comment ()
1889   "Return the indentation amount for line, assuming that
1890 the current line is to be regarded as part of a block comment."
1891   (let (end star-start)
1892     (save-excursion
1893       (beginning-of-line)
1894       (skip-chars-forward " \t")
1895       (setq end (point))
1896       (and (= (following-char) ?#)
1897            (forward-line -1)
1898            (cperl-to-comment-or-eol)
1899            (setq end (point)))
1900       (goto-char end)
1901       (current-column))))
1902
1903
1904 (defun cperl-to-comment-or-eol ()
1905   "Goes to position before comment on the current line, or to end of line.
1906 Returns true if comment is found."
1907   (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
1908       (beginning-of-line)
1909       (if (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t) 
1910           (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
1911         ;; Else
1912         (while (not stop-in)
1913           (setq state (parse-partial-sexp (point) lim nil nil nil t))
1914                                         ; stop at comment
1915           ;; If fails (beginning-of-line inside sexp), then contains not-comment
1916           ;; Do simplified processing
1917           ;;(if (re-search-forward "[^$]#" lim 1)
1918           ;;      (progn
1919           ;;    (forward-char -1)
1920           ;;    (skip-chars-backward " \t\n\f" lim))
1921           ;;    (goto-char lim))                ; No `#' at all
1922           ;;)
1923           (if (nth 4 state)             ; After `#';
1924                                         ; (nth 2 state) can be
1925                                         ; beginning of m,s,qq and so
1926                                         ; on
1927               (if (nth 2 state)
1928                   (progn
1929                     (setq cpoint (point))
1930                     (goto-char (nth 2 state))
1931                     (cond
1932                      ((looking-at "\\(s\\|tr\\)\\>")
1933                       (or (re-search-forward
1934                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
1935                            lim 'move)
1936                           (setq stop-in t)))
1937                      ((looking-at "\\(m\\|q\\([qxw]\\)?\\)\\>")
1938                       (or (re-search-forward
1939                            "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
1940                            lim 'move)
1941                           (setq stop-in t)))
1942                      (t                 ; It was fair comment
1943                       (setq stop-in t)  ; Finish
1944                       (goto-char (1- cpoint)))))
1945                 (setq stop-in t)        ; Finish
1946                 (forward-char -1))
1947             (setq stop-in t))           ; Finish
1948           )
1949         (nth 4 state))))
1950
1951 (defun cperl-find-pods-heres (&optional min max)
1952   "Scans the buffer for POD sections and here-documents.
1953 If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify 
1954 the sections using `cperl-pod-head-face', `cperl-pod-face', 
1955 `cperl-here-face'."
1956   (interactive)
1957   (or min (setq min (point-min)))
1958   (or max (setq max (point-max)))
1959   (let (face head-face here-face b e bb tag err
1960              (cperl-pod-here-fontify (eval cperl-pod-here-fontify))
1961              (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
1962              (modified (buffer-modified-p))
1963              (after-change-functions nil))
1964     (unwind-protect
1965         (progn
1966           (save-excursion
1967             (message "Scanning for pods and here-docs...")
1968             (if cperl-pod-here-fontify
1969                 (setq face (eval cperl-pod-face) 
1970                       head-face (eval cperl-pod-head-face)
1971                       here-face (eval cperl-here-face)))
1972             (remove-text-properties min max '(syntax-type t))
1973             ;; Need to remove face as well...
1974             (goto-char min)
1975             (while (re-search-forward "\\(\\`\n?\\|\n\n\\)=" max t)
1976               (if (looking-at "\n*cut\\>")
1977                   (progn
1978                     (message "=cut is not preceeded by a pod section")
1979                     (setq err (point)))
1980                 (beginning-of-line)
1981                 
1982                 (setq b (point) bb b)
1983                 (or (re-search-forward "\n\n=cut\\>" max 'toend)
1984                     (message "Cannot find the end of a pod section"))
1985                 (beginning-of-line 3)
1986                 (setq e (point))
1987                 (put-text-property b e 'in-pod t)
1988                 (goto-char b)
1989                 (while (re-search-forward "\n\n[ \t]" e t)
1990                   (beginning-of-line)
1991                   (put-text-property b (point) 'syntax-type 'pod)
1992                   (cperl-put-do-not-fontify b (point))
1993                   ;;(put-text-property (max (point-min) (1- b))
1994                   ;;                 (point) cperl-do-not-fontify t)
1995                   (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
1996                   (re-search-forward "\n\n[^ \t\f]" e 'toend)
1997                   (beginning-of-line)
1998                   (setq b (point)))
1999                 (put-text-property (point) e 'syntax-type 'pod)
2000                 (cperl-put-do-not-fontify (point) e)
2001                 ;;(put-text-property (max (point-min) (1- (point)))
2002                 ;;                 e cperl-do-not-fontify t)
2003                 (if cperl-pod-here-fontify 
2004                     (progn (put-text-property (point) e 'face face)
2005                            (goto-char bb)
2006                            (if (looking-at 
2007                             "=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
2008                                (put-text-property 
2009                                 (match-beginning 1) (match-end 1)
2010                                 'face head-face))
2011                            (while (re-search-forward
2012                                    ;; One paragraph
2013                                    "\n\n=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
2014                                    e 'toend)
2015                              (put-text-property 
2016                               (match-beginning 1) (match-end 1)
2017                               'face head-face))))
2018                 (goto-char e)))
2019             (goto-char min)
2020             (while (re-search-forward 
2021                     "<<\\(\\([\"'`]\\)?\\)\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\1"
2022                     max t)
2023               (setq tag (buffer-substring (match-beginning 3)
2024                                           (match-end 3)))
2025               (if cperl-pod-here-fontify 
2026                   (put-text-property (match-beginning 3) (match-end 3) 
2027                                      'face font-lock-reference-face))
2028               (forward-line)
2029               (setq b (point))
2030               (and (re-search-forward (concat "^" tag "$") max 'toend)
2031                    (progn
2032                      (if cperl-pod-here-fontify 
2033                          (progn
2034                            (put-text-property (match-beginning 0) (match-end 0) 
2035                                               'face font-lock-reference-face)
2036                            (cperl-put-do-not-fontify b (match-end 0))
2037                            ;;(put-text-property (max (point-min) (1- b))
2038                            ;;                 (min (point-max)
2039                            ;;                      (1+ (match-end 0)))
2040                            ;;                 cperl-do-not-fontify t)
2041                            (put-text-property b (match-beginning 0) 
2042                                               'face here-face)))
2043                      (put-text-property b (match-beginning 0) 
2044                                         'syntax-type 'here-doc)))))
2045           (if err (goto-char err)
2046             (message "Scan for pods and here-docs completed.")))
2047       (and (buffer-modified-p)
2048            (not modified)
2049            (set-buffer-modified-p nil)))))
2050
2051 (defun cperl-backward-to-noncomment (lim)
2052   ;; Stops at lim or after non-whitespace that is not in comment
2053   (let (stop p)
2054     (while (and (not stop) (> (point) (or lim 1)))
2055       (skip-chars-backward " \t\n\f" lim)
2056       (setq p (point))
2057       (beginning-of-line)
2058       (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
2059         ;; Else
2060         (cperl-to-comment-or-eol) 
2061         (skip-chars-backward " \t")
2062         (if (< p (point)) (goto-char p))
2063         (setq stop t)))))
2064
2065 (defun cperl-after-expr-p (&optional lim chars test)
2066   "Returns true if the position is good for start of expression.
2067 TEST is the expression to evaluate at the found position. If absent,
2068 CHARS is a string that contains good characters to have before us."
2069   (let (stop p)
2070     (save-excursion
2071       (while (and (not stop) (> (point) (or lim 1)))
2072         (skip-chars-backward " \t\n\f" lim)
2073         (setq p (point))
2074         (beginning-of-line)
2075         (if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
2076           ;; Else: last iteration (What to do with labels?)
2077           (cperl-to-comment-or-eol) 
2078           (skip-chars-backward " \t")
2079           (if (< p (point)) (goto-char p))
2080           (setq stop t)))
2081       (or (bobp)
2082           (progn
2083             (backward-char 1)
2084             (if test (eval test)
2085               (memq (following-char) (append (or chars "{};") nil))))))))
2086
2087 (defun cperl-backward-to-start-of-continued-exp (lim)
2088   (if (memq (preceding-char) (append ")]}\"'`" nil))
2089       (forward-sexp -1))
2090   (beginning-of-line)
2091   (if (<= (point) lim)
2092       (goto-char (1+ lim)))
2093   (skip-chars-forward " \t"))
2094
2095 \f
2096 (defvar innerloop-done nil)
2097 (defvar last-depth nil)
2098
2099 (defun cperl-indent-exp ()
2100   "Simple variant of indentation of continued-sexp.
2101 Should be slow. Will not indent comment if it starts at `comment-indent'
2102 or looks like continuation of the comment on the previous line."
2103   (interactive)
2104   (save-excursion
2105     (let ((tmp-end (progn (end-of-line) (point))) top done)
2106       (save-excursion
2107         (while (null done)
2108           (beginning-of-line)
2109           (setq top (point))
2110           (while (= (nth 0 (parse-partial-sexp (point) tmp-end
2111                                                -1)) -1)
2112             (setq top (point)))         ; Get the outermost parenths in line
2113           (goto-char top)
2114           (while (< (point) tmp-end)
2115             (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
2116             (or (eolp) (forward-sexp 1)))
2117           (if (> (point) tmp-end) (progn (end-of-line) (setq tmp-end (point)))
2118             (setq done t)))
2119         (goto-char tmp-end)
2120         (setq tmp-end (point-marker)))
2121       (cperl-indent-region (point) tmp-end))))
2122
2123 (defun cperl-indent-region (start end)
2124   "Simple variant of indentation of region in CPerl mode.
2125 Should be slow. Will not indent comment if it starts at `comment-indent' 
2126 or looks like continuation of the comment on the previous line.
2127 Indents all the lines whose first character is between START and END 
2128 inclusive."
2129   (interactive "r")
2130   (save-excursion
2131     (let (st comm indent-info old-comm-indent new-comm-indent 
2132              (pm 0) (imenu-scanning-message "Indenting... (%3d%%)"))
2133       (goto-char start)
2134       (setq old-comm-indent (and (cperl-to-comment-or-eol)
2135                                  (current-column))
2136             new-comm-indent old-comm-indent)
2137       (goto-char start)
2138       (or (bolp) (beginning-of-line 2))
2139       (or (fboundp 'imenu-progress-message)
2140           (message "Indenting... For feedback load `imenu'..."))
2141       (while (and (<= (point) end) (not (eobp))) ; bol to check start
2142         (and (fboundp 'imenu-progress-message)
2143              (imenu-progress-message 
2144               pm (/ (* 100 (- (point) start)) (- end start -1))))
2145         (setq st (point) 
2146               indent-info nil
2147               ) ; Believe indentation of the current
2148         (if (and (setq comm (looking-at "[ \t]*#"))
2149                  (or (eq (current-indentation) (or old-comm-indent 
2150                                                    comment-column))
2151                      (setq old-comm-indent nil)))
2152             (if (and old-comm-indent
2153                      (= (current-indentation) old-comm-indent))
2154                 (let ((comment-column new-comm-indent))
2155                   (indent-for-comment)))
2156           (progn 
2157             (cperl-indent-line 'indent-info)
2158             (or comm
2159                 (progn
2160                   (if (setq old-comm-indent (and (cperl-to-comment-or-eol)
2161                                                  (current-column)))
2162                       (progn (indent-for-comment)
2163                              (skip-chars-backward " \t")
2164                              (skip-chars-backward "#")
2165                              (setq new-comm-indent (current-column))))))))
2166         (beginning-of-line 2))
2167         (if (fboundp 'imenu-progress-message)
2168              (imenu-progress-message pm 100)
2169           (message nil)))))
2170
2171 (defun cperl-slash-is-regexp (&optional pos)
2172   (save-excursion
2173     (goto-char (if pos pos (1- (point))))
2174     (and
2175      (not (memq (get-text-property (point) 'face)
2176                 '(font-lock-string-face font-lock-comment-face)))
2177      (cperl-after-expr-p nil nil '
2178                        (or (looking-at "[^]a-zA-Z0-9_)}]")
2179                            (eq (get-text-property (point) 'face)
2180                                'font-lock-keyword-face))))))
2181
2182 ;; Stolen from lisp-mode with a lot of improvements
2183
2184 (defun cperl-fill-paragraph (&optional justify iteration)
2185   "Like \\[fill-paragraph], but handle CPerl comments.
2186 If any of the current line is a comment, fill the comment or the
2187 block of it that point is in, preserving the comment's initial
2188 indentation and initial hashes. Behaves usually outside of comment."
2189   (interactive "P")
2190   (let (
2191         ;; Non-nil if the current line contains a comment.
2192         has-comment
2193
2194         ;; If has-comment, the appropriate fill-prefix for the comment.
2195         comment-fill-prefix
2196         ;; Line that contains code and comment (or nil)
2197         start
2198         c spaces len dc (comment-column comment-column))
2199     ;; Figure out what kind of comment we are looking at.
2200     (save-excursion
2201       (beginning-of-line)
2202       (cond
2203
2204        ;; A line with nothing but a comment on it?
2205        ((looking-at "[ \t]*#[# \t]*")
2206         (setq has-comment t
2207               comment-fill-prefix (buffer-substring (match-beginning 0)
2208                                                     (match-end 0))))
2209
2210        ;; A line with some code, followed by a comment?  Remember that the
2211        ;; semi which starts the comment shouldn't be part of a string or
2212        ;; character.
2213        ((cperl-to-comment-or-eol)
2214         (setq has-comment t)
2215         (looking-at "#+[ \t]*")
2216         (setq start (point) c (current-column) 
2217               comment-fill-prefix
2218               (concat (make-string (current-column) ?\ )
2219                       (buffer-substring (match-beginning 0) (match-end 0)))
2220               spaces (progn (skip-chars-backward " \t") 
2221                             (buffer-substring (point) start))
2222               dc (- c (current-column)) len (- start (point)) 
2223               start (point-marker))
2224         (delete-char len)
2225         (insert (make-string dc ?-)))))
2226     (if (not has-comment)
2227         (fill-paragraph justify)        ; Do the usual thing outside of comment
2228       ;; Narrow to include only the comment, and then fill the region.
2229       (save-restriction
2230         (narrow-to-region
2231          ;; Find the first line we should include in the region to fill.
2232          (if start (progn (beginning-of-line) (point))
2233            (save-excursion
2234              (while (and (zerop (forward-line -1))
2235                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
2236              ;; We may have gone to far.  Go forward again.
2237              (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
2238                  (forward-line 1))
2239              (point)))
2240          ;; Find the beginning of the first line past the region to fill.
2241          (save-excursion
2242            (while (progn (forward-line 1)
2243                          (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
2244            (point)))
2245         ;; Remove existing hashes
2246         (goto-char (point-min))
2247         (while (progn (forward-line 1) (< (point) (point-max)))
2248           (skip-chars-forward " \t")
2249           (and (looking-at "#+") 
2250                (delete-char (- (match-end 0) (match-beginning 0)))))
2251
2252         ;; Lines with only hashes on them can be paragraph boundaries.
2253         (let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
2254               (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
2255               (fill-prefix comment-fill-prefix))
2256           (fill-paragraph justify)))
2257       (if (and start)
2258           (progn 
2259             (goto-char start)
2260             (if (> dc 0)
2261               (progn (delete-char dc) (insert spaces)))
2262             (if (or (= (current-column) c) iteration) nil
2263               (setq comment-column c)
2264               (indent-for-comment)
2265               ;; Repeat once more, flagging as iteration
2266               (cperl-fill-paragraph justify t)))))))
2267
2268 (defun cperl-do-auto-fill ()
2269   ;; Break out if the line is short enough
2270   (if (> (save-excursion
2271            (end-of-line)
2272            (current-column))
2273          fill-column)
2274   (let ((c (save-excursion (beginning-of-line)
2275                            (cperl-to-comment-or-eol) (point)))
2276         (s (memq (following-char) '(?\ ?\t))) marker)
2277     (if (>= c (point)) nil
2278       (setq marker (point-marker))
2279       (cperl-fill-paragraph)
2280       (goto-char marker)
2281       ;; Is not enough, sometimes marker is a start of line
2282       (if (bolp) (progn (re-search-forward "#+[ \t]*") 
2283                         (goto-char (match-end 0))))
2284       ;; Following space could have gone:
2285       (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
2286         (insert " ")
2287         (backward-char 1))
2288       ;; Previous space could have gone:
2289       (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))
2290
2291 (defvar imenu-example--function-name-regexp-perl
2292       "^\\([ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*\\|=head\\([12]\\)[ \t]+\\([^\n]+\\)$\\)")
2293
2294 (defun cperl-imenu-addback (lst &optional isback name)
2295   ;; We suppose that the lst is a DAG, unless the first element only
2296   ;; loops back, and ISBACK is set. Thus this function cannot be
2297   ;; applied twice without ISBACK set.
2298   (cond ((not cperl-imenu-addback) lst)
2299         (t
2300          (or name 
2301              (setq name "+++BACK+++"))
2302          (mapcar (function (lambda (elt)
2303                              (if (and (listp elt) (listp (cdr elt)))
2304                                  (progn
2305                                    ;; In the other order it goes up
2306                                    ;; one level only ;-(
2307                                    (setcdr elt (cons (cons name lst)
2308                                                      (cdr elt)))
2309                                    (cperl-imenu-addback (cdr elt) t name)
2310                                    ))))
2311                  (if isback (cdr lst) lst))
2312          lst)))
2313
2314 (defun imenu-example--create-perl-index (&optional regexp)
2315   (require 'cl)
2316   (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '()) 
2317         (index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
2318         (index-meth-alist '()) meth
2319         packages ends-ranges p
2320         (prev-pos 0) char fchar index index1 name (end-range 0) package)
2321     (goto-char (point-min))
2322     (imenu-progress-message prev-pos 0)
2323     ;; Search for the function
2324     (progn ;;save-match-data
2325       (while (re-search-forward
2326               (or regexp imenu-example--function-name-regexp-perl)
2327               nil t)
2328         (imenu-progress-message prev-pos)
2329         ;;(backward-up-list 1)
2330         (cond
2331          ((match-beginning 2)           ; package or sub
2332           (save-excursion
2333             (goto-char (match-beginning 2))
2334             (setq fchar (following-char))
2335             )
2336           (setq char (following-char) meth nil)
2337           (setq p (point))
2338           (while (and ends-ranges (>= p (car ends-ranges)))
2339             ;; delete obsolete entries
2340             (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
2341           (setq package (or (car packages) "")
2342                 end-range (or (car ends-ranges) 0))
2343           (if (eq fchar ?p)
2344               (setq name (buffer-substring (match-beginning 3) (match-end 3))
2345                     package (concat name "::") 
2346                     name (concat "package " name)
2347                     end-range 
2348                     (save-excursion
2349                       (parse-partial-sexp (point) (point-max) -1) (point))
2350                     ends-ranges (cons end-range ends-ranges)
2351                     packages (cons package packages)))
2352           ;;   )
2353           ;; Skip this function name if it is a prototype declaration.
2354           (if (and (eq fchar ?s) (eq char ?\;)) nil
2355             (setq index (imenu-example--name-and-position))
2356             (if (eq fchar ?p) nil
2357               (setq name (buffer-substring (match-beginning 3) (match-end 3)))
2358               (cond ((string-match "[:']" name)
2359                      (setq meth t))
2360                     ((> p end-range) nil)
2361                     (t 
2362                      (setq name (concat package name) meth t))))
2363             (setcar index name)
2364             (if (eq fchar ?p) 
2365                 (push index index-pack-alist)
2366               (push index index-alist))
2367             (if meth (push index index-meth-alist))
2368             (push index index-unsorted-alist)))
2369          (t                             ; Pod section
2370           ;; (beginning-of-line)
2371           (setq index (imenu-example--name-and-position)
2372                 name (buffer-substring (match-beginning 5) (match-end 5)))
2373           (if (eq (char-after (match-beginning 4)) ?2)
2374               (setq name (concat "   " name)))
2375           (setcar index name)
2376           (setq index1 (cons (concat "=" name) (cdr index)))
2377           (push index index-pod-alist)
2378           (push index1 index-unsorted-alist)))))
2379     (imenu-progress-message prev-pos 100)
2380     (setq index-alist 
2381           (if (default-value 'imenu-sort-function)
2382               (sort index-alist (default-value 'imenu-sort-function))
2383               (nreverse index-alist)))
2384     (and index-pod-alist
2385          (push (cons "+POD headers+..."
2386                      (nreverse index-pod-alist))
2387                index-alist))
2388     (and (or index-pack-alist index-meth-alist)
2389          (let ((lst index-pack-alist) hier-list pack elt group name)
2390            ;; Remove "package ", reverse and uniquify.
2391            (while lst
2392              (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
2393              (if (assoc name hier-list) nil
2394                (setq hier-list (cons (cons name (cdr elt)) hier-list))))
2395            (setq lst index-meth-alist)
2396            (while lst
2397              (setq elt (car lst) lst (cdr lst))
2398              (string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
2399              (setq pack (substring (car elt) 0 (match-beginning 0)))
2400              (if (setq group (assoc pack hier-list)) 
2401                  (if (listp (cdr group))
2402                      ;; Have some functions already
2403                      (setcdr group (cons (cons (substring 
2404                                                 (car elt)
2405                                                 (+ 2 (match-beginning 0)))
2406                                                (cdr elt))
2407                                          (cdr group)))
2408                    (setcdr group (list (cons (substring 
2409                                                 (car elt)
2410                                                 (+ 2 (match-beginning 0)))
2411                                                (cdr elt)))))
2412                (setq hier-list 
2413                      (cons (cons pack (list (cons (substring 
2414                                                 (car elt)
2415                                                 (+ 2 (match-beginning 0)))
2416                                                (cdr elt))))
2417                            hier-list))))
2418            (push (cons "+Hierarchy+..."
2419                        hier-list)
2420                  index-alist)))
2421     (and index-pack-alist
2422          (push (cons "+Packages+..."
2423                      (nreverse index-pack-alist))
2424                index-alist))
2425     (and (or index-pack-alist index-pod-alist 
2426              (default-value 'imenu-sort-function))
2427          index-unsorted-alist
2428          (push (cons "+Unsorted List+..."
2429                      (nreverse index-unsorted-alist))
2430                index-alist))
2431     (cperl-imenu-addback index-alist)))
2432
2433 (defvar cperl-compilation-error-regexp-alist 
2434   ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
2435   '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
2436      2 3))
2437   "Alist that specifies how to match errors in perl output.")
2438
2439 (if (fboundp 'eval-after-load)
2440     (eval-after-load
2441      "mode-compile"
2442      '(setq perl-compilation-error-regexp-alist
2443            cperl-compilation-error-regexp-alist)))
2444
2445
2446 (defvar cperl-faces-init nil)
2447
2448 (defun cperl-windowed-init ()
2449   "Initialization under windowed version."
2450   (add-hook 'font-lock-mode-hook
2451             (function
2452              (lambda ()
2453                (if (or
2454                     (eq major-mode 'perl-mode)
2455                     (eq major-mode 'cperl-mode))
2456                    (progn
2457                      (or cperl-faces-init (cperl-init-faces))))))))
2458
2459 (defvar perl-font-lock-keywords-1 nil
2460   "Additional expressions to highlight in Perl mode. Minimal set.")
2461 (defvar perl-font-lock-keywords nil
2462   "Additional expressions to highlight in Perl mode. Default set.")
2463 (defvar perl-font-lock-keywords-2 nil
2464   "Additional expressions to highlight in Perl mode. Maximal set")
2465
2466 (defun cperl-init-faces ()
2467   (condition-case nil
2468       (progn
2469         (require 'font-lock)
2470         (and (fboundp 'font-lock-fontify-anchored-keywords)
2471              (featurep 'font-lock-extra)
2472              (message "You have an obsolete package `font-lock-extra'. Install `choose-color'."))
2473         (let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
2474           ;;(defvar cperl-font-lock-enhanced nil
2475           ;;  "Set to be non-nil if font-lock allows active highlights.")
2476           (if (fboundp 'font-lock-fontify-anchored-keywords)
2477               (setq font-lock-anchored t))
2478           (setq 
2479            t-font-lock-keywords
2480            (list
2481             (cons
2482              (concat
2483               "\\(^\\|[^$@%&\\]\\)\\<\\("
2484               (mapconcat
2485                'identity
2486                '("if" "until" "while" "elsif" "else" "unless" "for"
2487                  "foreach" "continue" "exit" "die" "last" "goto" "next"
2488                  "redo" "return" "local" "exec" "sub" "do" "dump" "use"
2489                  "require" "package" "eval" "my" "BEGIN" "END")
2490                "\\|")                   ; Flow control
2491               "\\)\\>") 2)              ; was "\\)[ \n\t;():,\|&]"
2492                                         ; In what follows we use `type' style
2493                                         ; for overwritable buildins
2494             (list
2495              (concat
2496               "\\(^\\|[^$@%&\\]\\)\\<\\("
2497               ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm" "and" "atan2"
2498               ;; "bind" "binmode" "bless" "caller" "chdir" "chmod" "chown" "chr"
2499               ;; "chroot" "close" "closedir" "cmp" "connect" "continue" "cos"
2500               ;; "crypt" "dbmclose" "dbmopen" "die" "dump" "endgrent" "endhostent"
2501               ;; "endnetent" "endprotoent" "endpwent" "endservent" "eof" "eq" "exec"
2502               ;; "exit" "exp" "fcntl" "fileno" "flock" "fork" "formline" "ge" "getc"
2503               ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr" "gethostbyname"
2504               ;; "gethostent" "getlogin" "getnetbyaddr" "getnetbyname" "getnetent"
2505               ;; "getpeername" "getpgrp" "getppid" "getpriority" "getprotobyname"
2506               ;; "getprotobynumber" "getprotoent" "getpwent" "getpwnam" "getpwuid"
2507               ;; "getservbyname" "getservbyport" "getservent" "getsockname"
2508               ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int" "ioctl"
2509               ;; "join" "kill" "lc" "lcfirst" "le" "length" "link" "listen"
2510               ;; "localtime" "log" "lstat" "lt" "mkdir" "msgctl" "msgget" "msgrcv"
2511               ;; "msgsnd" "ne" "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
2512               ;; "quotemeta" "rand" "read" "readdir" "readline" "readlink"
2513               ;; "readpipe" "recv" "ref" "rename" "require" "reset" "reverse"
2514               ;; "rewinddir" "rindex" "rmdir" "seek" "seekdir" "select" "semctl"
2515               ;; "semget" "semop" "send" "setgrent" "sethostent" "setnetent"
2516               ;; "setpgrp" "setpriority" "setprotoent" "setpwent" "setservent"
2517               ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite" "shutdown"
2518               ;; "sin" "sleep" "socket" "socketpair" "sprintf" "sqrt" "srand" "stat"
2519               ;; "substr" "symlink" "syscall" "sysread" "system" "syswrite" "tell"
2520               ;; "telldir" "time" "times" "truncate" "uc" "ucfirst" "umask" "unlink"
2521               ;; "unpack" "utime" "values" "vec" "wait" "waitpid" "wantarray" "warn"
2522               ;; "write" "x" "xor"
2523               "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|" 
2524               "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
2525               "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
2526               "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
2527               "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
2528               "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
2529               "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
2530               "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
2531               "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
2532               "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
2533               "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
2534               "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
2535               "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
2536               "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
2537               "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
2538               "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
2539               "\\(\\|ngth\\)\\|o\\(caltime\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
2540               "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
2541               "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
2542               "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
2543               "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
2544               "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
2545               "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
2546               "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
2547               "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
2548               "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|tem\\|write\\)\\|"
2549               "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
2550               "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
2551               "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
2552               "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
2553               "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\)"
2554               "\\)\\>") 2 'font-lock-type-face)
2555             ;; In what follows we use `other' style
2556             ;; for nonoverwritable buildins
2557             ;; Somehow 's', 'm' are not autogenerated???
2558             (list
2559              (concat
2560               "\\(^\\|[^$@%&\\]\\)\\<\\("
2561               ;; "AUTOLOAD" "BEGIN" "DESTROY" "END" "__END__" "chomp" "chop"
2562               ;; "defined" "delete" "do" "each" "else" "elsif" "eval" "exists" "for"
2563               ;; "foreach" "format" "goto" "grep" "if" "keys" "last" "local" "map"
2564               ;; "my" "next" "no" "package" "pop" "pos" "print" "printf" "push" "q"
2565               ;; "qq" "qw" "qx" "redo" "return" "scalar" "shift" "sort" "splice"
2566               ;; "split" "study" "sub" "tie" "tr" "undef" "unless" "unshift" "untie"
2567               ;; "until" "use" "while" "y"
2568               "AUTOLOAD\\|BEGIN\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
2569               "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
2570               "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|if\\|keys\\|"
2571               "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|"
2572               "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
2573               "q\\(\\|q\\|w\\|x\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
2574               "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
2575               "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
2576               "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
2577               "\\|[sm]"                 ; Added manually
2578               "\\)\\>") 2 'font-lock-other-type-face)
2579             ;;          (mapconcat 'identity
2580             ;;                     '("#endif" "#else" "#ifdef" "#ifndef" "#if"
2581             ;;                       "#include" "#define" "#undef")
2582             ;;                     "\\|")
2583             '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
2584               font-lock-function-name-face) ; Not very good, triggers at "[a-z]"
2585             '("\\<sub[ \t]+\\([^ \t{;]+\\)[ \t]*[{\n]" 1
2586               font-lock-function-name-face)
2587             '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
2588               2 font-lock-function-name-face)
2589             (cond ((featurep 'font-lock-extra)
2590                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}" 
2591                      (2 font-lock-string-face t)
2592                      (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
2593                   (font-lock-anchored
2594                    '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
2595                      (2 font-lock-string-face t)
2596                      ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
2597                       nil nil
2598                       (1 font-lock-string-face t))))
2599                   (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
2600                        2 font-lock-string-face t)))
2601             '("[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
2602               font-lock-string-face t)
2603             '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1 
2604               font-lock-reference-face) ; labels
2605             '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
2606               2 font-lock-reference-face)
2607             (cond ((featurep 'font-lock-extra)
2608                    '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
2609                      (3 font-lock-variable-name-face)
2610                      (4 '(another 4 nil
2611                                   ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
2612                                    (1 font-lock-variable-name-face)
2613                                    (2 '(restart 2 nil) nil t))) 
2614                         nil t)))        ; local variables, multiple
2615                   (font-lock-anchored
2616                    '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
2617                      (3 font-lock-variable-name-face)
2618                      ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)"
2619                       nil nil
2620                       (1 font-lock-variable-name-face))))
2621                   (t '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
2622                        3 font-lock-variable-name-face)))
2623             '("\\<for\\(each\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
2624               2 font-lock-variable-name-face)))
2625           (setq 
2626            t-font-lock-keywords-1
2627            (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
2628                 (not (cperl-xemacs-p)) ; not yet as of XEmacs 19.12
2629                 '(("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
2630                    1
2631                    (if (= (- (match-end 2) (match-beginning 2)) 1) 
2632                        (if (eq (char-after (match-beginning 3)) ?{)
2633                            font-lock-other-emphasized-face
2634                          font-lock-emphasized-face) ; arrays and hashes
2635                      font-lock-variable-name-face) ; Just to put something
2636                    t)
2637                   ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
2638                    (if (eq (char-after (match-beginning 2)) ?%)
2639                        font-lock-other-emphasized-face
2640                      font-lock-emphasized-face)
2641                    t)                   ; arrays and hashes
2642                   ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
2643                        ;;; Too much noise from \s* @s[ and friends
2644                   ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)" 
2645                   ;;(3 font-lock-function-name-face t t)
2646                   ;;(4
2647                   ;; (if (cperl-slash-is-regexp)
2648                   ;;    font-lock-function-name-face 'default) nil t))
2649                   )))
2650           (setq perl-font-lock-keywords-1 t-font-lock-keywords
2651                 perl-font-lock-keywords perl-font-lock-keywords-1
2652                 perl-font-lock-keywords-2 (append
2653                                            t-font-lock-keywords
2654                                            t-font-lock-keywords-1)))
2655         (if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
2656         (if (or (featurep 'choose-color) (featurep 'font-lock-extra))
2657             (font-lock-require-faces
2658              (list
2659               ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
2660               (list 'font-lock-comment-face
2661                     ["Firebrick"        "OrangeRed"     "DimGray"       "Gray80"]
2662                     nil
2663                     [nil                nil             t               t       t]
2664                     [nil                nil             t               t       t]
2665                     nil)
2666               (list 'font-lock-string-face
2667                     ["RosyBrown"        "LightSalmon"   "Gray50"        "LightGray"]
2668                     nil
2669                     nil
2670                     [nil                nil             t               t       t]
2671                     nil)
2672               (list 'font-lock-keyword-face
2673                     ["Purple"           "LightSteelBlue" "DimGray"      "Gray90"]
2674                     nil
2675                     [nil                nil             t               t       t]
2676                     nil
2677                     nil)
2678               (list 'font-lock-function-name-face
2679                     (vector
2680                      "Blue"             "LightSkyBlue"  "Gray50"        "LightGray"
2681                      (cdr (assq 'background-color ; if mono
2682                                 (frame-parameters))))
2683                     (vector
2684                      nil                nil             nil             nil
2685                      (cdr (assq 'foreground-color ; if mono
2686                                 (frame-parameters))))
2687                     [nil                nil             t               t       t]
2688                     nil
2689                     nil)
2690               (list 'font-lock-variable-name-face
2691                     ["DarkGoldenrod"    "LightGoldenrod" "DimGray"      "Gray90"]
2692                     nil
2693                     [nil                nil             t               t       t]
2694                     [nil                nil             t               t       t]
2695                     nil)
2696               (list 'font-lock-type-face
2697                     ["DarkOliveGreen"   "PaleGreen"     "DimGray"       "Gray80"]
2698                     nil
2699                     [nil                nil             t               t       t]
2700                     nil
2701                     [nil                nil             t               t       t]
2702                     )
2703               (list 'font-lock-reference-face
2704                     ["CadetBlue"        "Aquamarine"    "Gray50"        "LightGray"]
2705                     nil
2706                     [nil                nil             t               t       t]
2707                     nil
2708                     [nil                nil             t               t       t]
2709                     )
2710               (list 'font-lock-other-type-face
2711                     ["chartreuse3"      ("orchid1" "orange")
2712                      nil                "Gray80"]
2713                     [nil                nil             "gray90"]
2714                     [nil                nil             nil             t       t]
2715                     [nil                nil             t               t]
2716                     [nil                nil             t               t       t]
2717                     )
2718               (list 'font-lock-emphasized-face
2719                     ["blue"             "yellow"        nil             "Gray80"]
2720                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
2721                      "gray90"]
2722                     t
2723                     nil
2724                     nil)
2725               (list 'font-lock-other-emphasized-face
2726                     ["red"              "red"           nil             "Gray80"]
2727                     ["lightyellow2"     ("navy" "os2blue" "darkgreen")
2728                      "gray90"]
2729                     t
2730                     t
2731                     nil)))
2732           (defvar cperl-guessed-background nil
2733             "Display characteristics as guessed by cperl.")
2734           (or (fboundp 'x-color-defined-p)
2735               (defalias 'x-color-defined-p 
2736                 (cond ((fboundp 'color-defined-p) 'color-defined-p)
2737                       ;; XEmacs >= 19.12
2738                       ((fboundp 'valid-color-name-p) 'valid-color-name-p)
2739                       ;; XEmacs 19.11
2740                       (t 'x-valid-color-name-p))))
2741           (defvar font-lock-reference-face 'font-lock-reference-face)
2742           (defvar font-lock-variable-name-face 'font-lock-variable-name-face)
2743           (or (boundp 'font-lock-type-face)
2744               (defconst font-lock-type-face
2745                 'font-lock-type-face
2746                 "Face to use for data types.")
2747               )
2748           (or (boundp 'font-lock-other-type-face)
2749               (defconst font-lock-other-type-face
2750                 'font-lock-other-type-face
2751                 "Face to use for data types from another group.")
2752               )
2753           (if (not (cperl-xemacs-p)) nil
2754             (or (boundp 'font-lock-comment-face)
2755                 (defconst font-lock-comment-face
2756                   'font-lock-comment-face
2757                   "Face to use for comments.")
2758                 )
2759             (or (boundp 'font-lock-keyword-face)
2760                 (defconst font-lock-keyword-face
2761                   'font-lock-keyword-face
2762                   "Face to use for keywords.")
2763                 )
2764             (or (boundp 'font-lock-function-name-face)
2765                 (defconst font-lock-function-name-face
2766                   'font-lock-function-name-face
2767                   "Face to use for function names.")
2768                 )
2769             )
2770           ;;(if (featurep 'font-lock)
2771           (if (face-equal font-lock-type-face font-lock-comment-face)
2772               (defconst font-lock-type-face
2773                 'font-lock-type-face
2774                 "Face to use for basic data types.")
2775             )
2776 ;;;       (if (fboundp 'eval-after-load)
2777 ;;;           (eval-after-load "font-lock"
2778 ;;;                            '(if (face-equal font-lock-type-face
2779 ;;;                                             font-lock-comment-face)
2780 ;;;                                 (defconst font-lock-type-face
2781 ;;;                                   'font-lock-type-face
2782 ;;;                                   "Face to use for basic data types.")
2783 ;;;                               )))   ; This does not work :-( Why?!
2784 ;;;                                     ; Workaround: added to font-lock-m-h
2785 ;;;       )
2786           (or (boundp 'font-lock-other-emphasized-face)
2787               (defconst font-lock-other-emphasized-face
2788                 'font-lock-other-emphasized-face
2789                 "Face to use for another type of emphasizing.")
2790               )
2791           (or (boundp 'font-lock-emphasized-face)
2792               (defconst font-lock-emphasized-face
2793                 'font-lock-emphasized-face
2794                 "Face to use for emphasizing.")
2795               )
2796           ;; Here we try to guess background
2797           (let ((background
2798                  (if (boundp 'font-lock-background-mode)
2799                      font-lock-background-mode
2800                    'light)) 
2801                 (face-list (and (fboundp 'face-list) (face-list)))
2802                 is-face)
2803             (fset 'is-face
2804                   (cond ((fboundp 'find-face)
2805                          (symbol-function 'find-face))
2806                         (face-list
2807                          (function (lambda (face) (member face face-list))))
2808                         (t
2809                          (function (lambda (face) (boundp face))))))
2810             (defvar cperl-guessed-background
2811               (if (and (boundp 'font-lock-display-type)
2812                        (eq font-lock-display-type 'grayscale))
2813                   'gray
2814                 background)
2815               "Background as guessed by CPerl mode")
2816             (if (is-face 'font-lock-type-face) nil
2817               (copy-face 'default 'font-lock-type-face)
2818               (cond
2819                ((eq background 'light)
2820                 (set-face-foreground 'font-lock-type-face
2821                                      (if (x-color-defined-p "seagreen")
2822                                          "seagreen"
2823                                        "sea green")))
2824                ((eq background 'dark)
2825                 (set-face-foreground 'font-lock-type-face
2826                                      (if (x-color-defined-p "os2pink")
2827                                          "os2pink"
2828                                        "pink")))
2829                (t
2830                 (set-face-background 'font-lock-type-face "gray90"))))
2831             (if (is-face 'font-lock-other-type-face)
2832                 nil
2833               (copy-face 'font-lock-type-face 'font-lock-other-type-face)
2834               (cond
2835                ((eq background 'light)
2836                 (set-face-foreground 'font-lock-other-type-face
2837                                      (if (x-color-defined-p "chartreuse3")
2838                                          "chartreuse3"
2839                                        "chartreuse")))
2840                ((eq background 'dark)
2841                 (set-face-foreground 'font-lock-other-type-face
2842                                      (if (x-color-defined-p "orchid1")
2843                                          "orchid1"
2844                                        "orange")))))
2845             (if (is-face 'font-lock-other-emphasized-face) nil
2846               (copy-face 'bold-italic 'font-lock-other-emphasized-face)
2847               (cond
2848                ((eq background 'light)
2849                 (set-face-background 'font-lock-other-emphasized-face
2850                                      (if (x-color-defined-p "lightyellow2")
2851                                          "lightyellow2"
2852                                        (if (x-color-defined-p "lightyellow")
2853                                            "lightyellow"
2854                                          "light yellow"))))
2855                ((eq background 'dark)
2856                 (set-face-background 'font-lock-other-emphasized-face
2857                                      (if (x-color-defined-p "navy")
2858                                          "navy"
2859                                        (if (x-color-defined-p "darkgreen")
2860                                            "darkgreen"
2861                                          "dark green"))))
2862                (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
2863             (if (is-face 'font-lock-emphasized-face) nil
2864               (copy-face 'bold 'font-lock-emphasized-face)
2865               (cond
2866                ((eq background 'light)
2867                 (set-face-background 'font-lock-emphasized-face
2868                                      (if (x-color-defined-p "lightyellow2")
2869                                          "lightyellow2"
2870                                        "lightyellow")))
2871                ((eq background 'dark)
2872                 (set-face-background 'font-lock-emphasized-face
2873                                      (if (x-color-defined-p "navy")
2874                                          "navy"
2875                                        (if (x-color-defined-p "darkgreen")
2876                                            "darkgreen"
2877                                          "dark green"))))
2878                (t (set-face-background 'font-lock-emphasized-face "gray90"))))
2879             (if (is-face 'font-lock-variable-name-face) nil
2880               (copy-face 'italic 'font-lock-variable-name-face))
2881             (if (is-face 'font-lock-reference-face) nil
2882               (copy-face 'italic 'font-lock-reference-face))))
2883         (setq cperl-faces-init t))
2884     (error nil)))
2885
2886
2887 (defun cperl-ps-print-init ()
2888   "Initialization of `ps-print' components for faces used in CPerl."
2889   ;; Guard against old versions
2890   (defvar ps-underlined-faces nil)
2891   (defvar ps-bold-faces nil)
2892   (defvar ps-italic-faces nil)
2893   (setq ps-bold-faces
2894         (append '(font-lock-emphasized-face
2895                   font-lock-keyword-face 
2896                   font-lock-variable-name-face 
2897                   font-lock-reference-face 
2898                   font-lock-other-emphasized-face) 
2899                 ps-bold-faces))
2900   (setq ps-italic-faces
2901         (append '(font-lock-other-type-face
2902                   font-lock-reference-face 
2903                   font-lock-other-emphasized-face)
2904                 ps-italic-faces))
2905   (setq ps-underlined-faces
2906         (append '(font-lock-emphasized-face
2907                   font-lock-other-emphasized-face 
2908                   font-lock-other-type-face font-lock-type-face)
2909                 ps-underlined-faces))
2910   (cons 'font-lock-type-face ps-underlined-faces))
2911
2912
2913 (if (cperl-enable-font-lock) (cperl-windowed-init))
2914
2915 (defun cperl-set-style (style)
2916   "Set CPerl-mode variables to use one of several different indentation styles.
2917 The arguments are a string representing the desired style.
2918 Available styles are GNU, K&R, BSD and Whitesmith."
2919   (interactive 
2920    (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
2921                        c-style-alist)))
2922      (list (completing-read "Enter style: " list nil 'insist))))
2923   (let ((style (cdr (assoc style c-style-alist))) setting str sym)
2924     (while style
2925       (setq setting (car style) style (cdr style))
2926       (setq str (symbol-name (car setting)))
2927       (and (string-match "^c-" str)
2928            (setq str (concat "cperl-" (substring str 2)))
2929            (setq sym (intern-soft str))
2930            (boundp sym)
2931            (set sym (cdr setting))))))
2932
2933 (defun cperl-check-syntax ()
2934   (interactive)
2935   (require 'mode-compile)
2936   (let ((perl-dbg-flags "-wc"))
2937     (mode-compile)))
2938
2939 (defun cperl-info-buffer ()
2940   ;; Returns buffer with documentation. Creats if missing
2941   (let ((info (get-buffer "*info-perl*")))
2942     (if info info
2943       (save-window-excursion
2944         ;; Get Info running
2945         (require 'info)
2946         (save-window-excursion
2947           (info))
2948         (Info-find-node "perl5" "perlfunc")
2949         (set-buffer "*info*")
2950         (rename-buffer "*info-perl*")
2951         (current-buffer)))))
2952
2953 (defun cperl-word-at-point (&optional p)
2954   ;; Returns the word at point or at P.
2955   (save-excursion
2956     (if p (goto-char p))
2957     (require 'etags)
2958     (funcall (or (and (boundp 'find-tag-default-function)
2959                       find-tag-default-function)
2960                  (get major-mode 'find-tag-default-function)
2961                  ;; XEmacs 19.12 has `find-tag-default-hook'; it is
2962                  ;; automatically used within `find-tag-default':
2963                  'find-tag-default))))
2964
2965 (defun cperl-info-on-command (command)
2966   "Shows documentation for Perl command in other window."
2967   (interactive 
2968    (let* ((default (cperl-word-at-point))
2969           (read (read-string 
2970                      (format "Find doc for Perl function (default %s): " 
2971                              default))))
2972      (list (if (equal read "") 
2973                    default 
2974                  read))))
2975
2976   (let ((buffer (current-buffer))
2977         (cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
2978         pos)
2979     (if (string-match "^-[a-zA-Z]$" command)
2980         (setq cmd-desc "^-X[ \t\n]"))
2981     (set-buffer (cperl-info-buffer))
2982     (beginning-of-buffer)
2983     (re-search-forward "^-X[ \t\n]")
2984     (forward-line -1)
2985     (if (re-search-forward cmd-desc nil t)
2986         (progn
2987           (setq pos (progn (beginning-of-line)
2988                            (point)))
2989           (pop-to-buffer (cperl-info-buffer))
2990           (set-window-start (selected-window) pos))
2991       (message "No entry for %s found." command))
2992     (pop-to-buffer buffer)))
2993
2994 (defun cperl-info-on-current-command ()
2995   "Shows documentation for Perl command at point in other window."
2996   (interactive)
2997   (cperl-info-on-command (cperl-word-at-point)))
2998
2999 (defun cperl-imenu-info-imenu-search ()
3000   (if (looking-at "^-X[ \t\n]") nil
3001     (re-search-backward
3002      "^\n\\([-a-zA-Z]+\\)[ \t\n]")
3003     (forward-line 1)))
3004
3005 (defun cperl-imenu-info-imenu-name ()  
3006   (buffer-substring
3007    (match-beginning 1) (match-end 1)))
3008
3009 (defun cperl-imenu-on-info ()
3010   (interactive)
3011   (let* ((buffer (current-buffer))
3012          imenu-create-index-function
3013          imenu-prev-index-position-function 
3014          imenu-extract-index-name-function 
3015          (index-item (save-restriction
3016                        (save-window-excursion
3017                          (set-buffer (cperl-info-buffer))
3018                          (setq imenu-create-index-function 
3019                                'imenu-default-create-index-function
3020                                imenu-prev-index-position-function
3021                                'cperl-imenu-info-imenu-search
3022                                imenu-extract-index-name-function
3023                                'cperl-imenu-info-imenu-name)
3024                          (imenu-choose-buffer-index)))))
3025     (and index-item
3026          (progn
3027            (push-mark)
3028            (pop-to-buffer "*info-perl*")
3029            (cond
3030             ((markerp (cdr index-item))
3031              (goto-char (marker-position (cdr index-item))))
3032             (t
3033              (goto-char (cdr index-item))))
3034            (set-window-start (selected-window) (point))
3035            (pop-to-buffer buffer)))))
3036
3037 (defun cperl-lineup (beg end &optional step minshift)
3038   "Lineup construction in a region.
3039 Beginning of region should be at the start of a construction.
3040 All first occurences of this construction in the lines that are
3041 partially contained in the region are lined up at the same column.
3042
3043 MINSHIFT is the minimal amount of space to insert before the construction.
3044 STEP is the tabwidth to position constructions.
3045 If STEP is `nil', `cperl-lineup-step' will be used 
3046 \(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
3047 Will not move the position at the start to the left."
3048   (interactive "r")
3049   (let (search col tcol seen b e)
3050     (save-excursion
3051       (goto-char end)
3052       (end-of-line)
3053       (setq end (point-marker))
3054       (goto-char beg)
3055       (skip-chars-forward " \t\f")
3056       (setq beg (point-marker))
3057       (indent-region beg end nil)
3058       (goto-char beg)
3059       (setq col (current-column))
3060       (if (looking-at "\\sw")
3061           (if (looking-at "\\<\\sw+\\>")
3062               (setq search
3063                     (concat "\\<" 
3064                             (regexp-quote 
3065                              (buffer-substring (match-beginning 0)
3066                                                (match-end 0))) "\\>"))
3067             (error "Cannot line up in a middle of the word"))
3068         (if (looking-at "$")
3069             (error "Cannot line up end of line"))
3070         (setq search (regexp-quote (char-to-string (following-char)))))
3071       (setq step (or step cperl-lineup-step cperl-indent-level))
3072       (or minshift (setq minshift 1))
3073       (while (progn
3074                (beginning-of-line 2)
3075                (and (< (point) end) 
3076                     (re-search-forward search end t)
3077                     (goto-char (match-beginning 0))))
3078         (setq tcol (current-column) seen t)
3079         (if (> tcol col) (setq col tcol)))
3080       (or seen
3081           (error "The construction to line up occured only once"))
3082       (goto-char beg)
3083       (setq col (+ col minshift))
3084       (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
3085       (while 
3086           (progn
3087             (setq e (point))
3088             (skip-chars-backward " \t")
3089             (delete-region (point) e)
3090             (indent-to-column col); (make-string (- col (current-column)) ?\ ))
3091             (beginning-of-line 2) 
3092             (and (< (point) end) 
3093                  (re-search-forward search end t)
3094                  (goto-char (match-beginning 0)))))))) ; No body
3095
3096 (defun cperl-etags (&optional add all files)
3097   "Run etags with appropriate options for Perl files.
3098 If optional argument ALL is `recursive', will process Perl files
3099 in subdirectories too."
3100   (interactive)
3101   (let ((cmd "etags")
3102         (args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\([{#]\\|$\\)\\)/\\4/"))
3103         res)
3104     (if add (setq args (cons "-a" args)))
3105     (or files (setq files (list buffer-file-name)))
3106     (cond
3107      ((eq all 'recursive)
3108       ;;(error "Not implemented: recursive")
3109       (setq args (append (list "-e" 
3110                                "sub wanted {push @ARGV, $File::Find::name if /\\.[Pp][Llm]$/}
3111                                 use File::Find;
3112                                 find(\\&wanted, '.');
3113                                 exec @ARGV;" 
3114                                cmd) args)
3115             cmd "perl"))
3116      (all 
3117       ;;(error "Not implemented: all")
3118       (setq args (append (list "-e" 
3119                                "push @ARGV, <*.PL *.pl *.pm>;
3120                                 exec @ARGV;" 
3121                                cmd) args)
3122             cmd "perl"))
3123      (t
3124       (setq args (append args files))))
3125     (setq res (apply 'call-process cmd nil nil nil args))
3126     (or (eq res 0)
3127         (message "etags returned \"%s\"" res))))
3128
3129 (defun cperl-toggle-auto-newline ()
3130   "Toggle the state of `cperl-auto-newline'."
3131   (interactive)
3132   (setq cperl-auto-newline (not cperl-auto-newline))
3133   (message "Newlines will %sbe auto-inserted now." 
3134            (if cperl-auto-newline "" "not ")))
3135
3136 (defun cperl-toggle-abbrev ()
3137   "Toggle the state of automatic keyword expansion in CPerl mode."
3138   (interactive)
3139   (abbrev-mode (if abbrev-mode 0 1))
3140   (message "Perl control structure will %sbe auto-inserted now." 
3141            (if abbrev-mode "" "not ")))
3142
3143
3144 (defun cperl-toggle-electric ()
3145   "Toggle the state of parentheses doubling in CPerl mode."
3146   (interactive)
3147   (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
3148   (message "Parentheses will %sbe auto-doubled now." 
3149            (if (cperl-val 'cperl-electric-parens) "" "not ")))
3150
3151 ;;;; Tags file creation.
3152
3153 (defvar cperl-tmp-buffer " *cperl-tmp*")
3154
3155 (defun cperl-setup-tmp-buf ()
3156   (set-buffer (get-buffer-create cperl-tmp-buffer))
3157   (set-syntax-table cperl-mode-syntax-table)
3158   (buffer-disable-undo)
3159   (auto-fill-mode 0))
3160
3161 (defun cperl-xsub-scan ()
3162   (require 'cl)
3163   (let ((index-alist '()) 
3164         (prev-pos 0) index index1 name package prefix)
3165     (goto-char (point-min))
3166     (imenu-progress-message prev-pos 0)
3167     ;; Search for the function
3168     (progn ;;save-match-data
3169       (while (re-search-forward
3170               "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
3171               nil t)
3172         (imenu-progress-message prev-pos)
3173         (cond
3174          ((match-beginning 2)   ; SECTION
3175           (setq package (buffer-substring (match-beginning 2) (match-end 2)))
3176           (goto-char (match-beginning 0))
3177           (skip-chars-forward " \t")
3178           (forward-char 1)
3179           (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
3180               (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
3181             (setq prefix nil)))
3182          ((not package) nil)            ; C language section
3183          ((match-beginning 3)           ; XSUB
3184           (goto-char (1+ (match-beginning 3)))
3185           (setq index (imenu-example--name-and-position))
3186           (setq name (buffer-substring (match-beginning 3) (match-end 3)))
3187           (if (and prefix (string-match (concat "^" prefix) name))
3188               (setq name (substring name (length prefix))))
3189           (setq meth nil)
3190           (cond ((string-match "::" name) nil)
3191                 (t
3192                  (setq index1 (cons (concat package "::" name) (cdr index)))
3193                  (push index1 index-alist)))
3194           (setcar index name)
3195           (push index index-alist))
3196          (t                             ; BOOT: section
3197           ;; (beginning-of-line)
3198           (setq index (imenu-example--name-and-position))
3199           (setcar index (concat package "::BOOT:"))
3200           (push index index-alist)))))
3201     (imenu-progress-message prev-pos 100)
3202     ;;(setq index-alist 
3203     ;;      (if (default-value 'imenu-sort-function)
3204     ;;          (sort index-alist (default-value 'imenu-sort-function))
3205     ;;          (nreverse index-alist)))
3206     index-alist))
3207
3208 (defun cperl-find-tags (file xs)
3209   (let (ind (b (get-buffer cperl-tmp-buffer)) lst elt pos ret)
3210     (save-excursion
3211       (if b (set-buffer b)
3212           (cperl-setup-tmp-buf))
3213       (erase-buffer)
3214       (setq file (car (insert-file-contents file)))
3215       (message "Scanning file %s..." file)
3216       (if xs
3217           (setq lst (cperl-xsub-scan))
3218         (setq ind (imenu-example--create-perl-index))
3219         (setq lst (cdr (assoc "+Unsorted List+..." ind))))
3220       (setq lst 
3221             (mapcar 
3222              (function 
3223               (lambda (elt)
3224                 (cond ((string-match "^[_a-zA-Z]" (car elt))
3225                        (goto-char (cdr elt))
3226                        (list (car elt) 
3227                              (point) (count-lines 1 (point))
3228                              (buffer-substring (progn
3229                                                  (skip-chars-forward 
3230                                                   ":_a-zA-Z0-9")
3231                                                  (or (eolp) (forward-char 1))
3232                                                  (point))
3233                                                (progn
3234                                                  (beginning-of-line)
3235                                                  (point))))))))
3236                     lst))
3237       (erase-buffer)
3238       (while lst
3239         (setq elt (car lst) lst (cdr lst))
3240         (if elt
3241             (progn
3242               (insert (elt elt 3) 
3243                       127
3244                       (if (string-match "^package " (car elt))
3245                           (substring (car elt) 8)
3246                         (car elt) )
3247                       1
3248                       (number-to-string (elt elt 1))
3249                       ","
3250                       (number-to-string (elt elt 2))
3251                       "\n")
3252               (if (and (string-match "^[_a-zA-Z]+::" (car elt))
3253                        (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
3254                                      (elt elt 3)))
3255                   ;; Need to insert the name without package as well
3256                   (setq lst (cons (cons (substring (elt elt 3) 
3257                                                    (match-beginning 1)
3258                                                    (match-end 1))
3259                                         (cdr elt))
3260                                   lst))))))
3261       (setq pos (point))
3262       (goto-char 1)
3263       (insert "\f\n" file "," (number-to-string (1- pos)) "\n")
3264       (setq ret (buffer-substring 1 (point-max)))
3265       (erase-buffer)
3266       (message "Scanning file %s finished" file)
3267       ret)))
3268
3269 (defun cperl-write-tags (&optional file erase recurse dir inbuffer)
3270   ;; If INBUFFER, do not select buffer, and do not save
3271   ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
3272   (if file nil
3273     (setq file (if dir default-directory (buffer-file-name)))
3274     (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
3275   (let ((tags-file-name "TAGS")
3276         (case-fold-search (eq system-type 'emx))
3277         xs)
3278     (save-excursion
3279       (cond (inbuffer nil)              ; Already there
3280             ((file-exists-p tags-file-name)
3281              (visit-tags-table-buffer tags-file-name))
3282             (t (set-buffer (find-file-noselect tags-file-name))))
3283       (cond
3284        (dir
3285         (cond ((eq erase 'ignore))
3286               (erase
3287                (erase-buffer)
3288                (setq erase 'ignore)))
3289         (let ((files 
3290                (directory-files file t (if recurse nil "\\.[Pp][Llm]$") t)))
3291           (mapcar (function (lambda (file)
3292                               (cond
3293                                ((string-match "/\\.\\.?$" file) nil)
3294                                ((not (file-directory-p file))
3295                                 (if (string-match "\\.\\([Pp][Llm]\\|xs\\)$" file)
3296                                     (cperl-write-tags file erase recurse nil t)))
3297                                ((not recurse) nil)
3298                                (t (cperl-write-tags file erase recurse t t)))))
3299                   files))
3300         )
3301        (t
3302         (setq xs (string-match "\\.xs$" file))
3303         (cond ((eq erase 'ignore) nil)
3304               (erase (erase-buffer))
3305               (t
3306                (goto-char 1)
3307                (if (search-forward (concat "\f\n" file ",") nil t)
3308                    (progn
3309                      (search-backward "\f\n")
3310                      (delete-region (point)
3311                                     (progn 
3312                                       (forward-char 1)
3313                                       (search-forward "\f\n" nil 'toend)
3314                                       (point)))
3315                      (goto-char 1)))))
3316         (insert (cperl-find-tags file xs))))
3317       (if inbuffer nil          ; Delegate to the caller
3318         (save-buffer 0)         ; No backup
3319         (initialize-new-tags-table)))))
3320
3321 (defvar cperl-tags-hier-regexp-list
3322   "^\\(\\(package\\)\\>\\|sub\\>[^\n]+::\\|[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::\\|[ \t]*BOOT:\C-?[^\n]+::\\)")
3323
3324 (defvar cperl-hierarchy '(() ())
3325   "Global hierarchy of classes")
3326
3327 (defun cperl-tags-hier-fill ()
3328   ;; Suppose we are in a tag table cooked by cperl.
3329   (goto-char 1)
3330   (let (type pack name pos line chunk ord cons1 file str info fileind)
3331     (while (re-search-forward cperl-tags-hier-regexp-list nil t)
3332       (setq pos (match-beginning 0) 
3333             pack (match-beginning 2))
3334       (beginning-of-line)
3335       (if (looking-at "\\([^\n]+\\)\C-?\\([^\n]+\\)\C-a\\([0-9]+\\),\\([0-9]+\\)")
3336           (progn
3337             (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
3338                   name (buffer-substring (match-beginning 2) (match-end 2))
3339                   ;;pos (buffer-substring (match-beginning 3) (match-end 3))
3340                   line (buffer-substring (match-beginning 4) (match-end 4))
3341                   ord (if pack 1 0)
3342                   info (etags-snarf-tag) ; Moves to beginning of the next line
3343                   file (file-of-tag)
3344                   fileind (format "%s:%s" file line))
3345             ;; Move back
3346             (forward-char -1)
3347             ;; Make new member of hierarchy name ==> file ==> pos if needed
3348             (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
3349                 ;; Name known
3350                 (setcdr cons1 (cons (cons fileind (vector file info))
3351                                     (cdr cons1)))
3352               ;; First occurence of the name, start alist
3353               (setq cons1 (cons name (list (cons fileind (vector file info)))))
3354               (if pack 
3355                   (setcar (cdr cperl-hierarchy)
3356                           (cons cons1 (nth 1 cperl-hierarchy)))
3357                 (setcar cperl-hierarchy
3358                         (cons cons1 (car cperl-hierarchy)))))))
3359       (end-of-line))))
3360
3361 (defun cperl-tags-hier-init (&optional update)
3362   "Show hierarchical menu of classes and methods.
3363 Finds info about classes by a scan of loaded TAGS files.
3364 Supposes that the TAGS files contain fully qualified function names.
3365 One may build such TAGS files from CPerl mode menu."
3366   (interactive)
3367   (require 'etags)
3368   (require 'imenu)
3369   (if (or update (null (nth 2 cperl-hierarchy)))
3370       (let (pack name cons1 to l1 l2 l3 l4
3371                  (remover (function (lambda (elt) ; (name (file1...) (file2..))
3372                                       (or (nthcdr 2 elt)
3373                                           ;; Only in one file
3374                                           (setcdr elt (cdr (nth 1 elt))))))))
3375         ;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
3376         (setq cperl-hierarchy (list l1 l2 l3))
3377         (or tags-table-list
3378             (call-interactively 'visit-tags-table))
3379         (message "Updating list of classes...")
3380         (mapcar 
3381          (function
3382           (lambda (tagsfile)
3383             (set-buffer (get-file-buffer tagsfile))
3384             (cperl-tags-hier-fill)))
3385          tags-table-list)
3386         (mapcar remover (car cperl-hierarchy))
3387         (mapcar remover (nth 1 cperl-hierarchy))
3388         (setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
3389                        (cons "Methods: " (car cperl-hierarchy))))
3390         (cperl-tags-treeify to 1)
3391         (setcar (nthcdr 2 cperl-hierarchy)
3392                 (cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
3393         (message "Updating list of classes: done, requesting display...")
3394         ;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
3395         ))
3396   (or (nth 2 cperl-hierarchy)
3397       (error "No items found"))
3398   (setq update
3399 ;;;     (imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
3400         (if window-system
3401             (x-popup-menu t (nth 2 cperl-hierarchy))
3402           (require 'tmm)
3403           (tmm-prompt t (nth 2 cperl-hierarchy))))
3404   (if (and update (listp update))
3405       (progn (while (cdr update) (setq update (cdr update)))
3406              (setq update (car update)))) ; Get the last from the list
3407   (if (vectorp update) 
3408       (progn
3409         (find-file (elt update 0))
3410         (etags-goto-tag-location (elt update 1))))
3411   (if (eq update -999) (cperl-tags-hier-init t)))
3412
3413 (defun cperl-tags-treeify (to level)
3414   ;; cadr of to is read-write. On start it is a cons
3415   (let* ((regexp (concat "^\\(" (mapconcat 
3416                                  'identity
3417                                  (make-list level "[_a-zA-Z0-9]+")
3418                                  "::")
3419                          "\\)\\(::\\)?"))
3420          (packages (cdr (nth 1 to)))
3421          (methods (cdr (nth 2 to)))
3422          l1 head tail cons1 cons2 ord writeto packs recurse
3423          root-packages root-functions ms many_ms same_name ps
3424          (move-deeper
3425           (function 
3426            (lambda (elt)
3427              (cond ((and (string-match regexp (car elt))
3428                          (or (eq ord 1) (match-end 2)))
3429                     (setq head (substring (car elt) 0 (match-end 1))
3430                           tail (if (match-end 2) (substring (car elt) 
3431                                                             (match-end 2)))
3432                           recurse t)
3433                     (if (setq cons1 (assoc head writeto)) nil
3434                       ;; Need to init new head
3435                       (setcdr writeto (cons (list head (list "Packages: ")
3436                                                   (list "Methods: "))
3437                                             (cdr writeto)))
3438                       (setq cons1 (nth 1 writeto)))
3439                     (setq cons2 (nth ord cons1)) ; Either packs or meths
3440                     (setcdr cons2 (cons elt (cdr cons2))))
3441                    ((eq ord 2)
3442                     (setq root-functions (cons elt root-functions)))
3443                    (t
3444                     (setq root-packages (cons elt root-packages))))))))
3445     (setcdr to l1)                      ; Init to dynamic space
3446     (setq writeto to)
3447     (setq ord 1)
3448     (mapcar move-deeper packages)
3449     (setq ord 2)
3450     (mapcar move-deeper methods)
3451     (if recurse
3452         (mapcar (function (lambda (elt)
3453                           (cperl-tags-treeify elt (1+ level))))
3454                 (cdr to)))
3455     ;; Now add back functions removed from display
3456     (mapcar (function (lambda (elt)
3457                         (setcdr to (cons elt (cdr to)))))
3458             root-functions)
3459     ;; Now add back packages removed from display
3460     (mapcar (function (lambda (elt)
3461                         (setcdr to (cons (cons (concat "package " (car elt)) 
3462                                                (cdr elt)) 
3463                                          (cdr to)))))
3464             root-packages)
3465     ;;Now clean up leaders with one child only
3466     (mapcar (function (lambda (elt)
3467                         (if (not (and (listp (cdr elt)) 
3468                                       (eq (length elt) 2))) nil
3469                             (setcar elt (car (nth 1 elt)))
3470                             (setcdr elt (cdr (nth 1 elt))))))
3471             (cdr to))
3472     ))
3473
3474 ;;;(x-popup-menu t
3475 ;;;   '(keymap "Name1" 
3476 ;;;         ("Ret1" "aa")
3477 ;;;         ("Head1" "ab"  
3478 ;;;          keymap "Name2" 
3479 ;;;          ("Tail1" "x") ("Tail2" "y"))))
3480
3481 (defun cperl-list-fold (list name limit)
3482   (let (list1 list2 elt1 (num 0))
3483     (if (<= (length list) limit) list
3484       (setq list1 nil list2 nil)
3485       (while list
3486         (setq num (1+ num) 
3487               elt1 (car list)
3488               list (cdr list))
3489         (if (<= num imenu-max-items)
3490             (setq list2 (cons elt1 list2))
3491           (setq list1 (cons (cons name
3492                                   (nreverse list2))
3493                             list1)
3494                 list2 (list elt1)
3495                 num 1)))
3496       (nreverse (cons (cons name
3497                             (nreverse list2))
3498                       list1)))))
3499
3500 (defun cperl-menu-to-keymap (menu &optional name)
3501   (let (list)
3502     (cons 'keymap 
3503           (mapcar 
3504            (function 
3505             (lambda (elt)
3506               (cond ((listp (cdr elt))
3507                      (setq list (cperl-list-fold
3508                                  (cdr elt) (car elt) imenu-max-items))
3509                      (cons nil
3510                            (cons (car elt)
3511                                  (cperl-menu-to-keymap list))))
3512                     (t
3513                      (list (cdr elt) (car elt))))))
3514            (cperl-list-fold menu "Root" imenu-max-items)))))