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