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