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