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