Gnus -- Minor tweak define #'time-to-seconds
[packages] / xemacs-packages / sh-script / sh-script.el
1 ;;; sh-script.el --- shell-script editing commands for Emacs
2
3 ;; Copyright (C) 1993, 94, 95, 96, 97, 1999, 2001
4 ;;  Free Software Foundation, Inc.
5
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
7 ;; Version: 2.0f
8 ;; Maintainer: FSF
9 ;; Keywords: languages, unix
10
11 ;; This file is part of XEmacs.
12
13 ;; XEmacs is free software; you can redistribute it and/or modify it
14 ;; 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 ;; XEmacs is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 ;; General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
25 ;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 ;; 02110-1301, USA.
27
28 ;;; Synched up with: FSF 21.4.
29
30 ;;; Commentary:
31
32 ;; Major mode for editing shell scripts.  Bourne, C and rc shells as well
33 ;; as various derivatives are supported and easily derived from.  Structured
34 ;; statements can be inserted with one command or abbrev.  Completion is
35 ;; available for filenames, variables known from the script, the shell and
36 ;; the environment as well as commands.
37
38 ;;; Known Bugs:
39
40 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
41 ;; - Variables in `"' strings aren't fontified because there's no way of
42 ;;   syntactically distinguishing those from `'' strings.
43
44 ;;              Indentation
45 ;;              ===========
46 ;; Indentation for rc and es modes is very limited, but for Bourne shells
47 ;; and its derivatives it is quite customizable.
48 ;;
49 ;; The following description applies to sh and derived shells (bash,
50 ;; zsh, ...).
51 ;;
52 ;; There are various customization variables which allow tailoring to
53 ;; a wide variety of styles.  Most of these variables are named
54 ;; sh-indent-for-XXX and sh-indent-after-XXX.  For example.
55 ;; sh-indent-after-if controls the indenting of a line following
56 ;; an if statement, and sh-indent-for-fi controls the indentation
57 ;; of the line containing the fi.
58 ;;
59 ;; You can set each to a numeric value, but it is often more convenient
60 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
61 ;; By changing this one variable you can increase or decrease how much
62 ;; indentation there is.  Valid symbols:
63 ;;
64 ;;      +   Indent right by sh-basic-offset
65 ;;      -   Indent left  by sh-basic-offset
66 ;;      ++  Indent right twice sh-basic-offset
67 ;;      --  Indent left  twice sh-basic-offset
68 ;;      *   Indent right half sh-basic-offset
69 ;;      /   Indent left  half sh-basic-offset.
70 ;;
71 ;; There are 4 commands to help set the indentation variables:
72 ;;
73 ;; `sh-show-indent'
74 ;;    This shows what variable controls the indentation of the current
75 ;;    line and its value.
76 ;;
77 ;; `sh-set-indent'
78 ;;    This allows you to set the value of the variable controlling the
79 ;;    current line's indentation.  You can enter a number or one of a
80 ;;    number of special symbols to denote the value of sh-basic-offset,
81 ;;    or its negative, or half it, or twice it, etc.  If you've used
82 ;;    cc-mode this should be familiar.  If you forget which symbols are
83 ;;    valid simply press C-h at the prompt.
84 ;;
85 ;; `sh-learn-line-indent'
86 ;;    Simply make the line look the way you want it, then invoke this
87 ;;    command.  It will set the variable to the value that makes the line
88 ;;    indent like that.  If called with a prefix argument then it will set
89 ;;    the value to one of the symbols if applicable.
90 ;;
91 ;; `sh-learn-buffer-indent'
92 ;;    This is the deluxe function!  It "learns" the whole buffer (use
93 ;;    narrowing if you want it to process only part).  It outputs to a
94 ;;    buffer *indent* any conflicts it finds, and all the variables it has
95 ;;    learned.  This buffer is a sort of Occur mode buffer, allowing you to
96 ;;    easily find where something was set.  It is popped to automatically
97 ;;    if there are any conflicts found or if `sh-popup-occur-buffer' is
98 ;;    non-nil.
99 ;;    `sh-indent-comment' will be set if all comments follow  the same
100 ;;    pattern;  if they don't it will be set to nil.
101 ;;    Whether `sh-basic-offset' is set is determined by variable
102 ;;    `sh-learn-basic-offset'.
103 ;;
104 ;;    Unfortunately, `sh-learn-buffer-indent' can take a long time to run
105 ;;    (e.g. if there are large case statements).  Perhaps it does not make
106 ;;    sense to run it on large buffers: if lots of lines have different
107 ;;    indentation styles it will produce a lot of diagnostics in the
108 ;;    *indent* buffer; if there is a consistent style then running
109 ;;    `sh-learn-buffer-indent' on a small region of the buffer should
110 ;;    suffice.
111 ;;
112 ;;      Saving indentation values
113 ;;      -------------------------
114 ;; After you've learned the values in a buffer, how to you remember
115 ;; them?   Originally I had hoped that `sh-learn-buffer-indent'
116 ;; would make this unnecessary;  simply learn the values when you visit
117 ;; the buffer.
118 ;; You can do this automatically like this:
119 ;;   (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
120 ;;
121 ;; However...  `sh-learn-buffer-indent' is extremely slow,
122 ;; especially on large-ish buffer.  Also, if there are conflicts the
123 ;; "last one wins" which may not produce the desired setting.
124 ;;
125 ;; So...There is a minimal way of being able to save indentation values and
126 ;; to reload them in another buffer or at another point in time.
127 ;;
128 ;; Use `sh-name-style' to give a name to the indentation settings of
129 ;;      the current buffer.
130 ;; Use `sh-load-style' to load indentation settings for the current
131 ;;      buffer from a specific style.
132 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
133 ;;      in lisp code.  You can then store it in a file and later use
134 ;;      `load-file' to load it.
135 ;;
136 ;;      Indentation variables - buffer local or global?
137 ;;      ----------------------------------------------
138 ;; I think that often having them buffer-local makes sense,
139 ;; especially if one is using `sh-learn-buffer-indent'.  However, if
140 ;; a user sets values using customization, these changes won't appear
141 ;; to work if the variables are already local!
142 ;;
143 ;; To get round this, there is a variable `sh-make-vars-local' and 2
144 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
145 ;;
146 ;; If `sh-make-vars-local' is non-nil, then these variables become
147 ;; buffer local when the mode is established.
148 ;; If this is nil, then the variables are global.  At any time you
149 ;; can make them local with the command `sh-make-vars-local'.
150 ;; Conversely, to update with the global values you can use the
151 ;; command `sh-reset-indent-vars-to-global-values'.
152 ;;
153 ;; This may be awkward, but the intent is to cover all cases.
154 ;;
155 ;;      Awkward things, pitfalls
156 ;;      ------------------------
157 ;; Indentation for a sh script is complicated for a number of reasons:
158 ;;
159 ;; 1. You can't format by simply looking at symbols, you need to look
160 ;;    at keywords.  [This is not the case for rc and es shells.]
161 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
162 ;;    as a stand-alone symbol (in a case alternative).  This makes
163 ;;    things quite tricky!
164 ;; 3. Here-documents in a script should be treated "as is", and when
165 ;;    they terminate we want to revert to the indentation of the line
166 ;;    containing the "<<" symbol.
167 ;; 4. A line may be continued using the "\".
168 ;; 5. The character "#" (outside a string) normally starts a comment,
169 ;;    but it doesn't in the sequence "$#"!
170 ;;
171 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
172 ;; uses, that of a text's syntax property.  This, however, has 2
173 ;; disadvantages:
174 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
175 ;;    case alternative, to find any here documents, and handle "$#".
176 ;; 2. Setting the text property makes the buffer modified.  If the
177 ;;    buffer is read-only buffer we have to cheat and bypass the read-only
178 ;;    status.  This is for cases where the buffer started read-only buffer
179 ;;    but the user issued `toggle-read-only'.
180 ;;
181 ;;      Bugs
182 ;;      ----
183 ;; - Indenting many lines is slow.  It currently does each line
184 ;;   independently, rather than saving state information.
185 ;;
186 ;; - `sh-learn-buffer-indent' is extremely slow.
187 ;;
188 ;; Richard Sharman <rsharman@pobox.com>  June 1999.
189
190 ;;; Code:
191
192 ;; page 1:      variables and settings
193 ;; page 2:      indentation stuff
194 ;; page 3:      mode-command and utility functions
195 ;; page 4:      statement syntax-commands for various shells
196 ;; page 5:      various other commands
197
198 (eval-when-compile
199   (require 'skeleton)
200   (require 'comint))
201 (require 'executable)
202
203
204
205 (defgroup sh nil
206   "Shell programming utilities"
207   :group 'unix
208   :group 'languages)
209
210 (defgroup sh-script nil
211   "Shell script mode"
212   :group 'sh
213   :prefix "sh-")
214
215 ;;; interpreter-mode-alist is not compatible between Emacs and XEmacs.
216 ;;; So fake it.
217
218 (defvar sh-interpreter-mode-alist
219   '(("perl" . perl-mode)
220     ("perl5" . perl-mode)
221     ("wish" . tcl-mode)
222     ("wishx" . tcl-mode)
223     ("tcl" . tcl-mode)
224     ("tclsh" . tcl-mode)
225     ("awk" . awk-mode)
226     ("mawk" . awk-mode)
227     ("nawk" . awk-mode)
228     ("gawk" . awk-mode)
229     ("scm" . scheme-mode)
230     ("ash" . sh-mode)
231     ("bash" . sh-mode)
232     ("csh" . sh-mode)
233     ("dtksh" . sh-mode)
234     ("es" . sh-mode)
235     ("itcsh" . sh-mode)
236     ("jsh" . sh-mode)
237     ("ksh" . sh-mode)
238     ("oash" . sh-mode)
239     ("pdksh" . sh-mode)
240     ("rc" . sh-mode)
241     ("sh" . sh-mode)
242     ("sh5" . sh-mode)
243     ("cmd" . sh-mode)
244     ("tcsh" . sh-mode)
245     ("wksh" . sh-mode)
246     ("wsh" . sh-mode)
247     ("zsh" . sh-mode)
248     ("tail" . text-mode)
249     ("more" . text-mode)
250     ("less" . text-mode)
251     ("pg" . text-mode))
252   "Alist mapping interpreter names to major modes.
253 This alist applies to files whose first line starts with `#!'.
254 Each element looks like (INTERPRETER . MODE).
255 The car of each element is compared with
256 the name of the interpreter specified in the first line.
257 If it matches, mode MODE is selected.")
258
259 (defcustom sh-ancestor-alist
260   '((ash . sh)
261     (bash . jsh)
262     (bash2 . jsh)
263     (dtksh . ksh)
264     (es . rc)
265     (itcsh . tcsh)
266     (jcsh . csh)
267     (jsh . sh)
268     (ksh . ksh88)
269     (ksh88 . jsh)
270     (oash . sh)
271     (pdksh . ksh88)
272     (posix . sh)
273     (tcsh . csh)
274     (wksh . ksh88)
275     (wsh . sh)
276     (zsh . ksh88)
277     (rpm . sh))
278   "*Alist showing the direct ancestor of various shells.
279 This is the basis for `sh-feature'.  See also `sh-alias-alist'.
280 By default we have the following three hierarchies:
281
282 csh             C Shell
283   jcsh          C Shell with Job Control
284   tcsh          Toronto C Shell
285     itcsh       ? Toronto C Shell
286 rc              Plan 9 Shell
287   es            Extensible Shell
288 sh              Bourne Shell
289   ash           ? Shell
290   jsh           Bourne Shell with Job Control
291     bash        GNU Bourne Again Shell
292     ksh88       Korn Shell '88
293       ksh       Korn Shell '93
294         dtksh   CDE Desktop Korn Shell
295       pdksh     Public Domain Korn Shell
296       wksh      Window Korn Shell
297       zsh       Z Shell
298   oash          SCO OA (curses) Shell
299   posix         IEEE 1003.2 Shell Standard
300   wsh           ? Shell"
301   :type '(repeat (cons symbol symbol))
302   :group 'sh-script)
303
304
305 (defcustom sh-alias-alist
306   ;; XEmacs change: Linux is spelled `linux'
307   (nconc (if (eq system-type 'linux)
308              '((csh . tcsh)
309                (ksh . pdksh)))
310          ;; for the time being
311          '((ksh . ksh88)
312            (bash2 . bash)
313            (sh5 . sh)))
314   "*Alist for transforming shell names to what they really are.
315 Use this where the name of the executable doesn't correspond to the type of
316 shell it really is."
317   :type '(repeat (cons symbol symbol))
318   :group 'sh-script)
319
320
321 (defcustom sh-shell-file
322   (or
323    ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
324    ;; the executable extension, so comparisons with the list of
325    ;; known shells work.
326    (and (memq system-type '(ms-dos windows-nt))
327         (let* ((shell (getenv "SHELL"))
328                (shell-base
329                 (and shell (file-name-nondirectory shell))))
330           ;; shell-script mode doesn't support DOS/Windows shells,
331           ;; so use the default instead.
332           (if (or (null shell)
333                   (member (downcase shell-base)
334                           '("command.com" "cmd.exe" "4dos.com" "ndos.com"
335                             "cmdproxy.exe")))
336               "/bin/sh"
337             (file-name-sans-extension (downcase shell)))))
338    (getenv "SHELL")
339    "/bin/sh")
340   "*The executable file name for the shell being programmed."
341   :type 'string
342   :group 'sh-script)
343
344
345 (defcustom sh-shell-arg
346   ;; bash does not need any options when run in a shell script,
347   '((bash)
348     (csh . "-f")
349     (pdksh)
350     ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
351     (ksh88)
352     ;; -p means don't initialize functions from the environment.
353     (rc . "-p")
354     ;; Someone proposed -motif, but we don't want to encourage
355     ;; use of a non-free widget set.
356     (wksh)
357     ;; -f means don't run .zshrc.
358     (zsh . "-f"))
359   "*Single argument string for the magic number.  See `sh-feature'."
360   :type '(repeat (cons (symbol :tag "Shell")
361                        (choice (const :tag "No Arguments" nil)
362                                (string :tag "Arguments")
363                                (cons :format "Evaluate: %v"
364                                      (const :format "" eval)
365                                      sexp))))
366   :group 'sh-script)
367
368 (defcustom sh-imenu-generic-expression
369   `((sh
370      . ((nil "^\\s-*\\(function\\s-+\\)?\\([A-Za-z_][A-Za-z_0-9]+\\)\\s-*()" 2))))
371   "*Alist of regular expressions for recognizing shell function definitions.
372 See `sh-feature' and `imenu-generic-expression'."
373   :type '(alist :key-type (symbol :tag "Shell")
374                 :value-type (alist :key-type (choice :tag "Title"
375                                                      string
376                                                      (const :tag "None" nil))
377                                    :value-type
378                                    (repeat :tag "Regexp, index..." sexp)))
379   :group 'sh-script
380   :version "20.4")
381
382 (defvar sh-shell-variables nil
383   "Alist of shell variable names that should be included in completion.
384 These are used for completion in addition to all the variables named
385 in `process-environment'.  Each element looks like (VAR . VAR), where
386 the car and cdr are the same symbol.")
387
388 (defvar sh-shell-variables-initialized nil
389   "Non-nil if `sh-shell-variables' is initialized.")
390
391 (defun sh-canonicalize-shell (shell)
392   "Convert a shell name SHELL to the one we should handle it as."
393   (if (string-match "\\.exe\\'" shell)
394       (setq shell (substring shell 0 (match-beginning 0))))
395   (or (symbolp shell)
396       (setq shell (intern shell)))
397   (or (cdr (assq shell sh-alias-alist))
398       shell))
399
400 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
401   "The shell being programmed.  This is set by \\[sh-set-shell].")
402
403 ;;; I turned off this feature because it doesn't permit typing commands
404 ;;; in the usual way without help.
405 ;;;(defvar sh-abbrevs
406 ;;;  '((csh eval sh-abbrevs shell
407 ;;;      "switch" 'sh-case
408 ;;;      "getopts" 'sh-while-getopts)
409
410 ;;;    (es eval sh-abbrevs shell
411 ;;;     "function" 'sh-function)
412
413 ;;;    (ksh88 eval sh-abbrevs sh
414 ;;;        "select" 'sh-select)
415
416 ;;;    (rc eval sh-abbrevs shell
417 ;;;     "case" 'sh-case
418 ;;;     "function" 'sh-function)
419
420 ;;;    (sh eval sh-abbrevs shell
421 ;;;     "case" 'sh-case
422 ;;;     "function" 'sh-function
423 ;;;     "until" 'sh-until
424 ;;;     "getopts" 'sh-while-getopts)
425
426 ;;;    ;; The next entry is only used for defining the others
427 ;;;    (shell "for" sh-for
428 ;;;        "loop" sh-indexed-loop
429 ;;;        "if" sh-if
430 ;;;        "tmpfile" sh-tmp-file
431 ;;;        "while" sh-while)
432
433 ;;;    (zsh eval sh-abbrevs ksh88
434 ;;;      "repeat" 'sh-repeat))
435 ;;;  "Abbrev-table used in Shell-Script mode.  See `sh-feature'.
436 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
437 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
438
439
440
441 (easy-mmode-defsyntax sh-mode-syntax-table
442   '((?\# . "<")
443    (?\^l . ">#")
444    (?\n . ">#")
445    (?\" . "\"\"")
446    (?\' . "\"'")
447    (?\` . "\"`")
448    (?! . "_")
449    (?% . "_")
450    (?: . "_")
451    (?. . "_")
452    (?^ . "_")
453    (?~ . "_")
454    (?< . ".")
455    (?> . "."))
456   "Syntax-table used in Shell-Script mode.")
457
458
459 (defvar sh-mode-map
460   (let ((map (make-sparse-keymap))
461         (menu-map (make-sparse-keymap "Insert")))
462     (define-key map "\C-c(" 'sh-function)
463     (define-key map "\C-c\C-w" 'sh-while)
464     (define-key map "\C-c\C-u" 'sh-until)
465     (define-key map "\C-c\C-t" 'sh-tmp-file)
466     (define-key map "\C-c\C-s" 'sh-select)
467     (define-key map "\C-c\C-r" 'sh-repeat)
468     (define-key map "\C-c\C-o" 'sh-while-getopts)
469     (define-key map "\C-c\C-l" 'sh-indexed-loop)
470     (define-key map "\C-c\C-i" 'sh-if)
471     (define-key map "\C-c\C-f" 'sh-for)
472     (define-key map "\C-c\C-c" 'sh-case)
473     (define-key map "\C-c?" 'sh-show-indent)
474     (define-key map "\C-c=" 'sh-set-indent)
475     (define-key map "\C-c<" 'sh-learn-line-indent)
476     (define-key map "\C-c>" 'sh-learn-buffer-indent)
477
478     (define-key map "=" 'sh-assignment)
479     (define-key map "\C-c+" 'sh-add)
480     (define-key map "\C-\M-x" 'sh-execute-region)
481     (define-key map "\C-c\C-x" 'executable-interpret)
482     (define-key map "<" 'sh-maybe-here-document)
483     (define-key map "(" 'skeleton-pair-insert-maybe)
484     (define-key map "{" 'skeleton-pair-insert-maybe)
485     (define-key map "[" 'skeleton-pair-insert-maybe)
486     (define-key map "'" 'skeleton-pair-insert-maybe)
487     (define-key map "`" 'skeleton-pair-insert-maybe)
488     (define-key map "\"" 'skeleton-pair-insert-maybe)
489
490     (substitute-key-definition 'complete-tag 'comint-dynamic-complete
491                                map (current-global-map))
492     (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
493                                map (current-global-map))
494 ;; XEmacs change: Don't mess around with the DEL bindings
495 ;    (substitute-key-definition 'delete-backward-char
496 ;                              'backward-delete-char-untabify
497 ;                              map (current-global-map))
498     (define-key map "\C-c:" 'sh-set-shell)
499     (substitute-key-definition 'beginning-of-defun
500                                'sh-beginning-of-compound-command
501                                map (current-global-map))
502     (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
503                                map (current-global-map))
504     (substitute-key-definition 'forward-sentence 'sh-end-of-command
505                                map (current-global-map))
506     map)
507   "Keymap used in Shell-Script mode.")
508
509 ;; XEmacs change
510 (easy-menu-define
511  sh-mode-menu sh-mode-map "Menu for sh-script mode"
512      '("Insert"
513        ["While Loop" sh-while t]
514        ["Until Loop" sh-until t]
515        ["Temporary File" sh-tmp-file t]
516        ["Select Statement" sh-select t]
517        ["Repeat Loop" sh-repeat t]
518        ["Options Loop" sh-while-getopts t]
519        ["Indexed Loop" sh-indexed-loop t]
520        ["If Statement" sh-if t]
521        ["For Loop" sh-for t]
522        ["Case Statement" sh-case t]))
523
524 (defcustom sh-dynamic-complete-functions
525   '(shell-dynamic-complete-environment-variable
526     shell-dynamic-complete-command
527     comint-dynamic-complete-filename)
528   "*Functions for doing TAB dynamic completion."
529   :type '(repeat function)
530   :group 'sh-script)
531
532
533 (defcustom sh-require-final-newline
534   '((csh . t)
535     (pdksh . t)
536     (rc eval . require-final-newline)
537     (sh eval . require-final-newline))
538   "*Value of `require-final-newline' in Shell-Script mode buffers.
539 See `sh-feature'."
540   :type '(repeat (cons (symbol :tag "Shell")
541                        (choice (const :tag "require" t)
542                                (cons :format "Evaluate: %v"
543                                      (const :format "" eval)
544                                      sexp))))
545   :group 'sh-script)
546
547
548 (defcustom sh-assignment-regexp
549   '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
550     ;; actually spaces are only supported in let/(( ... ))
551     (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
552     (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
553     (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
554   "*Regexp for the variable name and what may follow in an assignment.
555 First grouping matches the variable name.  This is upto and including the `='
556 sign.  See `sh-feature'."
557   :type '(repeat (cons (symbol :tag "Shell")
558                        (choice regexp
559                                (cons :format "Evaluate: %v"
560                                      (const :format "" eval)
561                                      sexp))))
562   :group 'sh-script)
563
564
565 (defcustom sh-indentation 4
566   "The width for further indentation in Shell-Script mode."
567   :type 'integer
568   :group 'sh-script)
569
570
571 (defcustom sh-remember-variable-min 3
572   "*Don't remember variables less than this length for completing reads."
573   :type 'integer
574   :group 'sh-script)
575
576
577 (defvar sh-header-marker nil
578   "When non-nil is the end of header for prepending by \\[sh-execute-region].
579 That command is also used for setting this variable.")
580
581
582 (defcustom sh-beginning-of-command
583   "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
584   "*Regexp to determine the beginning of a shell command.
585 The actual command starts at the beginning of the second \\(grouping\\)."
586   :type 'regexp
587   :group 'sh-script)
588
589
590 (defcustom sh-end-of-command
591   "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
592   "*Regexp to determine the end of a shell command.
593 The actual command ends at the end of the first \\(grouping\\)."
594   :type 'regexp
595   :group 'sh-script)
596
597
598
599 (defvar sh-here-document-word "EOF"
600   "Word to delimit here documents.")
601
602 ;; XEmacs change: indexes decreased by one (behaviour difference with GNU?)
603 (defvar sh-test
604   '((sh "[  ]" . 2)
605     (ksh88 "[[  ]]" . 3))
606   "Initial input in Bourne if, while and until skeletons.  See `sh-feature'.")
607
608
609 ;; customized this out of sheer bravado.  not for the faint of heart.
610 ;; but it *did* have an asterisk in the docstring!
611 (defcustom sh-builtins
612   '((bash eval sh-append posix
613           "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
614           "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
615           "suspend" "typeset" "unalias")
616
617     ;; The next entry is only used for defining the others
618     (bourne eval sh-append shell
619             "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
620             "times" "ulimit")
621
622     (csh eval sh-append shell
623          "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
624          "setenv" "source" "time" "unalias" "unhash")
625
626     (dtksh eval identity wksh)
627
628     (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
629         "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
630
631     (jsh eval sh-append sh
632          "bg" "fg" "jobs" "kill" "stop" "suspend")
633
634     (jcsh eval sh-append csh
635           "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
636
637     (ksh88 eval sh-append bourne
638            "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
639            "typeset" "unalias" "whence")
640
641     (oash eval sh-append sh
642           "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
643           "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
644           "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
645           "wmtitle" "wrefresh")
646
647     (pdksh eval sh-append ksh88
648            "bind")
649
650     (posix eval sh-append sh
651            "command")
652
653     (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
654         "whatis")
655
656     (sh eval sh-append bourne
657         "hash" "test" "type")
658
659     ;; The next entry is only used for defining the others
660     (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
661
662     (wksh eval sh-append ksh88
663           "Xt[A-Z][A-Za-z]*")
664
665     (zsh eval sh-append ksh88
666          "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
667          "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
668          "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
669          "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
670          "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
671          "which"))
672   "*List of all shell builtins for completing read and fontification.
673 Note that on some systems not all builtins are available or some are
674 implemented as aliases.  See `sh-feature'."
675   :type '(repeat (cons (symbol :tag "Shell")
676                        (choice (repeat string)
677                                (cons :format "Evaluate: %v"
678                                      (const :format "" eval)
679                                      sexp))))
680   :group 'sh-script)
681
682
683
684 (defcustom sh-leading-keywords
685   '((csh "else")
686
687     (es "true" "unwind-protect" "whatis")
688
689     (rc "else")
690
691     (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
692   "*List of keywords that may be immediately followed by a builtin or keyword.
693 Given some confusion between keywords and builtins depending on shell and
694 system, the distinction here has been based on whether they influence the
695 flow of control or syntax.  See `sh-feature'."
696   :type '(repeat (cons (symbol :tag "Shell")
697                        (choice (repeat string)
698                                (cons :format "Evaluate: %v"
699                                      (const :format "" eval)
700                                      sexp))))
701   :group 'sh-script)
702
703
704 (defcustom sh-other-keywords
705   '((bash eval sh-append bourne
706           "bye" "logout")
707
708     ;; The next entry is only used for defining the others
709     (bourne eval sh-append sh
710             "function")
711
712     (csh eval sh-append shell
713          "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
714          "if" "logout" "onintr" "repeat" "switch" "then" "while")
715
716     (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
717         "return" "throw" "while")
718
719     (ksh88 eval sh-append bourne
720            "select")
721
722     (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
723         "while")
724
725     (sh eval sh-append shell
726         "done" "esac" "fi" "for" "in" "return")
727
728     ;; The next entry is only used for defining the others
729     (shell "break" "case" "continue" "exec" "exit")
730
731     (zsh eval sh-append bash
732          "select"))
733   "*List of keywords not in `sh-leading-keywords'.
734 See `sh-feature'."
735   :type '(repeat (cons (symbol :tag "Shell")
736                        (choice (repeat string)
737                                (cons :format "Evaluate: %v"
738                                      (const :format "" eval)
739                                      sexp))))
740   :group 'sh-script)
741
742
743
744 (defvar sh-variables
745   '((bash eval sh-append sh
746           "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
747           "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
748           "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
749           "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
750           "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
751           "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
752           "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
753           "SECONDS" "SHLVL" "TMOUT" "UID")
754
755     (csh eval sh-append shell
756          "argv" "cdpath" "child" "echo" "histchars" "history" "home"
757          "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
758          "shell" "status" "time" "verbose")
759
760     (es eval sh-append shell
761         "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
762         "pid" "prompt" "signals")
763
764     (jcsh eval sh-append csh
765           "notify")
766
767     (ksh88 eval sh-append sh
768            "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
769            "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
770            "TMOUT")
771
772     (oash eval sh-append sh
773           "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
774
775     (rc eval sh-append shell
776         "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
777         "prompt" "status")
778
779     (sh eval sh-append shell
780         "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
781
782     ;; The next entry is only used for defining the others
783     (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
784            "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
785            "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
786            "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
787
788     (tcsh eval sh-append csh
789           "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
790           "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
791           "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
792           "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
793           "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
794           "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
795           "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
796           "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
797           "wordchars")
798
799     (zsh eval sh-append ksh88
800          "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
801          "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
802          "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
803          "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
804          "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
805          "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
806          "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
807   "List of all shell variables available for completing read.
808 See `sh-feature'.")
809
810 \f
811 ;;; Font-Lock support
812
813 (defface sh-heredoc-face
814   '((((class color)
815       (background dark))
816      (:foreground "yellow" :bold t))
817     (((class color)
818       (background light))
819      (:foreground "tan" ))
820     (t
821      (:bold t)))
822   "Face to show a here-document"
823 :group 'sh-indentation)
824 (defvar sh-heredoc-face 'sh-heredoc-face)
825
826
827 (defvar sh-font-lock-keywords
828   '((csh eval sh-append shell
829          '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
830            font-lock-variable-name-face))
831
832     (es eval sh-append executable-font-lock-keywords
833         '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
834           font-lock-variable-name-face))
835
836     (rc eval identity es)
837
838     (sh eval sh-append shell
839         ;; Variable names.
840         '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
841           font-lock-variable-name-face)
842         ;; Function names.
843         '("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
844         '("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
845           (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t)))
846
847     ;; The next entry is only used for defining the others
848     (shell eval sh-append executable-font-lock-keywords
849            '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
850            '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
851              font-lock-variable-name-face))
852     (rpm eval sh-append rpm2
853          '("%{?\\(\\sw+\\)"  1 font-lock-keyword-face))
854     (rpm2 eval sh-append shell
855           '("^\\(\\sw+\\):"  1 font-lock-variable-name-face)))
856   "Default expressions to highlight in Shell Script modes.  See `sh-feature'.")
857
858 (defvar sh-font-lock-keywords-1
859   '((sh "[ \t]in\\>"))
860   "Subdued level highlighting for Shell Script modes.")
861
862 (defvar sh-font-lock-keywords-2 ()
863   "Gaudy level highlighting for Shell Script modes.")
864
865 ;; These are used for the syntax table stuff (derived from cperl-mode).
866 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
867
868 ;; XEmacs change: syntax-string-to-code replaces string-to-syntax
869 (defconst sh-st-punc (syntax-string-to-code "."))
870 (defconst sh-st-symbol (syntax-string-to-code "_"))
871 (defconst sh-here-doc-syntax (syntax-string-to-code "|")) ;; generic string
872
873 (defun sh-font-lock-heredoc (start string quoted)
874   "Determine the syntax of the \\n after a <<HEREDOC."
875   (unless (sh-in-comment-or-string start)
876     ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
877     ;; font-lock keywords to detect the end of this here document.
878     (let ((ere (concat
879                 "^" (if quoted "[ \t]*")
880                 (regexp-quote (replace-regexp-in-string "['\"]" "" string))
881                 "\\(\n\\)")))
882       (unless (assoc ere font-lock-syntactic-keywords)
883         (let* ( ;; A rough regexp that should find us back.
884                (sre (concat "<<\\(-\\)?\\s-*\\\\?['\"]?"
885                             (regexp-quote string) "['\"]?[ \t\n]"))
886                (code `(cond
887                        ((save-excursion (re-search-backward ,sre nil t))
888                         ;; This ^STRING$ is indeed following a <<STRING
889                         sh-here-doc-syntax)
890                        ((not (save-excursion (re-search-forward ,sre nil t)))
891                         ;; There's no <<STRING either before or after us,
892                         ;; so we should remove this now obsolete entry.
893                         (setq font-lock-syntactic-keywords
894                               (delq (assoc ,ere font-lock-syntactic-keywords)
895                                     font-lock-syntactic-keywords))
896                         nil))))
897           ;; Use destructive update so the new keyword gets used right away.
898           (setq font-lock-syntactic-keywords
899                 (nconc font-lock-syntactic-keywords
900                        (list (font-lock-compile-keyword `(,ere 1 ,code))))))))
901     sh-here-doc-syntax))
902
903 (defun sh-font-lock-paren (start)
904   (save-excursion
905     (goto-char start)
906     ;; Skip through all patterns
907     (while
908         (progn
909           (forward-comment (- (point-max)))
910           ;; Skip through one pattern
911           (while
912               (or (/= 0 (skip-syntax-backward "w_"))
913                   (/= 0 (skip-chars-backward "?*/"))
914                   (when (memq (char-before) '(?\" ?\'))
915                     (condition-case nil (progn (backward-sexp 1) t)
916                       (error nil)))))
917           (forward-comment (- (point-max)))
918           (when (eq (char-before) ?|)
919             (backward-char 1) t)))
920     (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
921       sh-st-punc)))
922
923 (defconst sh-font-lock-syntactic-keywords
924   ;; A `#' begins a comment when it is unquoted and at the beginning of a
925   ;; word.  In the shell, words are separated by metacharacters.
926   ;; The list of special chars is taken from the single-unix spec
927   ;; of the shell command language (under `quoting') but with `$' removed.
928   `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol)
929     ;; Find HEREDOC starters and add a corresponding rule for the ender.
930     ("[^<>]<<\\(-\\)?\\s-*\\\\?\\(\\(['\"][^'\"]+['\"]\\|\\sw\\|\\s_\\)+\\).*\\(\n\\)"
931      4 (sh-font-lock-heredoc
932         (match-beginning 0) (match-string 2) (match-end 1)))
933     ;; Distinguish the special close-paren in `case'.
934     (")" 0 (sh-font-lock-paren (match-beginning 0)))))
935
936 (defun sh-font-lock-syntactic-face-function (state)
937   (if (nth 3 state)
938       (if (char-valid-p (nth 3 state))
939           font-lock-string-face
940         sh-heredoc-face)
941     font-lock-comment-face))
942
943 (defgroup sh-indentation nil
944   "Variables controlling indentation in shell scripts.
945
946 Note: customizing these variables will not affect existing buffers if
947 `sh-make-vars-local' is no-nil.  See the documentation for
948 variable `sh-make-vars-local', command `sh-make-vars-local'
949 and command `sh-reset-indent-vars-to-global-values'."
950 :group 'sh-script)
951
952
953 (defcustom sh-set-shell-hook nil
954   "*Hook run by `sh-set-shell'."
955 :type 'hook
956 :group 'sh-script)
957
958 (defcustom sh-mode-hook nil
959   "*Hook run by `sh-mode'."
960 :type 'hook
961 :group 'sh-script)
962
963 (defcustom sh-learn-basic-offset nil
964   "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
965
966 nil mean:              never.
967 t means:               only if there seems to be an obvious value.
968 Anything else means:   whenever we have a \"good guess\" as to the value."
969 :type '(choice
970           (const :tag "Never" nil)
971           (const :tag "Only if sure"  t)
972           (const :tag "If have a good guess" usually))
973 :group 'sh-indentation)
974
975 (defcustom sh-popup-occur-buffer nil
976   "*Controls when  `sh-learn-buffer-indent' pops the *indent* buffer.
977 If t it is always shown.  If nil, it is shown only when there
978 are conflicts."
979 :type '(choice
980           (const :tag "Only when there are conflicts." nil)
981           (const :tag "Always"  t))
982 :group 'sh-indentation)
983
984 (defcustom sh-blink t
985   "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
986 The position on the line is not necessarily meaningful.
987 In some cases the line will be the matching keyword, but this is not
988 always the case."
989 :type 'boolean
990 :group 'sh-indentation)
991
992 (defcustom sh-first-lines-indent 0
993   "*The indentation of the first non-blank non-comment line.
994 Usually 0 meaning first column.
995 Can be set to a number, or to nil which means leave it as is."
996 :type '(choice
997           (const :tag "Leave as is"     nil)
998           (integer :tag "Column number"
999                    :menu-tag "Indent to this col (0 means first col)" ))
1000 :group 'sh-indentation)
1001
1002
1003 (defcustom sh-basic-offset 4
1004   "*The default indentation increment.
1005 This value is used for the + and - symbols in an indentation variable."
1006 :type 'integer
1007 :group 'sh-indentation)
1008
1009 (defcustom sh-indent-comment nil
1010   "*How a comment line is to be indented.
1011 nil means leave it as it is;
1012 t  means indent it as a normal line, aligning it to previous non-blank
1013    non-comment line;
1014 a number means align to that column, e.g. 0 means fist column."
1015 :type '(choice
1016           (const :tag "Leave as is." nil)
1017           (const :tag "Indent as a normal line."  t)
1018           (integer :menu-tag "Indent to this col (0 means first col)."
1019                    :tag "Indent to column number.") )
1020 :group 'sh-indentation)
1021
1022
1023 (defvar sh-debug nil
1024   "Enable lots of debug messages - if function `sh-debug' is enabled.")
1025
1026
1027 ;; Uncomment this defun and comment the defmacro for debugging.
1028 ;; (defun sh-debug (&rest args)
1029 ;;   "For debugging:  display message ARGS if variable SH-DEBUG is non-nil."
1030 ;;   (if sh-debug
1031 ;;       (apply 'message args)))
1032 (defmacro sh-debug (&rest args))
1033
1034 (defconst sh-symbol-list
1035   '((const :tag "+ "  :value +
1036            :menu-tag "+   Indent right by sh-basic-offset")
1037     (const :tag "- "  :value -
1038            :menu-tag "-   Indent left  by sh-basic-offset")
1039     (const :tag "++"  :value  ++
1040            :menu-tag "++  Indent right twice sh-basic-offset")
1041     (const :tag "--"  :value --
1042            :menu-tag "--  Indent left  twice sh-basic-offset")
1043     (const :tag "* " :value *
1044            :menu-tag "*   Indent right half sh-basic-offset")
1045     (const :tag "/ " :value /
1046            :menu-tag "/   Indent left  half sh-basic-offset")))
1047
1048 (defcustom sh-indent-for-else 0
1049   "*How much to indent an else relative to an if.  Usually 0."
1050 :type `(choice
1051           (integer :menu-tag "A number (positive=>indent right)"
1052                    :tag "A number")
1053           (const :tag "--") ;; separator!
1054           ,@ sh-symbol-list
1055           )
1056 :group 'sh-indentation)
1057
1058 (defconst sh-number-or-symbol-list
1059   (append '((integer :menu-tag "A number (positive=>indent right)"
1060                      :tag "A number")
1061             (const :tag "--"))          ; separator
1062           sh-symbol-list))
1063
1064 (defcustom sh-indent-for-fi 0
1065   "*How much to indent a fi relative to an if.  Usually 0."
1066 :type `(choice ,@ sh-number-or-symbol-list )
1067 :group 'sh-indentation)
1068
1069 (defcustom sh-indent-for-done '0
1070   "*How much to indent a done relative to its matching stmt.  Usually 0."
1071 :type `(choice ,@ sh-number-or-symbol-list )
1072 :group 'sh-indentation)
1073
1074 (defcustom sh-indent-after-else '+
1075   "*How much to indent a statement after an else statement."
1076 :type `(choice ,@ sh-number-or-symbol-list )
1077 :group 'sh-indentation)
1078
1079 (defcustom sh-indent-after-if '+
1080   "*How much to indent a statement after an if statement.
1081 This includes lines after else and elif statements, too, but
1082 does not affect then else elif or fi statements themselves."
1083 :type `(choice ,@ sh-number-or-symbol-list )
1084 :group 'sh-indentation)
1085
1086 (defcustom sh-indent-for-then '+
1087   "*How much to indent a then relative to an if."
1088 :type `(choice ,@ sh-number-or-symbol-list )
1089 :group 'sh-indentation)
1090
1091 (defcustom sh-indent-for-do '*
1092   "*How much to indent a do statement.
1093 This is relative to the statement before the do, i.e. the
1094 while until or for statement."
1095 :type `(choice ,@ sh-number-or-symbol-list)
1096 :group 'sh-indentation)
1097
1098 (defcustom sh-indent-after-do '*
1099   "*How much to indent a line after a do statement.
1100 This is used when the do is the first word of the line.
1101 This is relative to the statement before the do, e.g. a
1102 while for repeat or select statement."
1103 :type `(choice ,@ sh-number-or-symbol-list)
1104 :group 'sh-indentation)
1105
1106 (defcustom sh-indent-after-loop-construct '+
1107   "*How much to indent a statement after a loop construct.
1108
1109 This variable is used when the keyword \"do\" is on the same line as the
1110 loop statement (e.g.  \"until\", \"while\" or \"for\").
1111 If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1112 :type `(choice ,@ sh-number-or-symbol-list)
1113 :group 'sh-indentation)
1114
1115
1116 (defcustom sh-indent-after-done 0
1117   "*How much to indent a statement after a \"done\" keyword.
1118 Normally this is 0, which aligns the \"done\" to the matching
1119 looping construct line.
1120 Setting it non-zero allows you to have the \"do\" statement on a line
1121 by itself and align the done under to do."
1122 :type `(choice ,@ sh-number-or-symbol-list)
1123 :group 'sh-indentation)
1124
1125 (defcustom sh-indent-for-case-label '+
1126   "*How much to indent a case label statement.
1127 This is relative to the line containing the case statement."
1128 :type `(choice ,@ sh-number-or-symbol-list)
1129 :group 'sh-indentation)
1130
1131 (defcustom sh-indent-for-case-alt '++
1132   "*How much to indent statements after the case label.
1133 This is relative to the line containing the case statement."
1134 :type `(choice ,@ sh-number-or-symbol-list)
1135 :group 'sh-indentation)
1136
1137
1138 (defcustom sh-indent-for-continuation '+
1139   "*How much to indent for a continuation statement."
1140 :type `(choice ,@ sh-number-or-symbol-list)
1141 :group 'sh-indentation)
1142
1143 (defcustom sh-indent-after-open '+
1144   "*How much to indent after a line with an opening parenthesis or brace.
1145 For an open paren after a function `sh-indent-after-function' is used."
1146 :type `(choice ,@ sh-number-or-symbol-list)
1147 :group 'sh-indentation)
1148
1149 (defcustom sh-indent-after-function '+
1150   "*How much to indent after a function line."
1151 :type `(choice ,@ sh-number-or-symbol-list)
1152 :group 'sh-indentation)
1153
1154 ;; These 2 are for the rc shell:
1155
1156 (defcustom sh-indent-after-switch '+
1157   "*How much to indent a case statement relative to the switch statement.
1158 This is for the rc shell."
1159 :type `(choice ,@ sh-number-or-symbol-list)
1160 :group 'sh-indentation)
1161
1162 (defcustom sh-indent-after-case '+
1163   "*How much to indent a statement relative to the case statement.
1164 This is for the rc shell."
1165 :type `(choice ,@ sh-number-or-symbol-list)
1166 :group 'sh-indentation)
1167
1168 ;; Internal use - not designed to be changed by the user:
1169
1170 (defun sh-mkword-regexpr (word)
1171   "Make a regexp which matches WORD as a word.
1172 This specifically excludes an occurrence of WORD followed by
1173 punctuation characters like '-'."
1174   (concat word "\\([^-a-z0-9_]\\|$\\)"))
1175
1176 (defconst sh-re-done (sh-mkword-regexpr "done"))
1177
1178
1179 (defconst sh-kws-for-done
1180   '((sh .  ( "while" "until" "for" ) )
1181     (bash . ( "while" "until" "for" "select"  ) )
1182     (ksh88 . ( "while" "until" "for" "select"  ) )
1183     (zsh .  ( "while" "until" "for" "repeat" "select" ) ) )
1184   "Which keywords can match the word `done' in this shell.")
1185
1186
1187 (defconst sh-indent-supported
1188   '((sh . t)
1189     (csh . nil)
1190     (rc . t))
1191   "Shell types that shell indenting can do something with.")
1192
1193 (defvar sh-indent-supported-here nil
1194   "Non-nil if we support indentation for the current buffer's shell type.")
1195
1196 (defconst sh-electric-rparen-needed
1197   '((sh . t))
1198   "Non-nil if the shell type needs an electric handling of case alternatives.")
1199
1200 (defconst sh-var-list
1201   '(
1202     sh-basic-offset sh-first-lines-indent sh-indent-after-case
1203     sh-indent-after-do sh-indent-after-done
1204     sh-indent-after-else
1205     sh-indent-after-if
1206     sh-indent-after-loop-construct
1207     sh-indent-after-open
1208     sh-indent-comment
1209     sh-indent-for-case-alt
1210     sh-indent-for-case-label
1211     sh-indent-for-continuation
1212     sh-indent-for-do
1213     sh-indent-for-done
1214     sh-indent-for-else
1215     sh-indent-for-fi
1216     sh-indent-for-then
1217     )
1218   "A list of variables used by script mode to control indentation.
1219 This list is used when switching between buffer-local and global
1220 values of variables, and for the commands using indentation styles.")
1221
1222 (defvar sh-make-vars-local t
1223   "*Controls whether indentation variables are local to the buffer.
1224 If non-nil, indentation variables are made local initially.
1225 If nil, you can later make the variables local by invoking
1226 command `sh-make-vars-local'.
1227 The default is t because I assume that in one Emacs session one is
1228 frequently editing existing scripts with different styles.")
1229
1230 \f
1231 ;; mode-command and utility functions
1232
1233 ;;;###autoload
1234 (put 'sh-mode 'mode-class 'special)
1235
1236 ;;;###autoload
1237 (define-derived-mode sh-mode fundamental-mode "Shell-script"
1238   "Major mode for editing shell scripts.
1239 This mode works for many shells, since they all have roughly the same syntax,
1240 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1241 Unless the file's magic number indicates the shell, your usual shell is
1242 assumed.  Since filenames rarely give a clue, they are not further analyzed.
1243
1244 This mode adapts to the variations between shells (see `sh-set-shell') by
1245 means of an inheritance based feature lookup (see `sh-feature').  This
1246 mechanism applies to all variables (including skeletons) that pertain to
1247 shell-specific features.
1248
1249 The default style of this mode is that of Rosenblatt's Korn shell book.
1250 The syntax of the statements varies with the shell being used.  The
1251 following commands are available, based on the current shell's syntax:
1252
1253 \\[sh-case]      case statement
1254 \\[sh-for]       for loop
1255 \\[sh-function]  function definition
1256 \\[sh-if]        if statement
1257 \\[sh-indexed-loop]      indexed loop from 1 to n
1258 \\[sh-while-getopts]     while getopts loop
1259 \\[sh-repeat]    repeat loop
1260 \\[sh-select]    select loop
1261 \\[sh-until]     until loop
1262 \\[sh-while]     while loop
1263
1264 For sh and rc shells indentation commands are:
1265 \\[sh-show-indent]      Show the variable controlling this line's indentation.
1266 \\[sh-set-indent]       Set then variable controlling this line's indentation.
1267 \\[sh-learn-line-indent]        Change the indentation variable so this line
1268 would indent to the way it currently is.
1269 \\[sh-learn-buffer-indent]  Set the indentation variables so the
1270 buffer indents as it currently is indented.
1271
1272
1273 \\[backward-delete-char-untabify]        Delete backward one position, even if it was a tab.
1274 \\[sh-newline-and-indent]        Delete unquoted space and indent new line same as this one.
1275 \\[sh-end-of-command]    Go to end of successive commands.
1276 \\[sh-beginning-of-command]      Go to beginning of successive commands.
1277 \\[sh-set-shell]         Set this buffer's shell, and maybe its magic number.
1278 \\[sh-execute-region]    Have optional header and region be executed in a subshell.
1279
1280 \\[sh-maybe-here-document]       Without prefix, following an unquoted < inserts here document.
1281 {, (, [, ', \", `
1282         Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1283
1284 If you generally program a shell different from your login shell you can
1285 set `sh-shell-file' accordingly.  If your shell's file name doesn't correctly
1286 indicate what shell it is use `sh-alias-alist' to translate.
1287
1288 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1289 with your script for an edit-interpret-debug cycle."
1290   (make-local-variable 'skeleton-end-hook)
1291   (make-local-variable 'paragraph-start)
1292   (make-local-variable 'paragraph-separate)
1293   (make-local-variable 'comment-start)
1294   (make-local-variable 'comment-start-skip)
1295   (make-local-variable 'require-final-newline)
1296   (make-local-variable 'sh-header-marker)
1297   (make-local-variable 'sh-shell-file)
1298   (make-local-variable 'sh-shell)
1299   (make-local-variable 'skeleton-pair-alist)
1300   (make-local-variable 'skeleton-pair-filter)
1301   (make-local-variable 'comint-dynamic-complete-functions)
1302   (make-local-variable 'comint-prompt-regexp)
1303   (make-local-variable 'font-lock-defaults)
1304   (make-local-variable 'skeleton-filter)
1305   (make-local-variable 'skeleton-newline-indent-rigidly)
1306   (make-local-variable 'sh-shell-variables)
1307   (make-local-variable 'sh-shell-variables-initialized)
1308   (make-local-variable 'imenu-generic-expression)
1309   (make-local-variable 'sh-indent-supported-here)
1310   (setq skeleton-end-hook (lambda ()
1311                             (or (eolp) (newline) (indent-relative)))
1312         paragraph-start (concat page-delimiter "\\|$")
1313         paragraph-separate paragraph-start
1314         comment-start "# "
1315         comint-dynamic-complete-functions sh-dynamic-complete-functions
1316         ;; we can't look if previous line ended with `\'
1317         comint-prompt-regexp "^[ \t]*"
1318         font-lock-defaults
1319         `((sh-font-lock-keywords
1320            sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1321           nil nil
1322           ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1323           (font-lock-syntactic-keywords
1324            ;; Copy so we can use destructive update in `sh-font-lock-heredoc'.
1325            . ,(copy-sequence sh-font-lock-syntactic-keywords))
1326           (font-lock-syntactic-face-function
1327            . sh-font-lock-syntactic-face-function))
1328         skeleton-pair-alist '((?` _ ?`))
1329         skeleton-pair-filter 'sh-quoted-p
1330         skeleton-further-elements '((< '(- (min sh-indentation
1331                                                 (current-column)))))
1332         skeleton-filter 'sh-feature
1333         skeleton-newline-indent-rigidly t
1334         sh-indent-supported-here nil)
1335   (set (make-local-variable 'parse-sexp-ignore-comments) t)
1336   ;; Parse or insert magic number for exec, and set all variables depending
1337   ;; on the shell thus determined.
1338   (let ((interpreter
1339          (save-excursion
1340            (goto-char (point-min))
1341            (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1342                   (match-string 2))
1343                  ((and buffer-file-name
1344                        (string-match "\\.m?spec$" buffer-file-name))
1345                   "rpm")))))
1346     (sh-set-shell (or interpreter sh-shell-file) nil nil))
1347   ;; XEmacs change
1348   (if sh-mode-menu
1349       (easy-menu-add sh-mode-menu)))
1350
1351 ;;;###autoload
1352 (defalias 'shell-script-mode 'sh-mode)
1353
1354 ;;; XEmacs change
1355 (put 'sh-mode 'font-lock-defaults
1356      `((sh-font-lock-keywords
1357         sh-font-lock-keywords-1
1358         sh-font-lock-keywords-2)))
1359 ;;       ,sh-font-lock-keywords-only
1360 ;;       nil
1361 ;;       ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w"))))
1362
1363
1364 (defun sh-font-lock-keywords (&optional keywords)
1365   "Function to get simple fontification based on `sh-font-lock-keywords'.
1366 This adds rules for comments and assignments."
1367   (sh-feature sh-font-lock-keywords
1368               (when (stringp (sh-feature sh-assignment-regexp))
1369                 (lambda (list)
1370                   `((,(sh-feature sh-assignment-regexp)
1371                      1 font-lock-variable-name-face)
1372                     ,@keywords
1373                     ,@list)))))
1374
1375 (defun sh-font-lock-keywords-1 (&optional builtins)
1376   "Function to get better fontification including keywords."
1377   (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
1378                           (mapconcat 'identity
1379                                      (sh-feature sh-leading-keywords)
1380                                      "\\|")
1381                           "\\)[ \t]+\\)?\\("
1382                           (mapconcat 'identity
1383                                      (append (sh-feature sh-leading-keywords)
1384                                              (sh-feature sh-other-keywords))
1385                                      "\\|")
1386                           "\\)")))
1387     (sh-font-lock-keywords
1388      `(,@(if builtins
1389              `((,(concat keywords "[ \t]+\\)?\\("
1390                          (mapconcat 'identity (sh-feature sh-builtins) "\\|")
1391                          "\\)\\>")
1392                 (2 font-lock-keyword-face nil t)
1393                 (6 font-lock-builtin-face))
1394                ,@(sh-feature sh-font-lock-keywords-2)))
1395          (,(concat keywords "\\)\\>")
1396           2 font-lock-keyword-face)
1397          ,@(sh-feature sh-font-lock-keywords-1)))))
1398
1399 (defun sh-font-lock-keywords-2 ()
1400   "Function to get better fontification including keywords and builtins."
1401   (sh-font-lock-keywords-1 t))
1402
1403
1404 (defvar sh-regexp-for-done nil
1405   "A buffer-local regexp to match opening keyword for done.")
1406
1407 (defvar sh-kw-alist nil
1408   "A buffer-local, since it is shell-type dependent, list of keywords.")
1409
1410 ;; ( key-word  first-on-this  on-prev-line )
1411 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1412 ;; having 3 elements:
1413 ;;   a keyword
1414 ;;   a rule to check when the keyword appears on "this" line
1415 ;;   a rule to check when the keyword appears on "the previous" line
1416 ;; The keyword is usually a string and is the first word on a line.
1417 ;; If this keyword appears on the line whose indentation is to be
1418 ;; calculated, the rule in element 2 is called.  If this returns
1419 ;; non-zero, the resulting point (which may be changed by the rule)
1420 ;; is used as the default indentation.
1421 ;; If it returned false or the keyword was not found in the table,
1422 ;; then the keyword from the previous line is looked up and the rule
1423 ;; in element 3 is called.  In this case, however,
1424 ;; `sh-get-indent-info' does not stop but may keep going and test
1425 ;; other keywords against rules in element 3.  This is because the
1426 ;; preceding line could have, for example, an opening "if" and an
1427 ;; opening "while" keyword and we need to add the indentation offsets
1428 ;; for both.
1429 ;;
1430 (defconst sh-kw
1431   '((sh
1432      ("if" nil sh-handle-prev-if)
1433      ("elif" sh-handle-this-else sh-handle-prev-else)
1434      ("else" sh-handle-this-else sh-handle-prev-else)
1435      ("fi" sh-handle-this-fi sh-handle-prev-fi)
1436      ("then" sh-handle-this-then sh-handle-prev-then)
1437      ("(" nil sh-handle-prev-open)
1438      ("{" nil sh-handle-prev-open)
1439      ("[" nil sh-handle-prev-open)
1440      ("}" sh-handle-this-close nil)
1441      (")" sh-handle-this-close nil)
1442      ("]" sh-handle-this-close nil)
1443      ("case" nil sh-handle-prev-case)
1444      ("esac" sh-handle-this-esac sh-handle-prev-esac)
1445      (case-label nil sh-handle-after-case-label) ;; ???
1446      (";;" nil sh-handle-prev-case-alt-end) ;; ???
1447      ("done" sh-handle-this-done sh-handle-prev-done)
1448      ("do" sh-handle-this-do sh-handle-prev-do))
1449
1450     ;; Note: we don't need specific stuff for bash and zsh shells;
1451     ;; the regexp `sh-regexp-for-done' handles the extra keywords
1452     ;; these shells use.
1453     (rc
1454      ("{" nil sh-handle-prev-open)
1455      ("}" sh-handle-this-close nil)
1456      ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1457
1458
1459 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1460   "Set this buffer's shell to SHELL (a string).
1461 Makes this script executable via `executable-set-magic', and sets up the
1462 proper starting #!-line, if INSERT-FLAG is non-nil.
1463 Calls the value of `sh-set-shell-hook' if set."
1464   (interactive (list (completing-read "Name or path of shell: "
1465                                       ;; XEmacs change
1466                                       sh-interpreter-mode-alist
1467                                       (lambda (x) (eq (cdr x) 'sh-mode)))
1468                      (eq executable-query 'function)
1469                      t))
1470   (if (string-match "\\.exe\\'" shell)
1471       (setq shell (substring shell 0 (match-beginning 0))))
1472   (setq sh-shell (intern (file-name-nondirectory shell))
1473         sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1474                      sh-shell))
1475   (if insert-flag
1476       (setq sh-shell-file
1477             (executable-set-magic shell (sh-feature sh-shell-arg)
1478                                   no-query-flag insert-flag)))
1479   (setq require-final-newline (sh-feature sh-require-final-newline)
1480 ;;;     local-abbrev-table (sh-feature sh-abbrevs)
1481         comment-start-skip "#+[\t ]*"
1482         mode-line-process (format "[%s]" sh-shell)
1483         sh-shell-variables nil
1484         sh-shell-variables-initialized nil
1485         imenu-generic-expression (sh-feature sh-imenu-generic-expression)
1486         imenu-case-fold-search nil)
1487   (dolist (var (sh-feature sh-variables))
1488     (sh-remember-variable var))
1489   (make-local-variable 'indent-line-function)
1490   (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1491       (progn
1492         (message "Setting up indent for shell type %s" sh-shell)
1493         (set (make-local-variable 'parse-sexp-lookup-properties) t)
1494         (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1495         (let ((regexp (sh-feature sh-kws-for-done)))
1496           (if regexp
1497               (set (make-local-variable 'sh-regexp-for-done)
1498                    (sh-mkword-regexpr (regexp-opt regexp t)))))
1499         (message "setting up indent stuff")
1500         ;; sh-mode has already made indent-line-function local
1501         ;; but do it in case this is called before that.
1502         (setq indent-line-function 'sh-indent-line)
1503         (if sh-make-vars-local
1504             (sh-make-vars-local))
1505         (message "Indentation setup for shell type %s" sh-shell))
1506     (message "No indentation for this shell type.")
1507     (setq indent-line-function 'sh-basic-indent-line))
1508   (run-hooks 'sh-set-shell-hook))
1509
1510
1511
1512 (defun sh-feature (list &optional function)
1513   "Index ALIST by the current shell.
1514 If ALIST isn't a list where every element is a cons, it is returned as is.
1515 Else indexing follows an inheritance logic which works in two ways:
1516
1517   - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1518     the alist contains no value for the current shell.
1519     The ultimate default is always `sh'.
1520
1521   - If the value thus looked up is a list starting with `eval' its `cdr' is
1522     first evaluated.  If that is also a list and the first argument is a
1523     symbol in ALIST it is not evaluated, but rather recursively looked up in
1524     ALIST to allow the function called to define the value for one shell to be
1525     derived from another shell.  While calling the function, is the car of the
1526     alist element is the current shell.
1527     The value thus determined is physically replaced into the alist.
1528
1529 Optional FUNCTION is applied to the determined value and the result is cached
1530 in ALIST."
1531   (or (if (consp list)
1532           (let ((l list))
1533             (while (and l (consp (car l)))
1534               (setq l (cdr l)))
1535             (if l list)))
1536       (if function
1537           (cdr (assoc (setq function (cons sh-shell function)) list)))
1538       (let ((sh-shell sh-shell)
1539             elt val)
1540         (while (and sh-shell
1541                     (not (setq elt (assq sh-shell list))))
1542           (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1543         ;; If the shell is not known, treat it as sh.
1544         (unless elt
1545           (setq elt (assq 'sh list)))
1546         (if (and (consp (setq val (cdr elt)))
1547                  (eq (car val) 'eval))
1548             (setcdr elt
1549                     (setq val
1550                           (eval (if (consp (setq val (cdr val)))
1551                                     (let ((sh-shell (car (cdr val)))
1552                                           function)
1553                                       (if (assq sh-shell list)
1554                                           (setcar (cdr val)
1555                                                   (list 'quote
1556                                                         (sh-feature list))))
1557                                       val)
1558                                   val)))))
1559         (if function
1560             (nconc list
1561                    (list (cons function
1562                                (setq sh-shell (car function)
1563                                      val (funcall (cdr function) val))))))
1564         val)))
1565
1566
1567
1568 ;;; I commented this out because nobody calls it -- rms.
1569 ;;;(defun sh-abbrevs (ancestor &rest list)
1570 ;;;  "Iff it isn't, define the current shell as abbrev table and fill that.
1571 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1572 ;;;table or a list of (NAME1 EXPANSION1 ...).  In addition it will define abbrevs
1573 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
1574 ;;;EXPANSION may be either a string or a skeleton command."
1575 ;;;  (or (if (boundp sh-shell)
1576 ;;;       (symbol-value sh-shell))
1577 ;;;      (progn
1578 ;;;     (if (listp ancestor)
1579 ;;;         (nconc list ancestor))
1580 ;;;     (define-abbrev-table sh-shell ())
1581 ;;;     (if (vectorp ancestor)
1582 ;;;         (mapatoms (lambda (atom)
1583 ;;;                     (or (eq atom 0)
1584 ;;;                         (define-abbrev (symbol-value sh-shell)
1585 ;;;                           (symbol-name atom)
1586 ;;;                           (symbol-value atom)
1587 ;;;                           (symbol-function atom))))
1588 ;;;                   ancestor))
1589 ;;;     (while list
1590 ;;;       (define-abbrev (symbol-value sh-shell)
1591 ;;;         (car list)
1592 ;;;         (if (stringp (car (cdr list)))
1593 ;;;             (car (cdr list))
1594 ;;;           "")
1595 ;;;         (if (symbolp (car (cdr list)))
1596 ;;;             (car (cdr list))))
1597 ;;;       (setq list (cdr (cdr list)))))
1598 ;;;      (symbol-value sh-shell)))
1599
1600
1601 (defun sh-append (ancestor &rest list)
1602   "Return list composed of first argument (a list) physically appended to rest."
1603   (nconc list ancestor))
1604
1605
1606 (defun sh-modify (skeleton &rest list)
1607   "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1608   (setq skeleton (copy-sequence skeleton))
1609   (while list
1610     (setcar (or (nthcdr (car list) skeleton)
1611                 (error "Index %d out of bounds" (car list)))
1612             (car (cdr list)))
1613     (setq list (nthcdr 2 list)))
1614   skeleton)
1615
1616
1617 (defun sh-basic-indent-line ()
1618   "Indent a line for Sh mode (shell script mode).
1619 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1620 Lines containing only comments are considered empty."
1621   (interactive)
1622   (let ((previous (save-excursion
1623                     (while (and (progn (beginning-of-line)
1624                                        (not (bobp)))
1625                                 (progn
1626                                   (forward-line -1)
1627                                   (back-to-indentation)
1628                                   (or (eolp)
1629                                       (eq (following-char) ?#)))))
1630                     (current-column)))
1631         current)
1632     (save-excursion
1633       (indent-to (if (eq this-command 'newline-and-indent)
1634                      previous
1635                    (if (< (current-column)
1636                           (setq current (progn (back-to-indentation)
1637                                                (current-column))))
1638                        (if (eolp) previous 0)
1639                      (delete-region (point)
1640                                     (progn (beginning-of-line) (point)))
1641                      (if (eolp)
1642                          (max previous (* (1+ (/ current sh-indentation))
1643                                           sh-indentation))
1644                        (* (1+ (/ current sh-indentation)) sh-indentation))))))
1645     (if (< (current-column) (current-indentation))
1646         (skip-chars-forward " \t"))))
1647
1648
1649 (defun sh-execute-region (start end &optional flag)
1650   "Pass optional header and region to a subshell for noninteractive execution.
1651 The working directory is that of the buffer, and only environment variables
1652 are already set which is why you can mark a header within the script.
1653
1654 With a positive prefix ARG, instead of sending region, define header from
1655 beginning of buffer to point.  With a negative prefix ARG, instead of sending
1656 region, clear header."
1657   (interactive "r\nP")
1658   (if flag
1659       (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1660                                  (point-marker)))
1661     (if sh-header-marker
1662         (save-excursion
1663           (let (buffer-undo-list)
1664             (goto-char sh-header-marker)
1665             (append-to-buffer (current-buffer) start end)
1666             (shell-command-on-region (point-min)
1667                                      (setq end (+ sh-header-marker
1668                                                   (- end start)))
1669                                      sh-shell-file)
1670             (delete-region sh-header-marker end)))
1671       (shell-command-on-region start end (concat sh-shell-file " -")))))
1672
1673
1674 (defun sh-remember-variable (var)
1675   "Make VARIABLE available for future completing reads in this buffer."
1676   (or (< (length var) sh-remember-variable-min)
1677       (getenv var)
1678       (assoc var sh-shell-variables)
1679       (push (cons var var) sh-shell-variables))
1680   var)
1681
1682
1683
1684 (defun sh-quoted-p ()
1685   "Is point preceded by an odd number of backslashes?"
1686   (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1687 \f
1688 ;; Indentation stuff.
1689 (defun sh-must-be-shell-mode ()
1690   "Signal an error if not in Shell-script mode."
1691   (unless (eq major-mode 'sh-mode)
1692     (error "This buffer is not in Shell-script mode")))
1693
1694 (defun sh-must-support-indent ()
1695   "*Signal an error if the shell type for this buffer is not supported.
1696 Also, the buffer must be in Shell-script mode."
1697   (sh-must-be-shell-mode)
1698   (unless sh-indent-supported-here
1699     (error "This buffer's shell type is not supported for this command")))
1700
1701 (defun sh-make-vars-local ()
1702   "Make the indentation variables local to this buffer.
1703 Normally they already are local.  This command is provided in case
1704 variable `sh-make-vars-local' has been set to nil.
1705
1706 To revert all these variables to the global values, use
1707 command `sh-reset-indent-vars-to-global-values'."
1708   (interactive)
1709   (sh-must-be-shell-mode)
1710   (mapcar 'make-local-variable sh-var-list)
1711   (message "Indentation variable are now local."))
1712
1713 (defun sh-reset-indent-vars-to-global-values ()
1714   "Reset local indentation variables to the global values.
1715 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1716   (interactive)
1717   (sh-must-be-shell-mode)
1718   (mapcar 'kill-local-variable sh-var-list)
1719   (if sh-make-vars-local
1720       (mapcar 'make-local-variable sh-var-list)))
1721
1722
1723 ;; Theoretically these are only needed in shell and derived modes.
1724 ;; However, the routines which use them are only called in those modes.
1725 (defconst sh-special-keywords "then\\|do")
1726
1727 (defun sh-help-string-for-variable (var)
1728   "Construct a string for `sh-read-variable' when changing variable VAR ."
1729   (let ((msg (documentation-property var 'variable-documentation))
1730         (msg2 ""))
1731     (unless (memq var '(sh-first-lines-indent sh-indent-comment))
1732       (setq msg2
1733             (format "\n
1734 You can enter a number (positive to increase indentation,
1735 negative to decrease indentation, zero for no change to indentation).
1736
1737 Or, you can enter one of the following symbols which are relative to
1738 the value of variable `sh-basic-offset'
1739 which in this buffer is currently %s.
1740
1741 \t%s."
1742                     sh-basic-offset
1743                     (mapconcat  (lambda (x)
1744                                   (nth (1- (length x)) x))
1745                                 sh-symbol-list  "\n\t"))))
1746     (concat
1747      ;; The following shows the global not the local value!
1748      ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1749      msg msg2)))
1750
1751 (defun sh-read-variable (var)
1752   "Read a new value for indentation variable VAR."
1753   (interactive "*variable? ") ;; to test
1754   (let ((minibuffer-help-form `(sh-help-string-for-variable
1755                                 (quote ,var)))
1756         val)
1757     (setq val (read-from-minibuffer
1758                (format "New value for %s (press %s for help): "
1759                        var  (single-key-description help-char))
1760                (format "%s" (symbol-value var))
1761                nil t))
1762     val))
1763
1764
1765
1766 (defun sh-in-comment-or-string (start)
1767   "Return non-nil if START is in a comment or string."
1768   (save-excursion
1769     (let (state)
1770       (beginning-of-line)
1771       (setq state (parse-partial-sexp (point) start nil nil nil t))
1772       (or (nth 3 state)(nth 4 state)))))
1773
1774 (defun sh-goto-matching-if ()
1775   "Go to the matching if for a fi.
1776 This handles nested if..fi pairs."
1777   (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1778     (if found
1779         (goto-char found))))
1780
1781
1782 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1783 ;; line whose indentation is being handled contain XXX;
1784 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1785
1786 (defun sh-handle-prev-if ()
1787   (list '(+ sh-indent-after-if)))
1788
1789 (defun sh-handle-this-else ()
1790   (if (sh-goto-matching-if)
1791       ;; (list "aligned to if")
1792       (list "aligned to if" '(+ sh-indent-for-else))
1793     nil
1794     ))
1795
1796 (defun sh-handle-prev-else ()
1797   (if (sh-goto-matching-if)
1798       (list  '(+ sh-indent-after-if))
1799     ))
1800
1801 (defun sh-handle-this-fi ()
1802   (if (sh-goto-matching-if)
1803       (list "aligned to if" '(+ sh-indent-for-fi))
1804     nil
1805     ))
1806
1807 (defun sh-handle-prev-fi ()
1808   ;; Why do we have this rule?  Because we must go back to the if
1809   ;; to get its indent.  We may continue back from there.
1810   ;; We return nil because we don't have anything to add to result,
1811   ;; the side affect of setting align-point is all that matters.
1812   ;; we could return a comment (a string) but I can't think of a good one...
1813   (sh-goto-matching-if)
1814   nil)
1815
1816 (defun sh-handle-this-then ()
1817   (let ((p (sh-goto-matching-if)))
1818     (if p
1819         (list '(+ sh-indent-for-then))
1820       )))
1821
1822 (defun sh-handle-prev-then ()
1823   (let ((p (sh-goto-matching-if)))
1824     (if p
1825         (list '(+ sh-indent-after-if))
1826       )))
1827
1828 (defun sh-handle-prev-open ()
1829   (save-excursion
1830     (let ((x (sh-prev-stmt)))
1831       (if (and x
1832                (progn
1833                  (goto-char x)
1834                  (or
1835                   (looking-at "function\\b")
1836                   (looking-at "\\s-*\\S-+\\s-*()")
1837                   )))
1838           (list '(+ sh-indent-after-function))
1839         (list '(+ sh-indent-after-open)))
1840       )))
1841
1842 (defun sh-handle-this-close ()
1843   (forward-char 1) ;; move over ")"
1844   (if (sh-safe-forward-sexp -1)
1845       (list "aligned to opening paren")))
1846
1847 (defun sh-goto-matching-case ()
1848   (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1849     (if found (goto-char found))))
1850
1851 (defun sh-handle-prev-case ()
1852   ;; This is typically called when point is on same line as a case
1853   ;; we shouldn't -- and can't find prev-case
1854   (if (looking-at ".*\\<case\\>")
1855       (list '(+ sh-indent-for-case-label))
1856     (error "We don't seem to be on a line with a case"))) ;; debug
1857
1858 (defun sh-handle-this-esac ()
1859   (if (sh-goto-matching-case)
1860       (list "aligned to matching case")))
1861
1862 (defun sh-handle-prev-esac ()
1863   (if (sh-goto-matching-case)
1864       (list "matching case")))
1865
1866 (defun sh-handle-after-case-label ()
1867   (if (sh-goto-matching-case)
1868       (list '(+ sh-indent-for-case-alt))))
1869
1870 (defun sh-handle-prev-case-alt-end ()
1871   (if (sh-goto-matching-case)
1872       (list '(+ sh-indent-for-case-label))))
1873
1874 (defun sh-safe-forward-sexp (&optional arg)
1875   "Try and do a `forward-sexp', but do not error.
1876 Return new point if successful, nil if an error occurred."
1877   (condition-case nil
1878       (progn
1879         (forward-sexp (or arg 1))
1880         (point))        ;; return point if successful
1881     (error
1882      (sh-debug "oops!(1) %d" (point))
1883      nil))) ;; return nil if fail
1884
1885 (defun sh-goto-match-for-done ()
1886   (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
1887     (if found
1888         (goto-char found))))
1889
1890 (defun sh-handle-this-done ()
1891   (if (sh-goto-match-for-done)
1892       (list  "aligned to do stmt"  '(+ sh-indent-for-done))))
1893
1894 (defun sh-handle-prev-done ()
1895   (if (sh-goto-match-for-done)
1896       (list "previous done")))
1897
1898 (defun sh-handle-this-do ()
1899   (if (sh-goto-match-for-done)
1900       (list '(+ sh-indent-for-do))))
1901
1902 (defun sh-handle-prev-do ()
1903   (cond
1904    ((save-restriction
1905       (narrow-to-region
1906        (point)
1907        (save-excursion
1908          (beginning-of-line)
1909          (point)))
1910       (sh-goto-match-for-done))
1911     (sh-debug "match for done found on THIS line")
1912     (list '(+ sh-indent-after-loop-construct)))
1913    ((sh-goto-match-for-done)
1914     (sh-debug "match for done found on PREV line")
1915     (list '(+ sh-indent-after-do)))
1916    (t
1917     (message "match for done NOT found")
1918     nil)))
1919
1920 ;; for rc:
1921 (defun sh-find-prev-switch ()
1922   "Find the line for the switch keyword matching this line's case keyword."
1923   (re-search-backward "\\<switch\\>" nil t))
1924
1925 (defun sh-handle-this-rc-case ()
1926   (if (sh-find-prev-switch)
1927       (list  '(+ sh-indent-after-switch))
1928     ;; (list  '(+ sh-indent-for-case-label))
1929     nil))
1930
1931 (defun sh-handle-prev-rc-case ()
1932   (list '(+ sh-indent-after-case)))
1933
1934 (defun sh-check-rule (n thing)
1935   (let ((rule (nth n (assoc thing sh-kw-alist)))
1936         (val nil))
1937     (if rule
1938         (progn
1939           (setq val (funcall rule))
1940           (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1941                     n thing (point) rule val)))
1942     val))
1943
1944
1945 (defun sh-get-indent-info ()
1946   "Return indent-info for this line.
1947 This is a list.  nil means the line is to be left as is.
1948 Otherwise it contains one or more of the following sublists:
1949 \(t NUMBER\)   NUMBER is the base location in the buffer that indentation is
1950              relative to.  If present, this is always the first of the
1951              sublists.  The indentation of the line in question is
1952              derived from the indentation of this point, possibly
1953              modified by subsequent sublists.
1954 \(+ VAR\)
1955 \(- VAR\)      Get the value of variable VAR and add to or subtract from
1956              the indentation calculated so far.
1957 \(= VAR\)            Get the value of variable VAR and *replace* the
1958              indentation with its value.  This only occurs for
1959              special variables such as `sh-indent-comment'.
1960 STRING       This is ignored for the purposes of calculating
1961              indentation, it is printed in certain cases to help show
1962              what the indentation is based on."
1963   ;; See comments before `sh-kw'.
1964   (save-excursion
1965     (let ((prev-kw nil)
1966           (prev-stmt nil)
1967           (have-result nil)
1968           depth-bol depth-eol
1969           this-kw
1970           (state nil)
1971           state-bol
1972           (depth-prev-bol nil)
1973           start
1974           func val
1975           (result nil)
1976           prev-lines-indent
1977           (prev-list nil)
1978           (this-list nil)
1979           (align-point nil)
1980           prev-line-end x)
1981       (beginning-of-line)
1982       ;; Note: setting result to t means we are done and will return nil.
1983       ;;(This function never returns just t.)
1984       (cond
1985        ((or (and (boundp 'font-lock-string-face)
1986                  (eq (get-text-property (point) 'face) font-lock-string-face))
1987             (eq (get-text-property (point) 'face) sh-heredoc-face))
1988         (setq result t)
1989         (setq have-result t))
1990        ((looking-at "\\s-*#")           ; was (equal this-kw "#")
1991         (if (bobp)
1992             (setq result t) ;; return nil if 1st line!
1993           (setq result (list '(= sh-indent-comment)))
1994           ;; we still need to get previous line in case
1995           ;; sh-indent-comment is t (indent as normal)
1996           (setq align-point (sh-prev-line nil))
1997           (setq have-result nil)
1998           ))
1999        ) ;; cond
2000
2001       (unless have-result
2002         ;; Continuation lines are handled specially
2003         (if (sh-this-is-a-continuation)
2004             (progn
2005               ;; We assume the line being continued is already
2006               ;; properly indented...
2007               ;; (setq prev-line-end (sh-prev-line))
2008               (setq align-point (sh-prev-line nil))
2009               (setq result (list '(+ sh-indent-for-continuation)))
2010               (setq have-result t))
2011           (beginning-of-line)
2012           (skip-chars-forward " \t")
2013           (setq this-kw (sh-get-kw)))
2014
2015         ;; Handle "this" keyword:  first word on the line we're
2016         ;; calculating indentation info for.
2017         (if this-kw
2018             (if (setq val (sh-check-rule 1 this-kw))
2019                 (progn
2020                   (setq align-point (point))
2021                   (sh-debug
2022                    "this - setting align-point to %d" align-point)
2023                   (setq result (append result val))
2024                   (setq have-result t)
2025                   ;; set prev-line to continue processing remainder
2026                   ;; of this line as a previous line
2027                   (setq prev-line-end (point))
2028                   ))))
2029
2030       (unless have-result
2031         (setq prev-line-end (sh-prev-line 'end)))
2032
2033       (if prev-line-end
2034           (save-excursion
2035             ;; We start off at beginning of this line.
2036             ;; Scan previous statements while this is <=
2037             ;; start of previous line.
2038             (setq start (point)) ;; for debug only
2039             (goto-char prev-line-end)
2040             (setq x t)
2041             (while (and x (setq x  (sh-prev-thing)))
2042               (sh-debug "at %d x is: %s  result is: %s" (point) x result)
2043               (cond
2044                ((and (equal x ")")
2045                      (equal (get-text-property (1- (point)) 'syntax-table)
2046                             sh-st-punc))
2047                 (sh-debug "Case label) here")
2048                 (setq x 'case-label)
2049                 (if (setq val (sh-check-rule 2 x))
2050                     (progn
2051                       (setq result (append result val))
2052                       (setq align-point (point))))
2053                 (forward-char -1)
2054                 (skip-chars-forward "[a-z0-9]*?")
2055                 )
2056                ((string-match "[])}]" x)
2057                 (setq x (sh-safe-forward-sexp -1))
2058                 (if x
2059                     (progn
2060                       (setq align-point (point))
2061                       (setq result (append result
2062                                            (list "aligned to opening paren")))
2063                       )))
2064                ((string-match "[[({]" x)
2065                 (sh-debug "Checking special thing: %s" x)
2066                 (if (setq val (sh-check-rule 2 x))
2067                     (setq result (append result val)))
2068                 (forward-char -1)
2069                 (setq align-point (point)))
2070                ((string-match "[\"'`]" x)
2071                 (sh-debug "Skipping back for %s" x)
2072                 ;; this was oops-2
2073                 (setq x (sh-safe-forward-sexp -1)))
2074                ((stringp x)
2075                 (sh-debug "Checking string %s at %s" x (point))
2076                 (if (setq val (sh-check-rule 2 x))
2077                     ;; (or (eq t (car val))
2078                     ;; (eq t (car (car val))))
2079                     (setq result (append result val)))
2080                 ;; not sure about this test Wed Jan 27 23:48:35 1999
2081                 (setq align-point (point))
2082                 (unless (bolp)
2083                   (forward-char -1)))
2084                (t
2085                 (error "Don't know what to do with %s" x))
2086                )
2087               ) ;; while
2088             (sh-debug "result is %s" result)
2089             )
2090         (sh-debug "No prev line!")
2091         (sh-debug "result: %s  align-point: %s" result align-point)
2092         )
2093
2094       (if align-point
2095           ;; was: (setq result (append result (list (list t align-point))))
2096           (setq result (append  (list (list t align-point)) result))
2097         )
2098       (sh-debug "result is now: %s" result)
2099
2100       (or result
2101           (if prev-line-end
2102               (setq result (list (list t prev-line-end)))
2103             (setq result (list (list '= 'sh-first-lines-indent)))
2104             ))
2105
2106       (if (eq result t)
2107           (setq result nil))
2108       (sh-debug  "result is: %s" result)
2109       result
2110       ) ;; let
2111     ))
2112
2113
2114 (defun sh-get-indent-var-for-line (&optional info)
2115   "Return the variable controlling indentation for this line.
2116 If there is not [just] one such variable, return a string
2117 indicating the problem.
2118 If INFO is supplied it is used, else it is calculated."
2119   (let ((var nil)
2120         (result nil)
2121         (reason nil)
2122         sym elt)
2123     (or info
2124         (setq info (sh-get-indent-info)))
2125     (if (null info)
2126         (setq result "this line to be left as is")
2127       (while (and info (null result))
2128         (setq elt (car info))
2129         (cond
2130          ((stringp elt)
2131           (setq reason elt)
2132           )
2133          ((not (listp elt))
2134           (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2135          ;; so it is a list
2136          ((eq t (car elt))
2137           ) ;; nothing
2138          ((symbolp  (setq sym (nth 1 elt)))
2139           ;; A bit of a kludge - when we see the sh-indent-comment
2140           ;; ignore other variables.  Otherwise it is tricky to
2141           ;; "learn" the comment indentation.
2142           (if (eq var 'sh-indent-comment)
2143               (setq result var)
2144             (if var
2145                 (setq result
2146                       "this line is controlled by more than 1 variable.")
2147               (setq var sym))))
2148          (t
2149           (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2150         (setq info (cdr info))
2151         ))
2152     (or result
2153         (setq result var))
2154     (or result
2155         (setq result reason))
2156     (if (null result)
2157         ;; e.g. just had (t POS)
2158         (setq result "line has default indentation"))
2159     result))
2160
2161
2162
2163 ;; Finding the previous line isn't trivial.
2164 ;; We must *always* go back one more and see if that is a continuation
2165 ;; line -- it is the PREVIOUS line which is continued, not the one
2166 ;; we are going to!
2167 ;; Also, we want to treat a whole "here document" as one big line,
2168 ;; because we may want to a align to the beginning of it.
2169 ;;
2170 ;; What we do:
2171 ;; - go back to previous non-empty line
2172 ;; - if this is in a here-document, go to the beginning of it
2173 ;; - while previous line is continued, go back one line
2174 (defun sh-prev-line (&optional end)
2175   "Back to end of previous non-comment non-empty line.
2176 Go to beginning of logical line unless END is non-nil, in which case
2177 we go to the end of the previous line and do not check for continuations."
2178   (sh-must-be-shell-mode)
2179   (save-excursion
2180     (beginning-of-line)
2181     (forward-comment (- (point-max)))
2182     (unless end (beginning-of-line))
2183     (when (and (not (bobp))
2184                (equal (get-text-property (1- (point)) 'face)
2185                       sh-heredoc-face))
2186       (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2187         (when p1
2188           (goto-char p1)
2189           (if end
2190               (end-of-line)
2191             (beginning-of-line)))))
2192     (unless end
2193       ;; we must check previous lines to see if they are continuation lines
2194       ;; if so, we must return position of first of them
2195       (while (and (sh-this-is-a-continuation)
2196                   (>= 0 (forward-line -1))))
2197       (beginning-of-line)
2198       (skip-chars-forward " \t"))
2199     (point)))
2200
2201
2202 (defun sh-prev-stmt ()
2203   "Return the address of the previous stmt or nil."
2204   ;; This is used when we are trying to find a matching keyword.
2205   ;; Searching backward for the keyword would certainly be quicker, but
2206   ;; it is hard to remove "false matches" -- such as if the keyword
2207   ;; appears in a string or quote.  This way is slower, but (I think) safer.
2208   (interactive)
2209   (save-excursion
2210     (let ((going t)
2211           (start (point))
2212           (found nil)
2213           (prev nil))
2214       (skip-chars-backward " \t;|&({[")
2215       (while (and (not found)
2216                   (not (bobp))
2217                   going)
2218         ;; Do a backward-sexp if possible, else backup bit by bit...
2219         (if (sh-safe-forward-sexp -1)
2220             (progn
2221               (if (looking-at sh-special-keywords)
2222                   (progn
2223                     (setq found prev))
2224                 (setq prev (point))
2225                 ))
2226           ;; backward-sexp failed
2227           (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2228               (forward-char -1))
2229           (if (bolp)
2230               (let ((back (sh-prev-line nil)))
2231                 (if back
2232                     (goto-char back)
2233                   (setq going nil)))))
2234         (unless found
2235           (skip-chars-backward " \t")
2236           (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2237                   (eq (char-before) ?\;)
2238                   (looking-at "\\s-*[|&]"))
2239               (setq found (point)))))
2240       (if found
2241           (goto-char found))
2242       (if found
2243           (progn
2244             (skip-chars-forward " \t|&({[")
2245             (setq found (point))))
2246       (if (>= (point) start)
2247           (progn
2248             (debug "We didn't move!")
2249             (setq found nil))
2250         (or found
2251             (sh-debug "Did not find prev stmt.")))
2252       found)))
2253
2254
2255 (defun sh-get-word ()
2256   "Get a shell word skipping whitespace from point."
2257   (interactive)
2258   (skip-chars-forward "\t ")
2259   (let ((start (point)))
2260     (while
2261         (if (looking-at "[\"'`]")
2262             (sh-safe-forward-sexp)
2263           ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2264           (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2265           ))
2266     (buffer-substring start (point))
2267     ))
2268
2269 (defun sh-prev-thing ()
2270   "Return the previous thing this logical line."
2271   ;; This is called when `sh-get-indent-info' is working backwards on
2272   ;; the previous line(s) finding what keywords may be relevant for
2273   ;; indenting.  It moves over sexps if possible, and will stop
2274   ;; on a ; and at the beginning of a line if it is not a continuation
2275   ;; line.
2276   ;;
2277   ;; Added a kludge for ";;"
2278   ;; Possible return values:
2279   ;;  nil  -  nothing
2280   ;; a string - possibly a keyword
2281   ;;
2282   (if (bolp)
2283       nil
2284     (let ((going t)
2285           c n
2286           min-point
2287           (start (point))
2288           (found nil))
2289       (save-restriction
2290         (narrow-to-region
2291         (if (sh-this-is-a-continuation)
2292             (setq min-point (sh-prev-line nil))
2293           (save-excursion
2294             (beginning-of-line)
2295             (setq min-point (point))))
2296         (point))
2297         (skip-chars-backward " \t;")
2298         (unless (looking-at "\\s-*;;")
2299         (skip-chars-backward "^)}];\"'`({[")
2300         (setq c (char-before))))
2301       (sh-debug "stopping at %d c is %s  start=%d min-point=%d"
2302                 (point) c start min-point)
2303       (if (< (point) min-point)
2304           (error "point %d < min-point %d" (point) min-point))
2305       (cond
2306        ((looking-at "\\s-*;;")
2307         ;; (message "Found ;; !")
2308        ";;")
2309        ((or (eq c ?\n)
2310             (eq c nil)
2311             (eq c ?\;))
2312        (save-excursion
2313          ;; skip forward over white space newline and \ at eol
2314          (skip-chars-forward " \t\n\\\\")
2315          (sh-debug "Now at %d   start=%d" (point) start)
2316          (if (>= (point) start)
2317              (progn
2318                (sh-debug "point: %d >= start: %d" (point) start)
2319                nil)
2320            (sh-get-word))
2321          ))
2322        (t
2323         ;; c    -- return a string
2324        (char-to-string c)
2325        ))
2326       )))
2327
2328
2329 (defun sh-this-is-a-continuation ()
2330   "Return non-nil if current line is a continuation of previous line."
2331   (save-excursion
2332     (and (zerop (forward-line -1))
2333          (looking-at ".*\\\\$")
2334          (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2335                                          nil nil nil t))))))
2336
2337 (defun sh-get-kw (&optional where and-move)
2338   "Return first word of line from WHERE.
2339 If AND-MOVE is non-nil then move to end of word."
2340   (let ((start (point)))
2341     (if where
2342         (goto-char where))
2343     (prog1
2344         (buffer-substring (point)
2345                           (progn (skip-chars-forward "^ \t\n;")(point)))
2346       (unless and-move
2347         (goto-char start)))))
2348
2349 (defun sh-find-prev-matching (open close &optional depth)
2350   "Find a matching token for a set of opening and closing keywords.
2351 This takes into account that there may be nested open..close pairings.
2352 OPEN and CLOSE are regexps denoting the tokens to be matched.
2353 Optional parameter DEPTH (usually 1) says how many to look for."
2354   (let ((parse-sexp-ignore-comments t)
2355         prev)
2356     (setq depth (or depth 1))
2357     (save-excursion
2358       (condition-case nil
2359           (while (and
2360                   (/= 0  depth)
2361                   (not (bobp))
2362                   (setq prev (sh-prev-stmt)))
2363             (goto-char prev)
2364             (save-excursion
2365               (if (looking-at "\\\\\n")
2366                   (progn
2367                     (forward-char 2)
2368                     (skip-chars-forward " \t")))
2369               (cond
2370                ((looking-at open)
2371                 (setq depth (1- depth))
2372                 (sh-debug "found open at %d - depth = %d" (point) depth))
2373                ((looking-at close)
2374                 (setq depth (1+ depth))
2375                 (sh-debug "found close - depth = %d" depth))
2376                (t
2377                 ))))
2378         (error nil))
2379       (if (eq depth 0)
2380           prev ;; (point)
2381         nil)
2382       )))
2383
2384
2385 (defun sh-var-value (var &optional ignore-error)
2386   "Return the value of variable VAR, interpreting symbols.
2387 It can also return t or nil.
2388 If an illegal value is found, throw an error unless Optional argument
2389 IGNORE-ERROR is non-nil."
2390   (let ((val (symbol-value var)))
2391     (cond
2392      ((numberp val)
2393       val)
2394      ((eq val t)
2395       val)
2396      ((null val)
2397       val)
2398      ((eq val '+)
2399       sh-basic-offset)
2400      ((eq val '-)
2401       (- sh-basic-offset))
2402      ((eq val '++)
2403       (* 2 sh-basic-offset))
2404      ((eq val '--)
2405       (* 2 (- sh-basic-offset)))
2406      ((eq val '*)
2407       (/ sh-basic-offset 2))
2408      ((eq val '/)
2409       (/ (- sh-basic-offset) 2))
2410      (t
2411       (if ignore-error
2412       (progn
2413         (message "Don't know how to handle %s's value of %s" var val)
2414         0)
2415       (error "Don't know how to handle %s's value of %s" var val))
2416       ))))
2417
2418 (defun sh-set-var-value (var value &optional no-symbol)
2419   "Set variable VAR to VALUE.
2420 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2421 can be represented by a symbol then do so."
2422   (cond
2423    (no-symbol
2424     (set var value))
2425    ((= value sh-basic-offset)
2426     (set var '+))
2427    ((= value (- sh-basic-offset))
2428     (set var '-))
2429    ((eq value (* 2 sh-basic-offset))
2430     (set var  '++))
2431    ((eq value (* 2 (- sh-basic-offset)))
2432     (set var  '--))
2433    ((eq value (/ sh-basic-offset 2))
2434     (set var  '*))
2435    ((eq value (/ (- sh-basic-offset) 2))
2436     (set var  '/))
2437    (t
2438     (set var value)))
2439   )
2440
2441
2442 (defun sh-calculate-indent (&optional info)
2443   "Return the indentation for the current line.
2444 If INFO is supplied it is used, else it is calculated from current line."
2445   (let ((ofs 0)
2446         (base-value 0)
2447         elt a b var val)
2448     (or info
2449         (setq info (sh-get-indent-info)))
2450     (when info
2451       (while info
2452         (sh-debug "info: %s  ofs=%s" info ofs)
2453         (setq elt (car info))
2454         (cond
2455          ((stringp elt)) ;; do nothing?
2456          ((listp elt)
2457           (setq a (car (car info)))
2458           (setq b (nth 1 (car info)))
2459           (cond
2460            ((eq a t)
2461             (save-excursion
2462               (goto-char b)
2463               (setq val (current-indentation)))
2464             (setq base-value val))
2465            ((symbolp b)
2466             (setq val (sh-var-value b))
2467             (cond
2468              ((eq a '=)
2469               (cond
2470                ((null val)
2471                 ;; no indentation
2472                 ;; set info to nil so  we stop immediately
2473                 (setq base-value nil  ofs nil  info nil))
2474                ((eq val t) (setq ofs 0)) ;; indent as normal line
2475                (t
2476                 ;; The following assume the (t POS) come first!
2477                 (setq ofs val  base-value 0)
2478                 (setq info nil))))      ;; ? stop now
2479              ((eq a '+) (setq ofs (+ ofs val)))
2480              ((eq a '-) (setq ofs (- ofs val)))
2481              (t
2482               (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2483            (t
2484             (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2485          (t
2486           (error "sh-calculate-indent invalid elt %s" elt)))
2487         (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2488                   a b val base-value ofs)
2489         (setq info (cdr info)))
2490       ;; return value:
2491       (sh-debug "at end:  base-value: %s    ofs: %s" base-value ofs)
2492
2493       (cond
2494        ((or (null base-value)(null ofs))
2495         nil)
2496        ((and (numberp base-value)(numberp ofs))
2497         (sh-debug "base (%d) + ofs (%d) = %d"
2498                   base-value ofs (+ base-value ofs))
2499         (+ base-value ofs)) ;; return value
2500        (t
2501         (error "sh-calculate-indent:  Help.  base-value=%s ofs=%s"
2502                base-value ofs)
2503         nil)))))
2504
2505
2506 (defun sh-indent-line (&optional prefix-arg)
2507   "Indent the current line."
2508   (interactive)
2509   (sh-must-be-shell-mode)
2510   (let ((indent (sh-calculate-indent)) shift-amt beg end
2511         (pos (- (point-max) (point))))
2512     (when indent
2513       (beginning-of-line)
2514       (setq beg (point))
2515       (skip-chars-forward " \t")
2516       (setq shift-amt (- indent (current-column)))
2517       (unless (zerop shift-amt)
2518         (delete-region beg (point))
2519         (indent-to indent))
2520       ;; If initial point was within line's indentation,
2521       ;; position after the indentation.  Else stay at same point in text.
2522       (if (> (- (point-max) pos) (point))
2523           (goto-char (- (point-max) pos))))))
2524
2525
2526 (defun sh-blink (blinkpos &optional msg)
2527   "Move cursor momentarily to BLINKPOS and display MSG."
2528   ;; We can get here without it being a number on first line
2529   (if (numberp blinkpos)
2530       (save-excursion
2531         (goto-char blinkpos)
2532         (message msg)
2533         (sit-for blink-matching-delay))
2534     (message msg)))
2535
2536 (defun sh-show-indent (arg)
2537   "Show the how the currently line would be indented.
2538 This tells you which variable, if any, controls the indentation of
2539 this line.
2540 If optional arg ARG is non-null (called interactively with a prefix),
2541 a pop up window describes this variable.
2542 If variable `sh-blink' is non-nil then momentarily go to the line
2543 we are indenting relative to, if applicable."
2544   (interactive "P")
2545   (sh-must-support-indent)
2546   (let* ((info (sh-get-indent-info))
2547          (var (sh-get-indent-var-for-line info))
2548          (curr-indent (current-indentation))
2549          val msg)
2550     (if (stringp var)
2551         (message (setq msg var))
2552       (setq val (sh-calculate-indent info))
2553
2554       (if (eq curr-indent val)
2555           (setq msg (format "%s is %s" var (symbol-value var)))
2556         (setq msg
2557               (if val
2558                   (format "%s (%s) would change indent from %d to: %d"
2559                           var (symbol-value var) curr-indent val)
2560                 (format "%s (%s) would leave line as is"
2561                         var (symbol-value var)))
2562               ))
2563       (if (and arg var)
2564           (describe-variable var)))
2565     (if sh-blink
2566         (let ((info (sh-get-indent-info)))
2567           (if (and info (listp (car info))
2568                    (eq (car (car info)) t))
2569               (sh-blink (nth 1 (car info))  msg)
2570             (message msg)))
2571       (message msg))
2572     ))
2573
2574 (defun sh-set-indent ()
2575   "Set the indentation for the current line.
2576 If the current line is controlled by an indentation variable, prompt
2577 for a new value for it."
2578   (interactive)
2579   (sh-must-support-indent)
2580   (let* ((info (sh-get-indent-info))
2581          (var (sh-get-indent-var-for-line info))
2582          val val0 new-val old-val indent-val)
2583     (if (stringp var)
2584         (message (format "Cannot set indent - %s" var))
2585       (setq old-val (symbol-value var))
2586       (setq val (sh-read-variable var))
2587       (condition-case nil
2588           (progn
2589             (set var val)
2590             (setq indent-val (sh-calculate-indent info))
2591             (if indent-val
2592                 (message "Variable: %s  Value: %s  would indent to: %d"
2593                          var (symbol-value var) indent-val)
2594               (message "Variable: %s  Value: %s  would leave line as is."
2595                        var (symbol-value var)))
2596             ;; I'm not sure about this, indenting it now?
2597             ;; No.  Because it would give the impression that an undo would
2598             ;; restore thing, but the value has been altered.
2599             ;; (sh-indent-line)
2600             )
2601         (error
2602          (set var old-val)
2603          (message "Bad value for %s, restoring to previous value %s"
2604                   var old-val)
2605          (sit-for 1)
2606          nil))
2607       )))
2608
2609
2610 (defun sh-learn-line-indent (arg)
2611   "Learn how to indent a line as it currently is indented.
2612
2613 If there is an indentation variable which controls this line's indentation,
2614 then set it to a value which would indent the line the way it
2615 presently is.
2616
2617 If the value can be represented by one of the symbols then do so
2618 unless optional argument ARG (the prefix when interactive) is non-nil."
2619   (interactive "*P")
2620   (sh-must-support-indent)
2621   ;; I'm not sure if we show allow learning on an empty line.
2622   ;; Though it might occasionally be useful I think it usually
2623   ;; would just be confusing.
2624   (if (save-excursion
2625         (beginning-of-line)
2626         (looking-at "\\s-*$"))
2627       (message "sh-learn-line-indent ignores empty lines.")
2628     (let* ((info (sh-get-indent-info))
2629            (var (sh-get-indent-var-for-line info))
2630            ival sval diff new-val
2631            (no-symbol arg)
2632            (curr-indent (current-indentation)))
2633       (cond
2634        ((stringp var)
2635         (message (format "Cannot learn line - %s" var)))
2636        ((eq var 'sh-indent-comment)
2637         ;; This is arbitrary...
2638         ;; - if curr-indent is 0, set to curr-indent
2639         ;; - else if it has the indentation of a "normal" line,
2640         ;;   then set to t
2641         ;; - else set to curr-indent.
2642         (setq sh-indent-comment
2643               (if (= curr-indent 0)
2644                   0
2645                 (let* ((sh-indent-comment t)
2646                        (val2 (sh-calculate-indent info)))
2647                   (if (= val2 curr-indent)
2648                       t
2649                     curr-indent))))
2650         (message "%s set to %s" var (symbol-value var))
2651         )
2652        ((numberp (setq sval (sh-var-value var)))
2653         (setq ival (sh-calculate-indent info))
2654         (setq diff (- curr-indent ival))
2655
2656         (sh-debug "curr-indent: %d   ival: %d  diff: %d  var:%s  sval %s"
2657                   curr-indent ival diff  var sval)
2658         (setq new-val (+ sval diff))
2659 ;;;       I commented out this because someone might want to replace
2660 ;;;       a value of `+' with the current value of sh-basic-offset
2661 ;;;       or vice-versa.
2662 ;;;       (if (= 0 diff)
2663 ;;;           (message "No change needed!")
2664         (sh-set-var-value var new-val no-symbol)
2665         (message "%s set to %s" var (symbol-value var))
2666         )
2667        (t
2668         (debug)
2669         (message "Cannot change %s" var))))))
2670
2671
2672
2673 (defun sh-mark-init (buffer)
2674   "Initialize a BUFFER to be used by `sh-mark-line'."
2675   (let ((main-buffer (current-buffer)))
2676     (save-excursion
2677       (set-buffer (get-buffer-create buffer))
2678       (erase-buffer)
2679       (occur-mode)
2680       (setq occur-buffer main-buffer)
2681       )))
2682
2683
2684 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2685   "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2686 Buffer BUFFER is in `occur-mode'.
2687 If ADD-LINENUM is non-nil the message is preceded by the line number.
2688 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2689 so that `occur-next' and `occur-prev' will work."
2690   (let ((m1 (make-marker))
2691         (main-buffer (current-buffer))
2692         start
2693         (line ""))
2694     (when point
2695       (set-marker m1 point (current-buffer))
2696       (if add-linenum
2697           (setq line (format "%d: " (1+ (count-lines 1 point))))))
2698     (save-excursion
2699       (if (get-buffer buffer)
2700           (set-buffer (get-buffer buffer))
2701         (set-buffer (get-buffer-create buffer))
2702         (occur-mode)
2703         (setq occur-buffer main-buffer)
2704         )
2705       (goto-char (point-max))
2706       (setq start (point))
2707       (insert line)
2708       (if occur-point
2709           (setq occur-point (point)))
2710       (insert message)
2711       (if point
2712           (add-text-properties
2713            start (point)
2714            '(mouse-face highlight
2715              help-echo "mouse-2: go to the line where I learned this")))
2716       (insert "\n")
2717       (if point
2718           (progn
2719             (put-text-property start (point) 'occur m1)
2720             (if occur-point
2721                 (put-text-property occur-point (1+ occur-point)
2722                                    'occur-point t))
2723             ))
2724       )))
2725
2726
2727
2728 ;; Is this really worth having?
2729 (defvar sh-learned-buffer-hook nil
2730   "*An abnormal hook, called with an alist of learned variables.")
2731 ;;; Example of how to use sh-learned-buffer-hook
2732 ;;
2733 ;; (defun what-i-learned (list)
2734 ;;   (let ((p list))
2735 ;;     (save-excursion
2736 ;;       (set-buffer "*scratch*")
2737 ;;       (goto-char (point-max))
2738 ;;       (insert "(setq\n")
2739 ;;       (while p
2740 ;;      (insert (format "  %s %s \n"
2741 ;;                      (nth 0 (car p)) (nth 1 (car p))))
2742 ;;      (setq p (cdr p)))
2743 ;;       (insert ")\n")
2744 ;;       )))
2745 ;;
2746 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2747
2748
2749 ;; Originally this was sh-learn-region-indent (beg end)
2750 ;; However, in practice this was awkward so I changed it to
2751 ;; use the whole buffer.  Use narrowing if needbe.
2752 (defun sh-learn-buffer-indent (&optional arg)
2753   "Learn how to indent the buffer the way it currently is.
2754
2755 Output in buffer \"*indent*\" shows any lines which have conflicting
2756 values of a variable, and the final value of all variables learned.
2757 This buffer is popped to automatically if there are any discrepancies.
2758
2759 If no prefix ARG is given, then variables are set to numbers.
2760 If a prefix arg is given, then variables are set to symbols when
2761 applicable -- e.g. to symbol `+' if the value is that of the
2762 basic indent.
2763 If a positive numerical prefix is given, then  `sh-basic-offset'
2764 is set to the prefix's numerical value.
2765 Otherwise, sh-basic-offset may or may not be changed, according
2766 to the value of variable `sh-learn-basic-offset'.
2767
2768 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2769 function completes.  The function is abnormal because it is called
2770 with an alist of variables learned.  This feature may be changed or
2771 removed in the future.
2772
2773 This command can often take a long time to run."
2774   (interactive "P")
2775   (sh-must-support-indent)
2776   (save-excursion
2777     (goto-char (point-min))
2778     (let ((learned-var-list nil)
2779           (out-buffer "*indent*")
2780           (num-diffs 0)
2781           last-pos
2782           previous-set-info
2783           (max 17)
2784           vec
2785           msg
2786           (comment-col nil) ;; number if all same, t if seen diff values
2787           (comments-always-default t) ;; nil if we see one not default
2788           initial-msg
2789           (specified-basic-offset (and arg (numberp arg)
2790                                        (> arg 0)))
2791           (linenum 0)
2792           suggested)
2793       (setq vec (make-vector max 0))
2794       (sh-mark-init out-buffer)
2795
2796       (if specified-basic-offset
2797           (progn
2798             (setq sh-basic-offset arg)
2799             (setq initial-msg
2800                   (format "Using specified sh-basic-offset of %d"
2801                           sh-basic-offset)))
2802         (setq initial-msg
2803               (format "Initial value of sh-basic-offset: %s"
2804                       sh-basic-offset)))
2805
2806       (while (< (point) (point-max))
2807         (setq linenum (1+ linenum))
2808         ;; (if (zerop (% linenum 10))
2809         (message "line %d" linenum)
2810         ;; )
2811         (unless (looking-at "\\s-*$") ;; ignore empty lines!
2812           (let* ((sh-indent-comment t) ;; info must return default indent
2813                  (info (sh-get-indent-info))
2814                  (var (sh-get-indent-var-for-line info))
2815                  sval ival diff new-val
2816                  (curr-indent (current-indentation)))
2817             (cond
2818              ((null var)
2819               nil)
2820              ((stringp var)
2821               nil)
2822              ((numberp (setq sval (sh-var-value var 'no-error)))
2823               ;; the numberp excludes comments since sval will be t.
2824               (setq ival (sh-calculate-indent))
2825               (setq diff (- curr-indent ival))
2826               (setq new-val (+ sval diff))
2827               (sh-set-var-value var new-val 'no-symbol)
2828               (unless (looking-at "\\s-*#") ;; don't learn from comments
2829                 (if (setq previous-set-info (assoc var learned-var-list))
2830                     (progn
2831                       ;; it was already there, is it same value ?
2832                       (unless (eq (symbol-value var)
2833                                   (nth 1 previous-set-info))
2834                         (sh-mark-line
2835                          (format "Variable %s was set to %s"
2836                                  var (symbol-value var))
2837                          (point) out-buffer t t)
2838                         (sh-mark-line
2839                          (format "  but was previously set to %s"
2840                                  (nth 1 previous-set-info))
2841                          (nth 2 previous-set-info) out-buffer t)
2842                         (setq num-diffs (1+ num-diffs))
2843                         ;; (delete previous-set-info  learned-var-list)
2844                         (setcdr previous-set-info
2845                                 (list (symbol-value var) (point)))
2846                         )
2847                       )
2848                   (setq learned-var-list
2849                         (append (list (list var (symbol-value var)
2850                                             (point)))
2851                                 learned-var-list)))
2852                 (if (numberp new-val)
2853                     (progn
2854                       (sh-debug
2855                        "This line's indent value: %d"  new-val)
2856                       (if (< new-val 0)
2857                           (setq new-val (- new-val)))
2858                       (if (< new-val max)
2859                           (aset vec new-val (1+ (aref vec new-val))))))
2860                 ))
2861              ((eq var 'sh-indent-comment)
2862               (unless (= curr-indent (sh-calculate-indent info))
2863                 ;; this is not the default indentation
2864                 (setq comments-always-default nil)
2865                 (if comment-col ;; then we have see one before
2866                     (or (eq comment-col curr-indent)
2867                         (setq comment-col t)) ;; seen a different one
2868                   (setq comment-col curr-indent))
2869                 ))
2870              (t
2871               (sh-debug "Cannot learn this line!!!")
2872               ))
2873             (sh-debug
2874              "at %s learned-var-list is %s" (point) learned-var-list)
2875             ))
2876         (forward-line 1)
2877         ) ;; while
2878       (if sh-debug
2879           (progn
2880             (setq msg (format
2881                        "comment-col = %s  comments-always-default = %s"
2882                        comment-col comments-always-default))
2883             ;; (message msg)
2884             (sh-mark-line  msg nil out-buffer)))
2885       (cond
2886        ((eq comment-col 0)
2887         (setq msg  "\nComments are all in 1st column.\n"))
2888        (comments-always-default
2889         (setq msg  "\nComments follow default indentation.\n")
2890         (setq comment-col t))
2891        ((numberp comment-col)
2892         (setq msg  (format "\nComments are in col %d." comment-col)))
2893        (t
2894         (setq msg  "\nComments seem to be mixed, leaving them as is.\n")
2895         (setq comment-col nil)
2896         ))
2897       (sh-debug msg)
2898       (sh-mark-line  msg nil out-buffer)
2899
2900       (sh-mark-line initial-msg nil out-buffer t t)
2901
2902       (setq suggested (sh-guess-basic-offset vec))
2903
2904       (if (and suggested (not specified-basic-offset))
2905           (let ((new-value
2906                  (cond
2907                   ;; t => set it if we have a single value as a number
2908                   ((and (eq sh-learn-basic-offset t) (numberp suggested))
2909                    suggested)
2910                   ;; other non-nil => set it if only one value was found
2911                   (sh-learn-basic-offset
2912                    (if (numberp suggested)
2913                        suggested
2914                      (if (= (length suggested) 1)
2915                          (car suggested))))
2916                   (t
2917                    nil))))
2918             (if new-value
2919                 (progn
2920                   (setq learned-var-list
2921                         (append (list (list 'sh-basic-offset
2922                                             (setq sh-basic-offset new-value)
2923                                             (point-max)))
2924                                 learned-var-list))
2925                   ;; Not sure if we need to put this line in, since
2926                   ;; it will appear in the "Learned variable settings".
2927                   (sh-mark-line
2928                    (format "Changed sh-basic-offset to: %d" sh-basic-offset)
2929                    nil out-buffer))
2930               (sh-mark-line
2931                (if (listp suggested)
2932                    (format "Possible value(s) for sh-basic-offset:  %s"
2933                            (mapconcat 'int-to-string suggested " "))
2934                  (format "Suggested sh-basic-offset:  %d" suggested))
2935                nil out-buffer))))
2936
2937
2938       (setq learned-var-list
2939             (append (list (list 'sh-indent-comment comment-col (point-max)))
2940                     learned-var-list))
2941       (setq sh-indent-comment comment-col)
2942       (let ((name (buffer-name))
2943             (lines (if (and (eq (point-min) 1)
2944                             (eq (point-max) (1+ (buffer-size))))
2945                        ""
2946                      (format "lines %d to %d of "
2947                              (1+ (count-lines 1 (point-min)))
2948                              (1+ (count-lines 1 (point-max))))))
2949             )
2950         (sh-mark-line  "\nLearned variable settings:" nil out-buffer)
2951         (if arg
2952             ;; Set learned variables to symbolic rather than numeric
2953             ;; values where possible.
2954             (dolist (learned-var (reverse learned-var-list))
2955               (let ((var (car learned-var))
2956                     (val (nth 1 learned-var)))
2957                 (when (and (not (eq var 'sh-basic-offset))
2958                            (numberp val))
2959                   (sh-set-var-value var val)))))
2960         (dolist (learned-var (reverse learned-var-list))
2961           (let ((var (car learned-var)))
2962             (sh-mark-line (format "  %s %s" var (symbol-value var))
2963                           (nth 2 learned-var) out-buffer)))
2964         (save-excursion
2965           (set-buffer out-buffer)
2966           (goto-char (point-min))
2967           (insert
2968            (format "Indentation values for buffer %s.\n" name)
2969            (format "%d indentation variable%s different values%s\n\n"
2970                    num-diffs
2971                    (if (= num-diffs 1)
2972                        " has"   "s have")
2973                    (if (zerop num-diffs)
2974                        "." ":"))
2975            )))
2976       ;; Are abnormal hooks considered bad form?
2977       (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
2978       (if (or sh-popup-occur-buffer (> num-diffs 0))
2979           (pop-to-buffer out-buffer))
2980       )))
2981
2982 (defun sh-guess-basic-offset (vec)
2983   "See if we can determine a reasonable value for `sh-basic-offset'.
2984 This is experimental, heuristic and arbitrary!
2985 Argument VEC is a vector of information collected by
2986 `sh-learn-buffer-indent'.
2987 Return values:
2988   number          - there appears to be a good single value
2989   list of numbers - no obvious one, here is a list of one or more
2990                     reasonable choices
2991   nil             - we couldn't find a reasonable one."
2992   (let* ((max (1- (length vec)))
2993          (i 1)
2994          (totals (make-vector max 0))
2995          (return nil)
2996          j)
2997     (while (< i max)
2998       (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
2999       (setq j (/ i 2))
3000       (if (zerop (% i 2))
3001           (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3002       (if (< (* i 2) max)
3003           (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3004       (setq i (1+ i)))
3005
3006     (let ((x nil)
3007           (result nil)
3008           tot sum p)
3009       (setq i 1)
3010       (while (< i max)
3011         (if (/= (aref totals i) 0)
3012             (setq x (append x (list (cons i (aref totals i))))))
3013         (setq i (1+ i)))
3014
3015       (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3016       (setq tot (apply '+ (append totals nil)))
3017       (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3018                         vec totals tot))
3019       (cond
3020        ((zerop (length x))
3021         (message "no values!")) ;; we return nil
3022        ((= (length x) 1)
3023         (message "only value is %d" (car (car x)))
3024         (setq result (car (car x)))) ;; return single value
3025        ((> (cdr (car x)) (/ tot 2))
3026         ;; 1st is > 50%
3027         (message "basic-offset is probably %d" (car (car x)))
3028         (setq result (car (car x)))) ;;   again, return a single value
3029        ((>=  (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3030         ;; 1st is >= 2 * 2nd
3031         (message "basic-offset could be %d" (car (car x)))
3032         (setq result (car (car x))))
3033        ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3034         ;; 1st & 2nd together >= 50%  - return a list
3035         (setq p x  sum 0 result nil)
3036         (while  (and p
3037                      (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3038           (setq result (append result (list (car (car p)))))
3039           (setq p (cdr p)))
3040         (message "Possible choices for sh-basic-offset: %s"
3041                  (mapconcat 'int-to-string result " ")))
3042        (t
3043         (message "No obvious value for sh-basic-offset.  Perhaps %d"
3044                  (car (car x)))
3045         ;; result is nil here
3046         ))
3047       result)))
3048
3049 ;; ========================================================================
3050
3051 ;; Styles -- a quick and dirty way of saving the indentation settings.
3052
3053 (defvar sh-styles-alist nil
3054   "A list of all known shell indentation styles.")
3055
3056 (defun sh-name-style (name &optional confirm-overwrite)
3057   "Name the current indentation settings as a style called NAME.
3058 If this name exists, the command will prompt whether it should be
3059 overwritten if
3060 - - it was called interactively with a prefix argument, or
3061 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3062   ;; (interactive "sName for this style: ")
3063   (interactive
3064    (list
3065     (read-from-minibuffer "Name for this style? " )
3066     (not current-prefix-arg)))
3067   (let ((slist (cons name
3068                      (mapcar (lambda (var) (cons var (symbol-value var)))
3069                              sh-var-list)))
3070         (style (assoc name sh-styles-alist)))
3071     (if style
3072         (if (and confirm-overwrite
3073                  (not (y-or-n-p "This style exists.  Overwrite it? ")))
3074             (message "Not changing style %s" name)
3075           (message "Updating style %s" name)
3076           (setcdr style (cdr slist)))
3077       (message "Creating new style %s" name)
3078       (push slist sh-styles-alist))))
3079
3080 (defun sh-load-style (name)
3081   "Set shell indentation values for this buffer from those in style NAME."
3082   (interactive (list (completing-read
3083                       "Which style to use for this buffer? "
3084                       sh-styles-alist nil t)))
3085   (let ((sl (assoc name  sh-styles-alist)))
3086     (if (null sl)
3087         (error "sh-load-style - style %s not known" name)
3088       (dolist (var (cdr sl))
3089         (set (car var) (cdr var))))))
3090
3091 (defun sh-save-styles-to-buffer (buff)
3092   "Save all current styles in elisp to buffer BUFF.
3093 This is always added to the end of the buffer."
3094   (interactive (list
3095                 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3096   (with-current-buffer (get-buffer-create buff)
3097     (goto-char (point-max))
3098     (insert "\n")
3099     (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3100
3101
3102 \f
3103 ;; statement syntax-commands for various shells
3104
3105 ;; You are welcome to add the syntax or even completely new statements as
3106 ;; appropriate for your favorite shell.
3107
3108 (define-skeleton sh-case
3109   "Insert a case/switch statement.  See `sh-feature'."
3110   (csh "expression: "
3111        "switch( " str " )" \n
3112        > "case " (read-string "pattern: ") ?: \n
3113        > _ \n
3114        "breaksw" \n
3115        ( "other pattern, %s: "
3116          < "case " str ?: \n
3117          > _ \n
3118          "breaksw" \n)
3119        < "default:" \n
3120        > _ \n
3121        resume:
3122        < < "endsw")
3123   (es)
3124   (rc "expression: "
3125       > "switch( " str " ) {" \n
3126       > "case " (read-string "pattern: ") \n
3127       > _ \n
3128       ( "other pattern, %s: "
3129         "case " str > \n
3130         > _ \n)
3131       "case *" > \n
3132       > _ \n
3133       resume:
3134       ?} > )
3135   (sh "expression: "
3136       > "case " str " in" \n
3137       > (read-string "pattern: ")
3138       (propertize ")" 'syntax-table sh-st-punc)
3139       \n
3140       > _ \n
3141       ";;" \n
3142       ( "other pattern, %s: "
3143         > str (propertize ")" 'syntax-table sh-st-punc) \n
3144         > _ \n
3145         ";;" \n)
3146       > "*" (propertize ")" 'syntax-table sh-st-punc) \n
3147       > _ \n
3148       resume:
3149       "esac" > ))
3150
3151 (define-skeleton sh-for
3152   "Insert a for loop.  See `sh-feature'."
3153   (csh eval sh-modify sh
3154        1 ""
3155        2 "foreach "
3156        4 " ( "
3157        6 " )"
3158        15 '<
3159        16 "end")
3160   (es eval sh-modify rc
3161       4 " = ")
3162   (rc eval sh-modify sh
3163       2 "for( "
3164       6 " ) {"
3165       15 ?} )
3166   (sh "Index variable: "
3167       > "for " str " in " _ "; do" \n
3168       > _ | ?$ & (sh-remember-variable str) \n
3169       "done" > ))
3170
3171
3172
3173 (define-skeleton sh-indexed-loop
3174   "Insert an indexed loop from 1 to n.  See `sh-feature'."
3175   (bash eval identity posix)
3176   (csh "Index variable: "
3177        "@ " str " = 1" \n
3178        "while( $" str " <= " (read-string "upper limit: ") " )" \n
3179        > _ ?$ str \n
3180        "@ " str "++" \n
3181        < "end")
3182   (es eval sh-modify rc
3183       4 " =")
3184   (ksh88 "Index variable: "
3185          > "integer " str "=0" \n
3186          > "while (( ( " str " += 1 ) <= "
3187          (read-string "upper limit: ")
3188          " )); do" \n
3189          > _ ?$ (sh-remember-variable str) > \n
3190          "done" > )
3191   (posix "Index variable: "
3192          > str "=1" \n
3193          "while [ $" str " -le "
3194          (read-string "upper limit: ")
3195          " ]; do" \n
3196          > _ ?$ str \n
3197          str ?= (sh-add (sh-remember-variable str) 1) \n
3198          "done" > )
3199   (rc "Index variable: "
3200       > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3201       (read-string "upper limit: ")
3202       "; i++ ) print i }'`}) {" \n
3203       > _ ?$ (sh-remember-variable str) \n
3204       ?} >)
3205   (sh "Index variable: "
3206       > "for " str " in `awk 'BEGIN { for( i=1; i<="
3207       (read-string "upper limit: ")
3208       "; i++ ) print i }'`; do" \n
3209       > _ ?$ (sh-remember-variable str) \n
3210       "done" > ))
3211
3212
3213 (defun sh-shell-initialize-variables ()
3214   "Scan the buffer for variable assignments.
3215 Add these variables to `sh-shell-variables'."
3216   (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3217   (save-excursion
3218     (goto-char (point-min))
3219     (setq sh-shell-variables-initialized t)
3220     (while (search-forward "=" nil t)
3221       (sh-assignment 0)))
3222   (message "Scanning buffer `%s' for variable assignments...done"
3223            (buffer-name)))
3224
3225 (defvar sh-add-buffer)
3226
3227 (defun sh-add-completer (string predicate code)
3228   "Do completion using `sh-shell-variables', but initialize it first.
3229 This function is designed for use as the \"completion table\",
3230 so it takes three arguments:
3231   STRING, the current buffer contents;
3232   PREDICATE, the predicate for filtering possible matches;
3233   CODE, which says what kind of things to do.
3234 CODE can be nil, t or `lambda'.
3235 nil means to return the best completion of STRING, or nil if there is none.
3236 t means to return a list of all possible completions of STRING.
3237 `lambda' means to return t if STRING is a valid completion as it stands."
3238   (let ((sh-shell-variables
3239          (save-excursion
3240            (set-buffer sh-add-buffer)
3241            (or sh-shell-variables-initialized
3242                (sh-shell-initialize-variables))
3243            (nconc (mapcar (lambda (var)
3244                             (let ((name
3245                                    (substring var 0 (string-match "=" var))))
3246                               (cons name name)))
3247                           process-environment)
3248                   sh-shell-variables))))
3249     (cond ((null code)
3250            (try-completion string sh-shell-variables predicate))
3251           ((eq code t)
3252            (all-completions string sh-shell-variables predicate))
3253           ((eq code 'lambda)
3254            (assoc string sh-shell-variables)))))
3255
3256 (defun sh-add (var delta)
3257   "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3258   (interactive
3259    (let ((sh-add-buffer (current-buffer)))
3260      (list (completing-read "Variable: " 'sh-add-completer)
3261            (prefix-numeric-value current-prefix-arg))))
3262   (insert (sh-feature '((bash . "$[ ")
3263                         (ksh88 . "$(( ")
3264                         (posix . "$(( ")
3265                         (rc . "`{expr $")
3266                         (sh . "`expr $")
3267                         (zsh . "$[ ")))
3268           (sh-remember-variable var)
3269           (if (< delta 0) " - " " + ")
3270           (number-to-string (abs delta))
3271           (sh-feature '((bash . " ]")
3272                         (ksh88 . " ))")
3273                         (posix . " ))")
3274                         (rc . "}")
3275                         (sh . "`")
3276                         (zsh . " ]")))))
3277
3278
3279
3280 (define-skeleton sh-function
3281   "Insert a function definition.  See `sh-feature'."
3282   (bash eval sh-modify ksh88
3283         3 "() {")
3284   (ksh88 "name: "
3285          "function " str " {" \n
3286          > _ \n
3287          < "}")
3288   (rc eval sh-modify ksh88
3289       1 "fn ")
3290   (sh ()
3291       "() {" \n
3292       > _ \n
3293       < "}"))
3294
3295
3296
3297 (define-skeleton sh-if
3298   "Insert an if statement.  See `sh-feature'."
3299   (csh "condition: "
3300        "if( " str " ) then" \n
3301        > _ \n
3302        ( "other condition, %s: "
3303          < "else if( " str " ) then" \n
3304          > _ \n)
3305        < "else" \n
3306        > _ \n
3307        resume:
3308        < "endif")
3309   (es "condition: "
3310       > "if { " str " } {" \n
3311       > _ \n
3312       ( "other condition, %s: "
3313         "} { " str " } {" > \n
3314         > _ \n)
3315       "} {" > \n
3316       > _ \n
3317       resume:
3318       ?} > )
3319   (rc "condition: "
3320       > "if( " str " ) {" \n
3321       > _ \n
3322       ( "other condition, %s: "
3323         "} else if( " str " ) {"  > \n
3324         > _ \n)
3325       "} else {" > \n
3326       > _ \n
3327       resume:
3328       ?} >
3329       )
3330   (sh "condition: "
3331       '(setq input (sh-feature sh-test))
3332       > "if " str "; then" \n
3333       > _ \n
3334       ( "other condition, %s: "
3335         >  "elif " str "; then" > \n
3336         > \n)
3337       "else" > \n
3338       > \n
3339       resume:
3340       "fi" > ))
3341
3342
3343
3344 (define-skeleton sh-repeat
3345   "Insert a repeat loop definition.  See `sh-feature'."
3346   (es nil
3347       > "forever {" \n
3348       > _ \n
3349       ?} > )
3350   (zsh "factor: "
3351        > "repeat " str "; do" > \n
3352        >  \n
3353        "done" > ))
3354
3355 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3356
3357
3358
3359 (define-skeleton sh-select
3360   "Insert a select statement.  See `sh-feature'."
3361   (ksh88 "Index variable: "
3362          > "select " str " in " _ "; do" \n
3363          > ?$ str \n
3364          "done" > )
3365   (bash eval sh-append ksh88))
3366 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3367
3368
3369
3370 (define-skeleton sh-tmp-file
3371   "Insert code to setup temporary file handling.  See `sh-feature'."
3372   (bash eval identity ksh88)
3373   (csh (file-name-nondirectory (buffer-file-name))
3374        "set tmp = /tmp/" str ".$$" \n
3375        "onintr exit" \n _
3376        (and (goto-char (point-max))
3377             (not (bolp))
3378             ?\n)
3379        "exit:\n"
3380        "rm $tmp* >&/dev/null" >)
3381   (es (file-name-nondirectory (buffer-file-name))
3382       > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3383       ".$pid ) {" \n
3384       > "catch @ e {" \n
3385       > "rm $tmp^* >[2]/dev/null" \n
3386       "throw $e" \n
3387       "} {" > \n
3388       _ \n
3389       ?} > \n
3390       ?} > )
3391   (ksh88 eval sh-modify sh
3392          7 "EXIT")
3393   (rc (file-name-nondirectory (buffer-file-name))
3394       > "tmp = /tmp/" str ".$pid" \n
3395       "fn sigexit { rm $tmp^* >[2]/dev/null }")
3396   (sh (file-name-nondirectory (buffer-file-name))
3397       > "TMP=${TMPDIR:-/tmp}/" str ".$$" \n
3398       "trap \"rm $TMP* 2>/dev/null\" " ?0))
3399
3400
3401
3402 (define-skeleton sh-until
3403   "Insert an until loop.  See `sh-feature'."
3404   (sh "condition: "
3405       '(setq input (sh-feature sh-test))
3406       > "until " str "; do" \n
3407       > _ \n
3408       "done" > ))
3409 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3410
3411
3412
3413 (define-skeleton sh-while
3414   "Insert a while loop.  See `sh-feature'."
3415   (csh eval sh-modify sh
3416        2 ""
3417        3 "while( "
3418        5 " )"
3419        10 '<
3420        11 "end")
3421   (es eval sh-modify sh
3422       3 "while { "
3423       5 " } {"
3424       10 ?} )
3425   (rc eval sh-modify sh
3426       3 "while( "
3427       5 " ) {"
3428       10 ?} )
3429   (sh "condition: "
3430       '(setq input (sh-feature sh-test))
3431       > "while " str "; do" \n
3432       > _ \n
3433       "done" > ))
3434
3435
3436
3437 (define-skeleton sh-while-getopts
3438   "Insert a while getopts loop.  See `sh-feature'.
3439 Prompts for an options string which consists of letters for each recognized
3440 option followed by a colon `:' if the option accepts an argument."
3441   (bash eval sh-modify sh
3442         18 "${0##*/}")
3443   (csh nil
3444        "while( 1 )" \n
3445        > "switch( \"$1\" )" \n
3446        '(setq input '("- x" . 2))
3447        > >
3448        ( "option, %s: "
3449          < "case " '(eval str)
3450          '(if (string-match " +" str)
3451               (setq v1 (substring str (match-end 0))
3452                     str (substring str 0 (match-beginning 0)))
3453             (setq v1 nil))
3454          str ?: \n
3455          > "set " v1 & " = $2" | -4 & _ \n
3456          (if v1 "shift") & \n
3457          "breaksw" \n)
3458        < "case --:" \n
3459        > "shift" \n
3460        < "default:" \n
3461        > "break" \n
3462        resume:
3463        < < "endsw" \n
3464        "shift" \n
3465        < "end")
3466   (ksh88 eval sh-modify sh
3467          16 "print"
3468          18 "${0##*/}"
3469          36 "OPTIND-1")
3470   (posix eval sh-modify sh
3471          18 "$(basename $0)")
3472   (sh "optstring: "
3473       > "while getopts :" str " OPT; do" \n
3474       > "case $OPT in" \n
3475       '(setq v1 (append (vconcat str) nil))
3476       ( (prog1 (if v1 (char-to-string (car v1)))
3477           (if (eq (nth 1 v1) ?:)
3478               (setq v1 (nthcdr 2 v1)
3479                     v2 "\"$OPTARG\"")
3480             (setq v1 (cdr v1)
3481                   v2 nil)))
3482         > str "|+" str (propertize ")" 'syntax-table sh-st-punc) \n
3483         > _ v2 \n
3484         > ";;" \n)
3485       > "*" (propertize ")" 'syntax-table sh-st-punc) \n
3486       > "echo" " \"usage: " "`basename $0`"
3487       " [+-" '(setq v1 (point)) str
3488       '(save-excursion
3489          (while (search-backward ":" v1 t)
3490            (replace-match " ARG] [+-" t t)))
3491       (if (eq (preceding-char) ?-) -5)
3492       (if (and (sequencep v1) (length v1)) "] " "} ")
3493       "[--] ARGS...\"" \n
3494       "exit 2"  > \n
3495       "esac" >
3496       \n "done"
3497       > \n
3498       "shift " (sh-add "OPTIND" -1)))
3499
3500
3501
3502 (defun sh-assignment (arg)
3503   "Remember preceding identifier for future completion and do self-insert."
3504   (interactive "p")
3505   (self-insert-command arg)
3506   (if (<= arg 1)
3507       (sh-remember-variable
3508        (save-excursion
3509          (if (re-search-forward (sh-feature sh-assignment-regexp)
3510                                 (prog1 (point)
3511                                   (beginning-of-line 1))
3512                                 t)
3513              (match-string 1))))))
3514
3515
3516
3517 (defun sh-maybe-here-document (arg)
3518   "Insert self.  Without prefix, following unquoted `<' inserts here document.
3519 The document is bounded by `sh-here-document-word'."
3520   (interactive "*P")
3521   (self-insert-command (prefix-numeric-value arg))
3522   (or arg
3523       (not (eq (char-after (- (point) 2)) last-command-char))
3524       (save-excursion
3525         (backward-char 2)
3526         (sh-quoted-p))
3527       (progn
3528         (insert sh-here-document-word)
3529         (or (eolp) (looking-at "[ \t]") (insert ? ))
3530         (end-of-line 1)
3531         (while
3532             (sh-quoted-p)
3533           (end-of-line 2))
3534         (newline)
3535         (save-excursion (insert ?\n sh-here-document-word)))))
3536
3537 \f
3538 ;; various other commands
3539
3540 (autoload 'comint-dynamic-complete "comint"
3541   "Dynamically perform completion at point." t)
3542
3543 (autoload 'shell-dynamic-complete-command "shell"
3544   "Dynamically complete the command at point." t)
3545
3546 (autoload 'comint-dynamic-complete-filename "comint"
3547   "Dynamically complete the filename at point." t)
3548
3549 (autoload 'shell-dynamic-complete-environment-variable "shell"
3550   "Dynamically complete the environment variable at point." t)
3551
3552
3553
3554 (defun sh-newline-and-indent ()
3555   "Strip unquoted whitespace, insert newline, and indent like current line."
3556   (interactive "*")
3557   (indent-to (prog1 (current-indentation)
3558                (delete-region (point)
3559                               (progn
3560                                 (or (zerop (skip-chars-backward " \t"))
3561                                     (if (sh-quoted-p)
3562                                         (forward-char)))
3563                                 (point)))
3564                (newline))))
3565
3566 (defun sh-beginning-of-command ()
3567   "Move point to successive beginnings of commands."
3568   (interactive)
3569   (if (re-search-backward sh-beginning-of-command nil t)
3570       (goto-char (match-beginning 2))))
3571
3572 (defun sh-end-of-command ()
3573   "Move point to successive ends of commands."
3574   (interactive)
3575   (if (re-search-forward sh-end-of-command nil t)
3576       (goto-char (match-end 1))))
3577
3578 ;; XEmacs change
3579 ;;;###autoload(add-to-list 'auto-mode-alist '("/\\.\\(?:bash_\\|z\\)?\\(profile\\|login\\|logout\\)\\'" . sh-mode))
3580 ;;;###autoload(add-to-list 'auto-mode-alist '("/\\.\\(?:[ckz]sh\\|bash\\|tcsh\\|es\\|xinit\\|startx\\)rc\\(?:\\.in\\)?\\'" . sh-mode))
3581 ;;;###autoload(add-to-list 'auto-mode-alist '("/\\.\\(?:[kz]shenv\\|xsession\\)\\'" . sh-mode))
3582 ;;;###autoload(setq auto-mode-alist (append auto-mode-alist '(("\\.m?spec$" . sh-mode))))
3583 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.\\(?:\\(?:ba\\|[ckz]\\)?sh\\|shar\\)\\(?:\\.in\\)?\\'" . sh-mode))
3584 ;;;###autoload(add-to-list 'interpreter-mode-alist '("^#!.*csh" . sh-mode))
3585 ;;;###autoload(add-to-list 'interpreter-mode-alist '("^#!.*sh\\b" . sh-mode))
3586 ;;;###autoload(add-to-list 'interpreter-mode-alist '("^:" . sh-mode))
3587
3588 (provide 'sh-script)
3589
3590 ;;; sh-script.el ends here