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