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