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