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