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