]> code.delx.au - gnu-emacs/blob - lisp/progmodes/sh-script.el
(sh-shell-arg): Don't add any options for bash, ksh.
[gnu-emacs] / lisp / progmodes / sh-script.el
1 ;;; sh-script.el --- shell-script editing commands for Emacs
2
3 ;; Copyright (C) 1993, 1994, 1995, 1996 by Free Software Foundation, Inc.
4
5 ;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
6 ;; Version: 2.0e
7 ;; Maintainer: FSF
8 ;; Keywords: languages, unix
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30 ;; as various derivatives are supported and easily derived from. Structured
31 ;; statements can be inserted with one command or abbrev. Completion is
32 ;; available for filenames, variables known from the script, the shell and
33 ;; the environment as well as commands.
34
35 ;;; Known Bugs:
36
37 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 ;; - Variables in `"' strings aren't fontified because there's no way of
39 ;; syntactically distinguishing those from `'' strings.
40
41 ;;; Code:
42
43 ;; page 1: variables and settings
44 ;; page 2: mode-command and utility functions
45 ;; page 3: statement syntax-commands for various shells
46 ;; page 4: various other commands
47
48 (require 'executable)
49
50 (defvar sh-ancestor-alist
51 '((ash . sh)
52 (bash . jsh)
53 (dtksh . ksh)
54 (es . rc)
55 (itcsh . tcsh)
56 (jcsh . csh)
57 (jsh . sh)
58 (ksh . ksh88)
59 (ksh88 . jsh)
60 (oash . sh)
61 (pdksh . ksh88)
62 (posix . sh)
63 (tcsh . csh)
64 (wksh . ksh88)
65 (wsh . sh)
66 (zsh . ksh88))
67 "*Alist showing the direct ancestor of various shells.
68 This is the basis for `sh-feature'. See also `sh-alias-alist'.
69 By default we have the following three hierarchies:
70
71 csh C Shell
72 jcsh C Shell with Job Control
73 tcsh Toronto C Shell
74 itcsh ? Toronto C Shell
75 rc Plan 9 Shell
76 es Extensible Shell
77 sh Bourne Shell
78 ash ? Shell
79 jsh Bourne Shell with Job Control
80 bash GNU Bourne Again Shell
81 ksh88 Korn Shell '88
82 ksh Korn Shell '93
83 dtksh CDE Desktop Korn Shell
84 pdksh Public Domain Korn Shell
85 wksh Window Korn Shell
86 zsh Z Shell
87 oash SCO OA (curses) Shell
88 posix IEEE 1003.2 Shell Standard
89 wsh ? Shell")
90
91
92 (defvar sh-alias-alist
93 (nconc (if (eq system-type 'linux)
94 '((csh . tcsh)
95 (ksh . pdksh)))
96 ;; for the time being
97 '((ksh . ksh88)
98 (sh5 . sh)))
99 "*Alist for transforming shell names to what they really are.
100 Use this where the name of the executable doesn't correspond to the type of
101 shell it really is.")
102
103
104 (defvar sh-shell-file (or (getenv "SHELL") "/bin/sh")
105 "*The executable file name for the shell being programmed.")
106
107
108 ;; bash and ksh do not need any options when run in a shell script,
109 ;; and Bill_Mann@praxisint.com says -p with ksh can do harm.
110 (defvar sh-shell-arg
111 '((bash)
112 (csh . "-f")
113 (pdksh)
114 (ksh88)
115 ;; Bill_Mann@praxisint.com says -p may be wrong for this too.
116 (rc . "-p")
117 (wksh . "-motif")
118 (zsh . "-f"))
119 "*Single argument string for the magic number. See `sh-feature'.")
120
121 (defvar sh-shell-variables nil
122 "Alist of shell variable names that should be included in completion.
123 These are used for completion in addition to all the variables named
124 in `process-environment'. Each element looks like (VAR . VAR), where
125 the car and cdr are the same symbol.")
126
127 (defvar sh-shell-variables-initialized nil
128 "Non-nil if `sh-shell-variables' is initialized.")
129
130 (defun sh-canonicalize-shell (shell)
131 "Convert a shell name SHELL to the one we should handle it as."
132 (or (symbolp shell)
133 (setq shell (intern shell)))
134 (or (cdr (assq shell sh-alias-alist))
135 shell))
136
137 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
138 "The shell being programmed. This is set by \\[sh-set-shell].")
139
140 ;;; I turned off this feature because it doesn't permit typing commands
141 ;;; in the usual way without help.
142 ;;;(defvar sh-abbrevs
143 ;;; '((csh eval sh-abbrevs shell
144 ;;; "switch" 'sh-case
145 ;;; "getopts" 'sh-while-getopts)
146
147 ;;; (es eval sh-abbrevs shell
148 ;;; "function" 'sh-function)
149
150 ;;; (ksh88 eval sh-abbrevs sh
151 ;;; "select" 'sh-select)
152
153 ;;; (rc eval sh-abbrevs shell
154 ;;; "case" 'sh-case
155 ;;; "function" 'sh-function)
156
157 ;;; (sh eval sh-abbrevs shell
158 ;;; "case" 'sh-case
159 ;;; "function" 'sh-function
160 ;;; "until" 'sh-until
161 ;;; "getopts" 'sh-while-getopts)
162
163 ;;; ;; The next entry is only used for defining the others
164 ;;; (shell "for" sh-for
165 ;;; "loop" sh-indexed-loop
166 ;;; "if" sh-if
167 ;;; "tmpfile" sh-tmp-file
168 ;;; "while" sh-while)
169
170 ;;; (zsh eval sh-abbrevs ksh88
171 ;;; "repeat" 'sh-repeat))
172 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
173 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
174 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
175
176
177
178 (defvar sh-mode-syntax-table
179 '((csh eval identity sh)
180 (sh eval sh-mode-syntax-table ()
181 ;; #'s meanings depend on context which can't be expressed here
182 ;; ?\# "<"
183 ;; ?\^l ">#"
184 ;; ?\n ">#"
185 ?\" "\"\""
186 ?\' "\"'"
187 ?\` ".`"
188 ?$ "_"
189 ?! "_"
190 ?% "_"
191 ?: "_"
192 ?. "_"
193 ?^ "_"
194 ?~ "_")
195 (rc eval sh-mode-syntax-table sh
196 ?\" "_"
197 ?\` "."))
198 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
199
200
201
202 (defvar sh-mode-map
203 (let ((map (make-sparse-keymap))
204 (menu-map (make-sparse-keymap "Insert")))
205 (define-key map "\C-c(" 'sh-function)
206 (define-key map "\C-c\C-w" 'sh-while)
207 (define-key map "\C-c\C-u" 'sh-until)
208 (define-key map "\C-c\C-t" 'sh-tmp-file)
209 (define-key map "\C-c\C-s" 'sh-select)
210 (define-key map "\C-c\C-r" 'sh-repeat)
211 (define-key map "\C-c\C-o" 'sh-while-getopts)
212 (define-key map "\C-c\C-l" 'sh-indexed-loop)
213 (define-key map "\C-c\C-i" 'sh-if)
214 (define-key map "\C-c\C-f" 'sh-for)
215 (define-key map "\C-c\C-c" 'sh-case)
216
217 (define-key map "=" 'sh-assignment)
218 (define-key map "\C-c+" 'sh-add)
219 (define-key map "\C-\M-x" 'sh-execute-region)
220 (define-key map "\C-c\C-x" 'executable-interpret)
221 (define-key map "<" 'sh-maybe-here-document)
222 (define-key map "(" 'skeleton-pair-insert-maybe)
223 (define-key map "{" 'skeleton-pair-insert-maybe)
224 (define-key map "[" 'skeleton-pair-insert-maybe)
225 (define-key map "'" 'skeleton-pair-insert-maybe)
226 (define-key map "`" 'skeleton-pair-insert-maybe)
227 (define-key map "\"" 'skeleton-pair-insert-maybe)
228
229 (define-key map "\t" 'sh-indent-line)
230 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
231 map (current-global-map))
232 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
233 map (current-global-map))
234 (substitute-key-definition 'delete-backward-char
235 'backward-delete-char-untabify
236 map (current-global-map))
237 (define-key map "\C-c:" 'sh-set-shell)
238 (substitute-key-definition 'beginning-of-defun
239 'sh-beginning-of-compound-command
240 map (current-global-map))
241 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
242 map (current-global-map))
243 (substitute-key-definition 'forward-sentence 'sh-end-of-command
244 map (current-global-map))
245 (define-key map [menu-bar insert] (cons "Insert" menu-map))
246 (define-key menu-map [sh-while] '("While Loop" . sh-while))
247 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
248 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
249 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
250 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
251 (define-key menu-map [sh-while-getopts]
252 '("Options Loop" . sh-while-getopts))
253 (define-key menu-map [sh-indexed-loop]
254 '("Indexed Loop" . sh-indexed-loop))
255 (define-key menu-map [sh-if] '("If Statement" . sh-if))
256 (define-key menu-map [sh-for] '("For Loop" . sh-for))
257 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
258 map)
259 "Keymap used in Shell-Script mode.")
260
261
262
263 (defvar sh-dynamic-complete-functions
264 '(shell-dynamic-complete-environment-variable
265 shell-dynamic-complete-command
266 comint-dynamic-complete-filename)
267 "*Functions for doing TAB dynamic completion.")
268
269
270 (defvar sh-require-final-newline
271 '((csh . t)
272 (pdksh . t)
273 (rc eval . require-final-newline)
274 (sh eval . require-final-newline))
275 "*Value of `require-final-newline' in Shell-Script mode buffers.
276 See `sh-feature'.")
277
278
279 (defvar sh-comment-prefix
280 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
281 (rc eval identity csh)
282 (sh . "\\(^\\|[ \t|&;()]\\)"))
283 "*Regexp matching what may come before a comment `#'.
284 This must contain one \\(grouping\\) since it is the basis for fontifying
285 comments as well as for `comment-start-skip'.
286 See `sh-feature'.")
287
288
289 (defvar sh-assignment-regexp
290 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
291 ;; actually spaces are only supported in let/(( ... ))
292 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
293 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
294 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
295 "*Regexp for the variable name and what may follow in an assignment.
296 First grouping matches the variable name. This is upto and including the `='
297 sign. See `sh-feature'.")
298
299
300 (defvar sh-indentation 4
301 "The width for further indentation in Shell-Script mode.")
302
303
304 (defvar sh-remember-variable-min 3
305 "*Don't remember variables less than this length for completing reads.")
306
307
308 (defvar sh-header-marker nil
309 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
310 That command is also used for setting this variable.")
311
312
313 (defvar sh-beginning-of-command
314 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
315 "*Regexp to determine the beginning of a shell command.
316 The actual command starts at the beginning of the second \\(grouping\\).")
317
318
319 (defvar sh-end-of-command
320 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
321 "*Regexp to determine the end of a shell command.
322 The actual command ends at the end of the first \\(grouping\\).")
323
324
325
326 (defvar sh-here-document-word "EOF"
327 "Word to delimit here documents.")
328
329 (defvar sh-test
330 '((sh "[ ]" . 3)
331 (ksh88 "[[ ]]" . 4))
332 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
333
334
335 (defvar sh-builtins
336 '((bash eval sh-append posix
337 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
338 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
339 "suspend" "typeset" "unalias")
340
341 ;; The next entry is only used for defining the others
342 (bourne eval sh-append shell
343 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
344 "times" "ulimit")
345
346 (csh eval sh-append shell
347 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
348 "setenv" "source" "time" "unalias" "unhash")
349
350 (dtksh eval identity wksh)
351
352 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
353 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
354
355 (jsh eval sh-append sh
356 "bg" "fg" "jobs" "kill" "stop" "suspend")
357
358 (jcsh eval sh-append csh
359 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
360
361 (ksh88 eval sh-append bourne
362 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
363 "typeset" "unalias" "whence")
364
365 (oash eval sh-append sh
366 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
367 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
368 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
369 "wmtitle" "wrefresh")
370
371 (pdksh eval sh-append ksh88
372 "bind")
373
374 (posix eval sh-append sh
375 "command")
376
377 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
378 "whatis")
379
380 (sh eval sh-append bourne
381 "hash" "test" "type")
382
383 ;; The next entry is only used for defining the others
384 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
385
386 (wksh eval sh-append ksh88
387 "Xt[A-Z][A-Za-z]*")
388
389 (zsh eval sh-append ksh88
390 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
391 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
392 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
393 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
394 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
395 "which"))
396 "*List of all shell builtins for completing read and fontification.
397 Note that on some systems not all builtins are available or some are
398 implemented as aliases. See `sh-feature'.")
399
400
401
402 (defvar sh-leading-keywords
403 '((csh "else")
404
405 (es "true" "unwind-protect" "whatis")
406
407 (rc "else")
408
409 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
410 "*List of keywords that may be immediately followed by a builtin or keyword.
411 Given some confusion between keywords and builtins depending on shell and
412 system, the distinction here has been based on whether they influence the
413 flow of control or syntax. See `sh-feature'.")
414
415
416 (defvar sh-other-keywords
417 '((bash eval sh-append bourne
418 "bye" "logout")
419
420 ;; The next entry is only used for defining the others
421 (bourne eval sh-append shell
422 "done" "esac" "fi" "for" "function" "in" "return")
423
424 (csh eval sh-append shell
425 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
426 "if" "logout" "onintr" "repeat" "switch" "then" "while")
427
428 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
429 "return" "throw" "while")
430
431 (ksh88 eval sh-append bourne
432 "select")
433
434 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
435 "while")
436
437 ;; The next entry is only used for defining the others
438 (shell "break" "case" "continue" "exec" "exit")
439
440 (zsh eval sh-append bash
441 "select"))
442 "*List of keywords not in `sh-leading-keywords'.
443 See `sh-feature'.")
444
445
446
447 (defvar sh-variables
448 '((bash eval sh-append sh
449 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
450 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
451 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
452 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
453 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
454 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
455 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
456 "SECONDS" "SHLVL" "TMOUT" "UID")
457
458 (csh eval sh-append shell
459 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
460 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
461 "shell" "status" "time" "verbose")
462
463 (es eval sh-append shell
464 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
465 "pid" "prompt" "signals")
466
467 (jcsh eval sh-append csh
468 "notify")
469
470 (ksh88 eval sh-append sh
471 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
472 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
473 "TMOUT")
474
475 (oash eval sh-append sh
476 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
477
478 (rc eval sh-append shell
479 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
480 "prompt" "status")
481
482 (sh eval sh-append shell
483 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
484
485 ;; The next entry is only used for defining the others
486 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
487 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
488 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
489 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
490
491 (tcsh eval sh-append csh
492 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
493 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
494 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
495 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
496 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
497 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
498 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
499 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
500 "wordchars")
501
502 (zsh eval sh-append ksh88
503 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
504 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
505 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
506 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
507 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
508 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
509 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
510 "List of all shell variables available for completing read.
511 See `sh-feature'.")
512
513
514
515 (defvar sh-font-lock-keywords
516 '((csh eval sh-append shell
517 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
518 font-lock-variable-name-face))
519
520 (es eval sh-append executable-font-lock-keywords
521 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
522 font-lock-variable-name-face))
523
524 (rc eval identity es)
525
526 (sh eval sh-append shell
527 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
528 font-lock-variable-name-face))
529
530 ;; The next entry is only used for defining the others
531 (shell eval sh-append executable-font-lock-keywords
532 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
533 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
534 font-lock-variable-name-face)))
535 "*Rules for highlighting shell scripts. See `sh-feature'.")
536
537 (defvar sh-font-lock-keywords-1
538 '((sh "[ \t]in\\>"))
539 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
540
541 (defvar sh-font-lock-keywords-2 ()
542 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
543
544 (defvar sh-font-lock-keywords-only t
545 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
546 Default value is `t' because Emacs' syntax is not expressive enough to
547 detect that $# does not start a comment. Thus comments are fontified by
548 regexp which means that a single apostrophe in a comment turns everything
549 upto the next one or end of buffer into a string.")
550 \f
551 ;; mode-command and utility functions
552
553 ;;;###autoload
554 (put 'sh-mode 'mode-class 'special)
555
556 ;;;###autoload
557 (defun sh-mode ()
558 "Major mode for editing shell scripts.
559 This mode works for many shells, since they all have roughly the same syntax,
560 as far as commands, arguments, variables, pipes, comments etc. are concerned.
561 Unless the file's magic number indicates the shell, your usual shell is
562 assumed. Since filenames rarely give a clue, they are not further analyzed.
563
564 This mode adapts to the variations between shells (see `sh-set-shell') by
565 means of an inheritance based feature lookup (see `sh-feature'). This
566 mechanism applies to all variables (including skeletons) that pertain to
567 shell-specific features.
568
569 The default style of this mode is that of Rosenblatt's Korn shell book.
570 The syntax of the statements varies with the shell being used. The
571 following commands are available, based on the current shell's syntax:
572
573 \\[sh-case] case statement
574 \\[sh-for] for loop
575 \\[sh-function] function definition
576 \\[sh-if] if statement
577 \\[sh-indexed-loop] indexed loop from 1 to n
578 \\[sh-while-getopts] while getopts loop
579 \\[sh-repeat] repeat loop
580 \\[sh-select] select loop
581 \\[sh-until] until loop
582 \\[sh-while] while loop
583
584 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
585 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
586 \\[sh-end-of-command] Go to end of successive commands.
587 \\[sh-beginning-of-command] Go to beginning of successive commands.
588 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
589 \\[sh-execute-region] Have optional header and region be executed in a subshell.
590
591 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
592 {, (, [, ', \", `
593 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
594
595 If you generally program a shell different from your login shell you can
596 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
597 indicate what shell it is use `sh-alias-alist' to translate.
598
599 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
600 with your script for an edit-interpret-debug cycle."
601 (interactive)
602 (kill-all-local-variables)
603 (use-local-map sh-mode-map)
604 (make-local-variable 'indent-line-function)
605 (make-local-variable 'indent-region-function)
606 (make-local-variable 'skeleton-end-hook)
607 (make-local-variable 'paragraph-start)
608 (make-local-variable 'paragraph-separate)
609 (make-local-variable 'comment-start)
610 (make-local-variable 'comment-start-skip)
611 (make-local-variable 'require-final-newline)
612 (make-local-variable 'sh-header-marker)
613 (make-local-variable 'sh-shell-file)
614 (make-local-variable 'sh-shell)
615 (make-local-variable 'skeleton-pair-alist)
616 (make-local-variable 'skeleton-pair-filter)
617 (make-local-variable 'comint-dynamic-complete-functions)
618 (make-local-variable 'comint-prompt-regexp)
619 (make-local-variable 'font-lock-keywords)
620 (make-local-variable 'font-lock-defaults)
621 (make-local-variable 'skeleton-filter)
622 (make-local-variable 'skeleton-newline-indent-rigidly)
623 (make-local-variable 'sh-shell-variables)
624 (make-local-variable 'sh-shell-variables-initialized)
625 (setq major-mode 'sh-mode
626 mode-name "Shell-script"
627 indent-line-function 'sh-indent-line
628 ;; not very clever, but enables wrapping skeletons around regions
629 indent-region-function (lambda (b e)
630 (save-excursion
631 (goto-char b)
632 (skip-syntax-backward "-")
633 (setq b (point))
634 (goto-char e)
635 (skip-syntax-backward "-")
636 (indent-rigidly b (point) sh-indentation)))
637 skeleton-end-hook (lambda ()
638 (or (eolp) (newline) (indent-relative)))
639 paragraph-start (concat page-delimiter "\\|$")
640 paragraph-separate paragraph-start
641 comment-start "# "
642 comint-dynamic-complete-functions sh-dynamic-complete-functions
643 ;; we can't look if previous line ended with `\'
644 comint-prompt-regexp "^[ \t]*"
645 font-lock-defaults
646 `((sh-font-lock-keywords
647 sh-font-lock-keywords-1
648 sh-font-lock-keywords-2)
649 ,sh-font-lock-keywords-only
650 nil
651 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
652 skeleton-pair-alist '((?` _ ?`))
653 skeleton-pair-filter 'sh-quoted-p
654 skeleton-further-elements '((< '(- (min sh-indentation
655 (current-column)))))
656 skeleton-filter 'sh-feature
657 skeleton-newline-indent-rigidly t)
658 (save-excursion
659 ;; parse or insert magic number for exec() and set all variables depending
660 ;; on the shell thus determined
661 (goto-char (point-min))
662 (sh-set-shell
663 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
664 (match-string 1)
665 sh-shell-file)))
666 (run-hooks 'sh-mode-hook))
667 ;;;###autoload
668 (defalias 'shell-script-mode 'sh-mode)
669
670
671 (defun sh-font-lock-keywords (&optional keywords)
672 "Function to get simple fontification based on `sh-font-lock-keywords'.
673 This adds rules for comments and assignments."
674 (sh-feature sh-font-lock-keywords
675 (lambda (list)
676 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
677 2 font-lock-comment-face t)
678 (,(sh-feature sh-assignment-regexp)
679 1 font-lock-variable-name-face)
680 ,@keywords
681 ,@list))))
682
683 (defun sh-font-lock-keywords-1 (&optional builtins)
684 "Function to get better fontification including keywords."
685 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
686 (mapconcat 'identity
687 (sh-feature sh-leading-keywords)
688 "\\|")
689 "\\)[ \t]+\\)?\\("
690 (mapconcat 'identity
691 (append (sh-feature sh-leading-keywords)
692 (sh-feature sh-other-keywords))
693 "\\|")
694 "\\)")))
695 (sh-font-lock-keywords
696 `(,@(if builtins
697 `((,(concat keywords "[ \t]+\\)?\\("
698 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
699 "\\)\\>")
700 (2 font-lock-keyword-face nil t)
701 (6 font-lock-function-name-face))
702 ,@(sh-feature sh-font-lock-keywords-2)))
703 (,(concat keywords "\\)\\>")
704 2 font-lock-keyword-face)
705 ,@(sh-feature sh-font-lock-keywords-1)))))
706
707 (defun sh-font-lock-keywords-2 ()
708 "Function to get better fontification including keywords and builtins."
709 (sh-font-lock-keywords-1 t))
710
711
712 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
713 "Set this buffer's shell to SHELL (a string).
714 Makes this script executable via `executable-set-magic'.
715 Calls the value of `sh-set-shell-hook' if set."
716 (interactive (list (completing-read "Name or path of shell: "
717 interpreter-mode-alist
718 (lambda (x) (eq (cdr x) 'sh-mode)))
719 (eq executable-query 'function)
720 t))
721 (setq sh-shell (intern (file-name-nondirectory shell))
722 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
723 sh-shell))
724 (setq sh-shell-file (executable-set-magic shell (sh-feature sh-shell-arg)))
725 (setq require-final-newline (sh-feature sh-require-final-newline)
726 ;;; local-abbrev-table (sh-feature sh-abbrevs)
727 font-lock-keywords nil ; force resetting
728 font-lock-syntax-table nil
729 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
730 mode-line-process (format "[%s]" sh-shell)
731 sh-shell-variables nil
732 sh-shell-variables-initialized nil
733 shell (sh-feature sh-variables))
734 (set-syntax-table (sh-feature sh-mode-syntax-table))
735 (while shell
736 (sh-remember-variable (car shell))
737 (setq shell (cdr shell)))
738 (and (boundp 'font-lock-mode)
739 font-lock-mode
740 (font-lock-mode (font-lock-mode 0)))
741 (run-hooks 'sh-set-shell-hook))
742
743
744
745 (defun sh-feature (list &optional function)
746 "Index ALIST by the current shell.
747 If ALIST isn't a list where every element is a cons, it is returned as is.
748 Else indexing follows an inheritance logic which works in two ways:
749
750 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
751 the alist contains no value for the current shell.
752
753 - If the value thus looked up is a list starting with `eval' its `cdr' is
754 first evaluated. If that is also a list and the first argument is a
755 symbol in ALIST it is not evaluated, but rather recursively looked up in
756 ALIST to allow the function called to define the value for one shell to be
757 derived from another shell. While calling the function, is the car of the
758 alist element is the current shell.
759 The value thus determined is physically replaced into the alist.
760
761 Optional FUNCTION is applied to the determined value and the result is cached
762 in ALIST."
763 (or (if (consp list)
764 (let ((l list))
765 (while (and l (consp (car l)))
766 (setq l (cdr l)))
767 (if l list)))
768 (if function
769 (cdr (assoc (setq function (cons sh-shell function)) list)))
770 (let ((sh-shell sh-shell)
771 elt val)
772 (while (and sh-shell
773 (not (setq elt (assq sh-shell list))))
774 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
775 (if (and (consp (setq val (cdr elt)))
776 (eq (car val) 'eval))
777 (setcdr elt
778 (setq val
779 (eval (if (consp (setq val (cdr val)))
780 (let ((sh-shell (car (cdr val)))
781 function)
782 (if (assq sh-shell list)
783 (setcar (cdr val)
784 (list 'quote
785 (sh-feature list))))
786 val)
787 val)))))
788 (if function
789 (nconc list
790 (list (cons function
791 (setq sh-shell (car function)
792 val (funcall (cdr function) val))))))
793 val)))
794
795
796
797 ;;; I commented this out because nobody calls it -- rms.
798 ;;;(defun sh-abbrevs (ancestor &rest list)
799 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
800 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
801 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
802 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
803 ;;;EXPANSION may be either a string or a skeleton command."
804 ;;; (or (if (boundp sh-shell)
805 ;;; (symbol-value sh-shell))
806 ;;; (progn
807 ;;; (if (listp ancestor)
808 ;;; (nconc list ancestor))
809 ;;; (define-abbrev-table sh-shell ())
810 ;;; (if (vectorp ancestor)
811 ;;; (mapatoms (lambda (atom)
812 ;;; (or (eq atom 0)
813 ;;; (define-abbrev (symbol-value sh-shell)
814 ;;; (symbol-name atom)
815 ;;; (symbol-value atom)
816 ;;; (symbol-function atom))))
817 ;;; ancestor))
818 ;;; (while list
819 ;;; (define-abbrev (symbol-value sh-shell)
820 ;;; (car list)
821 ;;; (if (stringp (car (cdr list)))
822 ;;; (car (cdr list))
823 ;;; "")
824 ;;; (if (symbolp (car (cdr list)))
825 ;;; (car (cdr list))))
826 ;;; (setq list (cdr (cdr list)))))
827 ;;; (symbol-value sh-shell)))
828
829
830 (defun sh-mode-syntax-table (table &rest list)
831 "Copy TABLE and set syntax for successive CHARs according to strings S."
832 (setq table (copy-syntax-table table))
833 (while list
834 (modify-syntax-entry (car list) (car (cdr list)) table)
835 (setq list (cdr (cdr list))))
836 table)
837
838
839 (defun sh-append (ancestor &rest list)
840 "Return list composed of first argument (a list) physically appended to rest."
841 (nconc list ancestor))
842
843
844 (defun sh-modify (skeleton &rest list)
845 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
846 (setq skeleton (copy-sequence skeleton))
847 (while list
848 (setcar (or (nthcdr (car list) skeleton)
849 (error "Index %d out of bounds" (car list)))
850 (car (cdr list)))
851 (setq list (nthcdr 2 list)))
852 skeleton)
853
854
855 (defun sh-indent-line ()
856 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
857 Lines containing only comments are considered empty."
858 (interactive)
859 (let ((previous (save-excursion
860 (while (and (not (bobp))
861 (progn
862 (forward-line -1)
863 (back-to-indentation)
864 (or (eolp)
865 (eq (following-char) ?#)))))
866 (current-column)))
867 current)
868 (save-excursion
869 (indent-to (if (eq this-command 'newline-and-indent)
870 previous
871 (if (< (current-column)
872 (setq current (progn (back-to-indentation)
873 (current-column))))
874 (if (eolp) previous 0)
875 (delete-region (point)
876 (progn (beginning-of-line) (point)))
877 (if (eolp)
878 (max previous (* (1+ (/ current sh-indentation))
879 sh-indentation))
880 (* (1+ (/ current sh-indentation)) sh-indentation))))))
881 (if (< (current-column) (current-indentation))
882 (skip-chars-forward " \t"))))
883
884
885 (defun sh-execute-region (start end &optional flag)
886 "Pass optional header and region to a subshell for noninteractive execution.
887 The working directory is that of the buffer, and only environment variables
888 are already set which is why you can mark a header within the script.
889
890 With a positive prefix ARG, instead of sending region, define header from
891 beginning of buffer to point. With a negative prefix ARG, instead of sending
892 region, clear header."
893 (interactive "r\nP")
894 (if flag
895 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
896 (point-marker)))
897 (if sh-header-marker
898 (save-excursion
899 (let (buffer-undo-list)
900 (goto-char sh-header-marker)
901 (append-to-buffer (current-buffer) start end)
902 (shell-command-on-region (point-min)
903 (setq end (+ sh-header-marker
904 (- end start)))
905 sh-shell-file)
906 (delete-region sh-header-marker end)))
907 (shell-command-on-region start end (concat sh-shell-file " -")))))
908
909
910 (defun sh-remember-variable (var)
911 "Make VARIABLE available for future completing reads in this buffer."
912 (or (< (length var) sh-remember-variable-min)
913 (getenv var)
914 (assoc var sh-shell-variables)
915 (setq sh-shell-variables (cons (cons var var) sh-shell-variables)))
916 var)
917
918
919
920 (defun sh-quoted-p ()
921 "Is point preceded by an odd number of backslashes?"
922 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
923 \f
924 ;; statement syntax-commands for various shells
925
926 ;; You are welcome to add the syntax or even completely new statements as
927 ;; appropriate for your favorite shell.
928
929 (define-skeleton sh-case
930 "Insert a case/switch statement. See `sh-feature'."
931 (csh "expression: "
932 "switch( " str " )" \n
933 > "case " (read-string "pattern: ") ?: \n
934 > _ \n
935 "breaksw" \n
936 ( "other pattern, %s: "
937 < "case " str ?: \n
938 > _ \n
939 "breaksw" \n)
940 < "default:" \n
941 > _ \n
942 resume:
943 < < "endsw")
944 (es)
945 (rc "expression: "
946 "switch( " str " ) {" \n
947 > "case " (read-string "pattern: ") \n
948 > _ \n
949 ( "other pattern, %s: "
950 < "case " str \n
951 > _ \n)
952 < "case *" \n
953 > _ \n
954 resume:
955 < < ?})
956 (sh "expression: "
957 "case " str " in" \n
958 > (read-string "pattern: ") ?\) \n
959 > _ \n
960 ";;" \n
961 ( "other pattern, %s: "
962 < str ?\) \n
963 > _ \n
964 ";;" \n)
965 < "*)" \n
966 > _ \n
967 resume:
968 < < "esac"))
969 (put 'sh-case 'menu-enable '(sh-feature sh-case))
970
971
972
973 (define-skeleton sh-for
974 "Insert a for loop. See `sh-feature'."
975 (csh eval sh-modify sh
976 1 "foreach "
977 3 " ( "
978 5 " )"
979 15 "end")
980 (es eval sh-modify rc
981 3 " = ")
982 (rc eval sh-modify sh
983 1 "for( "
984 5 " ) {"
985 15 ?})
986 (sh "Index variable: "
987 "for " str " in " _ "; do" \n
988 > _ | ?$ & (sh-remember-variable str) \n
989 < "done"))
990
991
992
993 (define-skeleton sh-indexed-loop
994 "Insert an indexed loop from 1 to n. See `sh-feature'."
995 (bash eval identity posix)
996 (csh "Index variable: "
997 "@ " str " = 1" \n
998 "while( $" str " <= " (read-string "upper limit: ") " )" \n
999 > _ ?$ str \n
1000 "@ " str "++" \n
1001 < "end")
1002 (es eval sh-modify rc
1003 3 " =")
1004 (ksh88 "Index variable: "
1005 "integer " str "=0" \n
1006 "while (( ( " str " += 1 ) <= "
1007 (read-string "upper limit: ")
1008 " )); do" \n
1009 > _ ?$ (sh-remember-variable str) \n
1010 < "done")
1011 (posix "Index variable: "
1012 str "=1" \n
1013 "while [ $" str " -le "
1014 (read-string "upper limit: ")
1015 " ]; do" \n
1016 > _ ?$ str \n
1017 str ?= (sh-add (sh-remember-variable str) 1) \n
1018 < "done")
1019 (rc "Index variable: "
1020 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
1021 (read-string "upper limit: ")
1022 "; i++ ) print i }'}) {" \n
1023 > _ ?$ (sh-remember-variable str) \n
1024 < ?})
1025 (sh "Index variable: "
1026 "for " str " in `awk 'BEGIN { for( i=1; i<="
1027 (read-string "upper limit: ")
1028 "; i++ ) print i }'`; do" \n
1029 > _ ?$ (sh-remember-variable str) \n
1030 < "done"))
1031
1032
1033 (defun sh-shell-initialize-variables ()
1034 "Scan the buffer for variable assignments.
1035 Add these variables to `sh-shell-variables'."
1036 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
1037 (save-excursion
1038 (goto-char (point-min))
1039 (setq sh-shell-variables-initialized t)
1040 (while (search-forward "=" nil t)
1041 (sh-assignment 0)))
1042 (message "Scanning buffer `%s' for variable assignments...done"
1043 (buffer-name)))
1044
1045 (defvar sh-add-buffer)
1046
1047 (defun sh-add-completer (string predicate code)
1048 "Do completion using `sh-shell-variables', but initialize it first.
1049 This function is designed for use as the \"completion table\",
1050 so it takes three arguments:
1051 STRING, the current buffer contents;
1052 PREDICATE, the predicate for filtering possible matches;
1053 CODE, which says what kind of things to do.
1054 CODE can be nil, t or `lambda'.
1055 nil means to return the best completion of STRING, or nil if there is none.
1056 t means to return a list of all possible completions of STRING.
1057 `lambda' means to return t if STRING is a valid completion as it stands."
1058 (let ((sh-shell-variables
1059 (save-excursion
1060 (set-buffer sh-add-buffer)
1061 (or sh-shell-variables-initialized
1062 (sh-shell-initialize-variables))
1063 (nconc (mapcar (lambda (var)
1064 (let ((name
1065 (substring var 0 (string-match "=" var))))
1066 (cons name name)))
1067 process-environment)
1068 sh-shell-variables))))
1069 (cond ((null code)
1070 (try-completion string sh-shell-variables predicate))
1071 ((eq code t)
1072 (all-completions string sh-shell-variables predicate))
1073 ((eq code 'lambda)
1074 (assoc string sh-shell-variables)))))
1075
1076 (defun sh-add (var delta)
1077 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1078 (interactive
1079 (let ((sh-add-buffer (current-buffer)))
1080 (list (completing-read "Variable: " 'sh-add-completer)
1081 (prefix-numeric-value current-prefix-arg))))
1082 (insert (sh-feature '((bash . "$[ ")
1083 (ksh88 . "$(( ")
1084 (posix . "$(( ")
1085 (rc . "`{expr $")
1086 (sh . "`expr $")
1087 (zsh . "$[ ")))
1088 (sh-remember-variable var)
1089 (if (< delta 0) " - " " + ")
1090 (number-to-string (abs delta))
1091 (sh-feature '((bash . " ]")
1092 (ksh88 . " ))")
1093 (posix . " ))")
1094 (rc . "}")
1095 (sh . "`")
1096 (zsh . " ]")))))
1097
1098
1099
1100 (define-skeleton sh-function
1101 "Insert a function definition. See `sh-feature'."
1102 (bash eval sh-modify ksh88
1103 3 "() {")
1104 (ksh88 "name: "
1105 "function " str " {" \n
1106 > _ \n
1107 < "}")
1108 (rc eval sh-modify ksh88
1109 1 "fn ")
1110 (sh ()
1111 "() {" \n
1112 > _ \n
1113 < "}"))
1114
1115
1116
1117 (define-skeleton sh-if
1118 "Insert an if statement. See `sh-feature'."
1119 (csh "condition: "
1120 "if( " str " ) then" \n
1121 > _ \n
1122 ( "other condition, %s: "
1123 < "else if( " str " ) then" \n
1124 > _ \n)
1125 < "else" \n
1126 > _ \n
1127 resume:
1128 < "endif")
1129 (es "condition: "
1130 "if { " str " } {" \n
1131 > _ \n
1132 ( "other condition, %s: "
1133 < "} { " str " } {" \n
1134 > _ \n)
1135 < "} {" \n
1136 > _ \n
1137 resume:
1138 < ?})
1139 (rc eval sh-modify csh
1140 3 " ) {"
1141 8 '( "other condition, %s: "
1142 < "} else if( " str " ) {" \n
1143 > _ \n)
1144 10 "} else {"
1145 17 ?})
1146 (sh "condition: "
1147 '(setq input (sh-feature sh-test))
1148 "if " str "; then" \n
1149 > _ \n
1150 ( "other condition, %s: "
1151 < "elif " str "; then" \n
1152 > _ \n)
1153 < "else" \n
1154 > _ \n
1155 resume:
1156 < "fi"))
1157
1158
1159
1160 (define-skeleton sh-repeat
1161 "Insert a repeat loop definition. See `sh-feature'."
1162 (es nil
1163 "forever {" \n
1164 > _ \n
1165 < ?})
1166 (zsh "factor: "
1167 "repeat " str "; do"\n
1168 > _ \n
1169 < "done"))
1170 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1171
1172
1173
1174 (define-skeleton sh-select
1175 "Insert a select statement. See `sh-feature'."
1176 (ksh88 "Index variable: "
1177 "select " str " in " _ "; do" \n
1178 > ?$ str \n
1179 < "done"))
1180 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1181
1182
1183
1184 (define-skeleton sh-tmp-file
1185 "Insert code to setup temporary file handling. See `sh-feature'."
1186 (bash eval identity ksh88)
1187 (csh (file-name-nondirectory (buffer-file-name))
1188 "set tmp = /tmp/" str ".$$" \n
1189 "onintr exit" \n _
1190 (and (goto-char (point-max))
1191 (not (bolp))
1192 ?\n)
1193 "exit:\n"
1194 "rm $tmp* >&/dev/null" >)
1195 (es (file-name-nondirectory (buffer-file-name))
1196 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1197 > "catch @ e {" \n
1198 > "rm $tmp^* >[2]/dev/null" \n
1199 "throw $e" \n
1200 < "} {" \n
1201 > _ \n
1202 < ?} \n
1203 < ?})
1204 (ksh88 eval sh-modify sh
1205 6 "EXIT")
1206 (rc (file-name-nondirectory (buffer-file-name))
1207 "tmp = /tmp/" str ".$pid" \n
1208 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1209 (sh (file-name-nondirectory (buffer-file-name))
1210 "TMP=/tmp/" str ".$$" \n
1211 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1212
1213
1214
1215 (define-skeleton sh-until
1216 "Insert an until loop. See `sh-feature'."
1217 (sh "condition: "
1218 '(setq input (sh-feature sh-test))
1219 "until " str "; do" \n
1220 > _ \n
1221 < "done"))
1222 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1223
1224
1225
1226 (define-skeleton sh-while
1227 "Insert a while loop. See `sh-feature'."
1228 (csh eval sh-modify sh
1229 2 "while( "
1230 4 " )"
1231 10 "end")
1232 (es eval sh-modify rc
1233 2 "while { "
1234 4 " } {")
1235 (rc eval sh-modify csh
1236 4 " ) {"
1237 10 ?})
1238 (sh "condition: "
1239 '(setq input (sh-feature sh-test))
1240 "while " str "; do" \n
1241 > _ \n
1242 < "done"))
1243
1244
1245
1246 (define-skeleton sh-while-getopts
1247 "Insert a while getopts loop. See `sh-feature'.
1248 Prompts for an options string which consists of letters for each recognized
1249 option followed by a colon `:' if the option accepts an argument."
1250 (bash eval sh-modify sh
1251 18 "${0##*/}")
1252 (csh nil
1253 "while( 1 )" \n
1254 > "switch( \"$1\" )" \n
1255 '(setq input '("- x" . 2))
1256 > >
1257 ( "option, %s: "
1258 < "case " '(eval str)
1259 '(if (string-match " +" str)
1260 (setq v1 (substring str (match-end 0))
1261 str (substring str 0 (match-beginning 0)))
1262 (setq v1 nil))
1263 str ?: \n
1264 > "set " v1 & " = $2" | -4 & _ \n
1265 (if v1 "shift") & \n
1266 "breaksw" \n)
1267 < "case --:" \n
1268 > "shift" \n
1269 < "default:" \n
1270 > "break" \n
1271 resume:
1272 < < "endsw" \n
1273 "shift" \n
1274 < "end")
1275 (ksh88 eval sh-modify sh
1276 16 "print"
1277 18 "${0##*/}"
1278 36 "OPTIND-1")
1279 (posix eval sh-modify sh
1280 18 "$(basename $0)")
1281 (sh "optstring: "
1282 "while getopts :" str " OPT; do" \n
1283 > "case $OPT in" \n
1284 > >
1285 '(setq v1 (append (vconcat str) nil))
1286 ( (prog1 (if v1 (char-to-string (car v1)))
1287 (if (eq (nth 1 v1) ?:)
1288 (setq v1 (nthcdr 2 v1)
1289 v2 "\"$OPTARG\"")
1290 (setq v1 (cdr v1)
1291 v2 nil)))
1292 < str "|+" str ?\) \n
1293 > _ v2 \n
1294 ";;" \n)
1295 < "*)" \n
1296 > "echo" " \"usage: " "`basename $0`"
1297 "[ +-" '(setq v1 (point)) str
1298 '(save-excursion
1299 (while (search-backward ":" v1 t)
1300 (replace-match " arg][ +-" t t)))
1301 (if (eq (preceding-char) ?-) -5)
1302 "][ --] args\"" \n
1303 "exit 2" \n
1304 < < "esac" \n
1305 < "done" \n
1306 "shift " (sh-add "OPTIND" -1)))
1307 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1308
1309
1310
1311 (defun sh-assignment (arg)
1312 "Remember preceding identifier for future completion and do self-insert."
1313 (interactive "p")
1314 (self-insert-command arg)
1315 (if (<= arg 1)
1316 (sh-remember-variable
1317 (save-excursion
1318 (if (re-search-forward (sh-feature sh-assignment-regexp)
1319 (prog1 (point)
1320 (beginning-of-line 1))
1321 t)
1322 (match-string 1))))))
1323
1324
1325
1326 (defun sh-maybe-here-document (arg)
1327 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1328 The document is bounded by `sh-here-document-word'."
1329 (interactive "*P")
1330 (self-insert-command (prefix-numeric-value arg))
1331 (or arg
1332 (not (eq (char-after (- (point) 2)) last-command-char))
1333 (save-excursion
1334 (backward-char 2)
1335 (sh-quoted-p))
1336 (progn
1337 (insert sh-here-document-word)
1338 (or (eolp) (looking-at "[ \t]") (insert ? ))
1339 (end-of-line 1)
1340 (while
1341 (sh-quoted-p)
1342 (end-of-line 2))
1343 (newline)
1344 (save-excursion (insert ?\n sh-here-document-word)))))
1345
1346 \f
1347 ;; various other commands
1348
1349 (autoload 'comint-dynamic-complete "comint"
1350 "Dynamically perform completion at point." t)
1351
1352 (autoload 'shell-dynamic-complete-command "shell"
1353 "Dynamically complete the command at point." t)
1354
1355 (autoload 'comint-dynamic-complete-filename "comint"
1356 "Dynamically complete the filename at point." t)
1357
1358 (autoload 'shell-dynamic-complete-environment-variable "shell"
1359 "Dynamically complete the environment variable at point." t)
1360
1361
1362
1363 (defun sh-newline-and-indent ()
1364 "Strip unquoted whitespace, insert newline, and indent like current line."
1365 (interactive "*")
1366 (indent-to (prog1 (current-indentation)
1367 (delete-region (point)
1368 (progn
1369 (or (zerop (skip-chars-backward " \t"))
1370 (if (sh-quoted-p)
1371 (forward-char)))
1372 (point)))
1373 (newline))))
1374
1375
1376
1377 (defun sh-beginning-of-command ()
1378 "Move point to successive beginnings of commands."
1379 (interactive)
1380 (if (re-search-backward sh-beginning-of-command nil t)
1381 (goto-char (match-beginning 2))))
1382
1383
1384 (defun sh-end-of-command ()
1385 "Move point to successive ends of commands."
1386 (interactive)
1387 (if (re-search-forward sh-end-of-command nil t)
1388 (goto-char (match-end 1))))
1389
1390 (provide 'sh-script)
1391 ;; sh-script.el ends here