]> code.delx.au - gnu-emacs/blob - lisp/progmodes/sh-script.el
Add ... to relevant menu entries.
[gnu-emacs] / lisp / progmodes / sh-script.el
1 ;;; sh-script.el --- shell-script editing commands for Emacs
2
3 ;; Copyright (C) 1993, 1994, 1995, 1996 by Free Software Foundation, Inc.
4
5 ;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
6 ;; Version: 2.0e
7 ;; Maintainer: FSF
8 ;; Keywords: languages, unix
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30 ;; as various derivatives are supported and easily derived from. Structured
31 ;; statements can be inserted with one command or abbrev. Completion is
32 ;; available for filenames, variables known from the script, the shell and
33 ;; the environment as well as commands.
34
35 ;;; Known Bugs:
36
37 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 ;; - Variables in `"' strings aren't fontified because there's no way of
39 ;; syntactically distinguishing those from `'' strings.
40
41 ;;; Code:
42
43 ;; page 1: variables and settings
44 ;; page 2: mode-command and utility functions
45 ;; page 3: statement syntax-commands for various shells
46 ;; page 4: various other commands
47
48 (require 'executable)
49
50 (defvar sh-ancestor-alist
51 '((ash . sh)
52 (bash . jsh)
53 (dtksh . ksh)
54 (es . rc)
55 (itcsh . tcsh)
56 (jcsh . csh)
57 (jsh . sh)
58 (ksh . ksh88)
59 (ksh88 . jsh)
60 (oash . sh)
61 (pdksh . ksh88)
62 (posix . sh)
63 (tcsh . csh)
64 (wksh . ksh88)
65 (wsh . sh)
66 (zsh . ksh88))
67 "*Alist showing the direct ancestor of various shells.
68 This is the basis for `sh-feature'. See also `sh-alias-alist'.
69 By default we have the following three hierarchies:
70
71 csh C Shell
72 jcsh C Shell with Job Control
73 tcsh Toronto C Shell
74 itcsh ? Toronto C Shell
75 rc Plan 9 Shell
76 es Extensible Shell
77 sh Bourne Shell
78 ash ? Shell
79 jsh Bourne Shell with Job Control
80 bash GNU Bourne Again Shell
81 ksh88 Korn Shell '88
82 ksh Korn Shell '93
83 dtksh CDE Desktop Korn Shell
84 pdksh Public Domain Korn Shell
85 wksh Window Korn Shell
86 zsh Z Shell
87 oash SCO OA (curses) Shell
88 posix IEEE 1003.2 Shell Standard
89 wsh ? Shell")
90
91
92 (defvar sh-alias-alist
93 (nconc (if (eq system-type 'gnu/linux)
94 '((csh . tcsh)
95 (ksh . pdksh)))
96 ;; for the time being
97 '((ksh . ksh88)
98 (sh5 . sh)))
99 "*Alist for transforming shell names to what they really are.
100 Use this where the name of the executable doesn't correspond to the type of
101 shell it really is.")
102
103
104 (defvar sh-shell-file
105 (or
106 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
107 ;; the executable extension, so comparisons with the list of
108 ;; known shells work.
109 (and (memq system-type '(ms-dos windows-nt))
110 (file-name-sans-extension (downcase (getenv "SHELL"))))
111 (getenv "SHELL")
112 "/bin/sh")
113 "*The executable file name for the shell being programmed.")
114
115
116 (defvar sh-shell-arg
117 ;; bash does not need any options when run in a shell script,
118 '((bash)
119 (csh . "-f")
120 (pdksh)
121 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
122 (ksh88)
123 ;; -p means don't initialize functions from the environment.
124 (rc . "-p")
125 ;; Someone proposed -motif, but we don't want to encourage
126 ;; use of a non-free widget set.
127 (wksh)
128 ;; -f means don't run .zshrc.
129 (zsh . "-f"))
130 "*Single argument string for the magic number. See `sh-feature'.")
131
132 (defvar sh-shell-variables nil
133 "Alist of shell variable names that should be included in completion.
134 These are used for completion in addition to all the variables named
135 in `process-environment'. Each element looks like (VAR . VAR), where
136 the car and cdr are the same symbol.")
137
138 (defvar sh-shell-variables-initialized nil
139 "Non-nil if `sh-shell-variables' is initialized.")
140
141 (defun sh-canonicalize-shell (shell)
142 "Convert a shell name SHELL to the one we should handle it as."
143 (or (symbolp shell)
144 (setq shell (intern shell)))
145 (or (cdr (assq shell sh-alias-alist))
146 shell))
147
148 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
149 "The shell being programmed. This is set by \\[sh-set-shell].")
150
151 ;;; I turned off this feature because it doesn't permit typing commands
152 ;;; in the usual way without help.
153 ;;;(defvar sh-abbrevs
154 ;;; '((csh eval sh-abbrevs shell
155 ;;; "switch" 'sh-case
156 ;;; "getopts" 'sh-while-getopts)
157
158 ;;; (es eval sh-abbrevs shell
159 ;;; "function" 'sh-function)
160
161 ;;; (ksh88 eval sh-abbrevs sh
162 ;;; "select" 'sh-select)
163
164 ;;; (rc eval sh-abbrevs shell
165 ;;; "case" 'sh-case
166 ;;; "function" 'sh-function)
167
168 ;;; (sh eval sh-abbrevs shell
169 ;;; "case" 'sh-case
170 ;;; "function" 'sh-function
171 ;;; "until" 'sh-until
172 ;;; "getopts" 'sh-while-getopts)
173
174 ;;; ;; The next entry is only used for defining the others
175 ;;; (shell "for" sh-for
176 ;;; "loop" sh-indexed-loop
177 ;;; "if" sh-if
178 ;;; "tmpfile" sh-tmp-file
179 ;;; "while" sh-while)
180
181 ;;; (zsh eval sh-abbrevs ksh88
182 ;;; "repeat" 'sh-repeat))
183 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
184 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
185 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
186
187
188
189 (defvar sh-mode-syntax-table
190 '((sh eval sh-mode-syntax-table ()
191 ?\# "<"
192 ?\^l ">#"
193 ?\n ">#"
194 ?\" "\"\""
195 ?\' "\"'"
196 ?\` "\"`"
197 ?$ "\\" ; `escape' so $# doesn't start a comment
198 ?! "_"
199 ?% "_"
200 ?: "_"
201 ?. "_"
202 ?^ "_"
203 ?~ "_")
204 (csh eval identity sh)
205 (rc eval identity sh))
206 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
207
208
209
210 (defvar sh-mode-map
211 (let ((map (make-sparse-keymap))
212 (menu-map (make-sparse-keymap "Insert")))
213 (define-key map "\C-c(" 'sh-function)
214 (define-key map "\C-c\C-w" 'sh-while)
215 (define-key map "\C-c\C-u" 'sh-until)
216 (define-key map "\C-c\C-t" 'sh-tmp-file)
217 (define-key map "\C-c\C-s" 'sh-select)
218 (define-key map "\C-c\C-r" 'sh-repeat)
219 (define-key map "\C-c\C-o" 'sh-while-getopts)
220 (define-key map "\C-c\C-l" 'sh-indexed-loop)
221 (define-key map "\C-c\C-i" 'sh-if)
222 (define-key map "\C-c\C-f" 'sh-for)
223 (define-key map "\C-c\C-c" 'sh-case)
224
225 (define-key map "=" 'sh-assignment)
226 (define-key map "\C-c+" 'sh-add)
227 (define-key map "\C-\M-x" 'sh-execute-region)
228 (define-key map "\C-c\C-x" 'executable-interpret)
229 (define-key map "<" 'sh-maybe-here-document)
230 (define-key map "(" 'skeleton-pair-insert-maybe)
231 (define-key map "{" 'skeleton-pair-insert-maybe)
232 (define-key map "[" 'skeleton-pair-insert-maybe)
233 (define-key map "'" 'skeleton-pair-insert-maybe)
234 (define-key map "`" 'skeleton-pair-insert-maybe)
235 (define-key map "\"" 'skeleton-pair-insert-maybe)
236
237 (define-key map "\t" 'sh-indent-line)
238 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
239 map (current-global-map))
240 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
241 map (current-global-map))
242 (substitute-key-definition 'delete-backward-char
243 'backward-delete-char-untabify
244 map (current-global-map))
245 (define-key map "\C-c:" 'sh-set-shell)
246 (substitute-key-definition 'beginning-of-defun
247 'sh-beginning-of-compound-command
248 map (current-global-map))
249 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
250 map (current-global-map))
251 (substitute-key-definition 'forward-sentence 'sh-end-of-command
252 map (current-global-map))
253 (define-key map [menu-bar insert] (cons "Insert" menu-map))
254 (define-key menu-map [sh-while] '("While Loop" . sh-while))
255 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
256 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
257 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
258 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
259 (define-key menu-map [sh-while-getopts]
260 '("Options Loop" . sh-while-getopts))
261 (define-key menu-map [sh-indexed-loop]
262 '("Indexed Loop" . sh-indexed-loop))
263 (define-key menu-map [sh-if] '("If Statement" . sh-if))
264 (define-key menu-map [sh-for] '("For Loop" . sh-for))
265 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
266 map)
267 "Keymap used in Shell-Script mode.")
268
269
270
271 (defvar sh-dynamic-complete-functions
272 '(shell-dynamic-complete-environment-variable
273 shell-dynamic-complete-command
274 comint-dynamic-complete-filename)
275 "*Functions for doing TAB dynamic completion.")
276
277
278 (defvar sh-require-final-newline
279 '((csh . t)
280 (pdksh . t)
281 (rc eval . require-final-newline)
282 (sh eval . require-final-newline))
283 "*Value of `require-final-newline' in Shell-Script mode buffers.
284 See `sh-feature'.")
285
286
287 (defvar sh-assignment-regexp
288 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
289 ;; actually spaces are only supported in let/(( ... ))
290 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
291 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
292 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
293 "*Regexp for the variable name and what may follow in an assignment.
294 First grouping matches the variable name. This is upto and including the `='
295 sign. See `sh-feature'.")
296
297
298 (defvar sh-indentation 4
299 "The width for further indentation in Shell-Script mode.")
300
301
302 (defvar sh-remember-variable-min 3
303 "*Don't remember variables less than this length for completing reads.")
304
305
306 (defvar sh-header-marker nil
307 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
308 That command is also used for setting this variable.")
309
310
311 (defvar sh-beginning-of-command
312 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
313 "*Regexp to determine the beginning of a shell command.
314 The actual command starts at the beginning of the second \\(grouping\\).")
315
316
317 (defvar sh-end-of-command
318 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
319 "*Regexp to determine the end of a shell command.
320 The actual command ends at the end of the first \\(grouping\\).")
321
322
323
324 (defvar sh-here-document-word "EOF"
325 "Word to delimit here documents.")
326
327 (defvar sh-test
328 '((sh "[ ]" . 3)
329 (ksh88 "[[ ]]" . 4))
330 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
331
332
333 (defvar sh-builtins
334 '((bash eval sh-append posix
335 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
336 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
337 "suspend" "typeset" "unalias")
338
339 ;; The next entry is only used for defining the others
340 (bourne eval sh-append shell
341 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
342 "times" "ulimit")
343
344 (csh eval sh-append shell
345 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
346 "setenv" "source" "time" "unalias" "unhash")
347
348 (dtksh eval identity wksh)
349
350 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
351 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
352
353 (jsh eval sh-append sh
354 "bg" "fg" "jobs" "kill" "stop" "suspend")
355
356 (jcsh eval sh-append csh
357 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
358
359 (ksh88 eval sh-append bourne
360 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
361 "typeset" "unalias" "whence")
362
363 (oash eval sh-append sh
364 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
365 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
366 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
367 "wmtitle" "wrefresh")
368
369 (pdksh eval sh-append ksh88
370 "bind")
371
372 (posix eval sh-append sh
373 "command")
374
375 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
376 "whatis")
377
378 (sh eval sh-append bourne
379 "hash" "test" "type")
380
381 ;; The next entry is only used for defining the others
382 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
383
384 (wksh eval sh-append ksh88
385 "Xt[A-Z][A-Za-z]*")
386
387 (zsh eval sh-append ksh88
388 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
389 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
390 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
391 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
392 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
393 "which"))
394 "*List of all shell builtins for completing read and fontification.
395 Note that on some systems not all builtins are available or some are
396 implemented as aliases. See `sh-feature'.")
397
398
399
400 (defvar sh-leading-keywords
401 '((csh "else")
402
403 (es "true" "unwind-protect" "whatis")
404
405 (rc "else")
406
407 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
408 "*List of keywords that may be immediately followed by a builtin or keyword.
409 Given some confusion between keywords and builtins depending on shell and
410 system, the distinction here has been based on whether they influence the
411 flow of control or syntax. See `sh-feature'.")
412
413
414 (defvar sh-other-keywords
415 '((bash eval sh-append bourne
416 "bye" "logout")
417
418 ;; The next entry is only used for defining the others
419 (bourne eval sh-append sh
420 "function")
421
422 (csh eval sh-append shell
423 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
424 "if" "logout" "onintr" "repeat" "switch" "then" "while")
425
426 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
427 "return" "throw" "while")
428
429 (ksh88 eval sh-append bourne
430 "select")
431
432 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
433 "while")
434
435 (sh eval sh-append shell
436 "done" "esac" "fi" "for" "in" "return")
437
438 ;; The next entry is only used for defining the others
439 (shell "break" "case" "continue" "exec" "exit")
440
441 (zsh eval sh-append bash
442 "select"))
443 "*List of keywords not in `sh-leading-keywords'.
444 See `sh-feature'.")
445
446
447
448 (defvar sh-variables
449 '((bash eval sh-append sh
450 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
451 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
452 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
453 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
454 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
455 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
456 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
457 "SECONDS" "SHLVL" "TMOUT" "UID")
458
459 (csh eval sh-append shell
460 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
461 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
462 "shell" "status" "time" "verbose")
463
464 (es eval sh-append shell
465 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
466 "pid" "prompt" "signals")
467
468 (jcsh eval sh-append csh
469 "notify")
470
471 (ksh88 eval sh-append sh
472 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
473 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
474 "TMOUT")
475
476 (oash eval sh-append sh
477 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
478
479 (rc eval sh-append shell
480 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
481 "prompt" "status")
482
483 (sh eval sh-append shell
484 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
485
486 ;; The next entry is only used for defining the others
487 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
488 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
489 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
490 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
491
492 (tcsh eval sh-append csh
493 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
494 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
495 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
496 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
497 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
498 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
499 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
500 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
501 "wordchars")
502
503 (zsh eval sh-append ksh88
504 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
505 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
506 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
507 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
508 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
509 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
510 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
511 "List of all shell variables available for completing read.
512 See `sh-feature'.")
513
514
515
516 (defvar sh-font-lock-keywords
517 '((csh eval sh-append shell
518 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
519 font-lock-variable-name-face))
520
521 (es eval sh-append executable-font-lock-keywords
522 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
523 font-lock-variable-name-face))
524
525 (rc eval identity es)
526
527 (sh eval sh-append shell
528 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
529 font-lock-variable-name-face))
530
531 ;; The next entry is only used for defining the others
532 (shell eval sh-append executable-font-lock-keywords
533 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
534 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
535 font-lock-variable-name-face)))
536 "*Rules for highlighting shell scripts. See `sh-feature'.")
537
538 (defvar sh-font-lock-keywords-1
539 '((sh "[ \t]in\\>"))
540 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
541
542 (defvar sh-font-lock-keywords-2 ()
543 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
544
545 \f
546 ;; mode-command and utility functions
547
548 ;;;###autoload
549 (put 'sh-mode 'mode-class 'special)
550
551 ;;;###autoload
552 (defun sh-mode ()
553 "Major mode for editing shell scripts.
554 This mode works for many shells, since they all have roughly the same syntax,
555 as far as commands, arguments, variables, pipes, comments etc. are concerned.
556 Unless the file's magic number indicates the shell, your usual shell is
557 assumed. Since filenames rarely give a clue, they are not further analyzed.
558
559 This mode adapts to the variations between shells (see `sh-set-shell') by
560 means of an inheritance based feature lookup (see `sh-feature'). This
561 mechanism applies to all variables (including skeletons) that pertain to
562 shell-specific features.
563
564 The default style of this mode is that of Rosenblatt's Korn shell book.
565 The syntax of the statements varies with the shell being used. The
566 following commands are available, based on the current shell's syntax:
567
568 \\[sh-case] case statement
569 \\[sh-for] for loop
570 \\[sh-function] function definition
571 \\[sh-if] if statement
572 \\[sh-indexed-loop] indexed loop from 1 to n
573 \\[sh-while-getopts] while getopts loop
574 \\[sh-repeat] repeat loop
575 \\[sh-select] select loop
576 \\[sh-until] until loop
577 \\[sh-while] while loop
578
579 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
580 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
581 \\[sh-end-of-command] Go to end of successive commands.
582 \\[sh-beginning-of-command] Go to beginning of successive commands.
583 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
584 \\[sh-execute-region] Have optional header and region be executed in a subshell.
585
586 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
587 {, (, [, ', \", `
588 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
589
590 If you generally program a shell different from your login shell you can
591 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
592 indicate what shell it is use `sh-alias-alist' to translate.
593
594 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
595 with your script for an edit-interpret-debug cycle."
596 (interactive)
597 (kill-all-local-variables)
598 (use-local-map sh-mode-map)
599 (make-local-variable 'indent-line-function)
600 (make-local-variable 'indent-region-function)
601 (make-local-variable 'skeleton-end-hook)
602 (make-local-variable 'paragraph-start)
603 (make-local-variable 'paragraph-separate)
604 (make-local-variable 'comment-start)
605 (make-local-variable 'comment-start-skip)
606 (make-local-variable 'require-final-newline)
607 (make-local-variable 'sh-header-marker)
608 (make-local-variable 'sh-shell-file)
609 (make-local-variable 'sh-shell)
610 (make-local-variable 'skeleton-pair-alist)
611 (make-local-variable 'skeleton-pair-filter)
612 (make-local-variable 'comint-dynamic-complete-functions)
613 (make-local-variable 'comint-prompt-regexp)
614 (make-local-variable 'font-lock-defaults)
615 (make-local-variable 'skeleton-filter)
616 (make-local-variable 'skeleton-newline-indent-rigidly)
617 (make-local-variable 'sh-shell-variables)
618 (make-local-variable 'sh-shell-variables-initialized)
619 (setq major-mode 'sh-mode
620 mode-name "Shell-script"
621 indent-line-function 'sh-indent-line
622 ;; not very clever, but enables wrapping skeletons around regions
623 indent-region-function (lambda (b e)
624 (save-excursion
625 (goto-char b)
626 (skip-syntax-backward "-")
627 (setq b (point))
628 (goto-char e)
629 (skip-syntax-backward "-")
630 (indent-rigidly b (point) sh-indentation)))
631 skeleton-end-hook (lambda ()
632 (or (eolp) (newline) (indent-relative)))
633 paragraph-start (concat page-delimiter "\\|$")
634 paragraph-separate paragraph-start
635 comment-start "# "
636 comint-dynamic-complete-functions sh-dynamic-complete-functions
637 ;; we can't look if previous line ended with `\'
638 comint-prompt-regexp "^[ \t]*"
639 font-lock-defaults
640 `((sh-font-lock-keywords
641 sh-font-lock-keywords-1
642 sh-font-lock-keywords-2)
643 nil nil
644 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
645 skeleton-pair-alist '((?` _ ?`))
646 skeleton-pair-filter 'sh-quoted-p
647 skeleton-further-elements '((< '(- (min sh-indentation
648 (current-column)))))
649 skeleton-filter 'sh-feature
650 skeleton-newline-indent-rigidly t)
651 ;; Parse or insert magic number for exec, and set all variables depending
652 ;; on the shell thus determined.
653 (let ((interpreter
654 (save-excursion
655 (goto-char (point-min))
656 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
657 (buffer-substring (match-beginning 2)
658 (match-end 2))))))
659 (if interpreter
660 (sh-set-shell interpreter nil nil)))
661 (run-hooks 'sh-mode-hook))
662 ;;;###autoload
663 (defalias 'shell-script-mode 'sh-mode)
664
665
666 (defun sh-font-lock-keywords (&optional keywords)
667 "Function to get simple fontification based on `sh-font-lock-keywords'.
668 This adds rules for comments and assignments."
669 (sh-feature sh-font-lock-keywords
670 (lambda (list)
671 `((,(sh-feature sh-assignment-regexp)
672 1 font-lock-variable-name-face)
673 ,@keywords
674 ,@list))))
675
676 (defun sh-font-lock-keywords-1 (&optional builtins)
677 "Function to get better fontification including keywords."
678 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
679 (mapconcat 'identity
680 (sh-feature sh-leading-keywords)
681 "\\|")
682 "\\)[ \t]+\\)?\\("
683 (mapconcat 'identity
684 (append (sh-feature sh-leading-keywords)
685 (sh-feature sh-other-keywords))
686 "\\|")
687 "\\)")))
688 (sh-font-lock-keywords
689 `(,@(if builtins
690 `((,(concat keywords "[ \t]+\\)?\\("
691 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
692 "\\)\\>")
693 (2 font-lock-keyword-face nil t)
694 (6 font-lock-builtin-face))
695 ,@(sh-feature sh-font-lock-keywords-2)))
696 (,(concat keywords "\\)\\>")
697 2 font-lock-keyword-face)
698 ,@(sh-feature sh-font-lock-keywords-1)))))
699
700 (defun sh-font-lock-keywords-2 ()
701 "Function to get better fontification including keywords and builtins."
702 (sh-font-lock-keywords-1 t))
703
704
705 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
706 "Set this buffer's shell to SHELL (a string).
707 Makes this script executable via `executable-set-magic', and sets up the
708 proper starting #!-line, if INSERT-FLAG is non-nil.
709 Calls the value of `sh-set-shell-hook' if set."
710 (interactive (list (completing-read "Name or path of shell: "
711 interpreter-mode-alist
712 (lambda (x) (eq (cdr x) 'sh-mode)))
713 (eq executable-query 'function)
714 t))
715 (setq sh-shell (intern (file-name-nondirectory shell))
716 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
717 sh-shell))
718 (if insert-flag
719 (setq sh-shell-file
720 (executable-set-magic shell (sh-feature sh-shell-arg)
721 no-query-flag insert-flag)))
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 "#+[\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