1 ;;; sh-script.el --- shell-script editing commands for Emacs
2 ;; Copyright (C) 1993, 1994, 1995 by Free Software Foundation, Inc.
4 ;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
7 ;; Keywords: languages, unix
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to
23 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
27 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
28 ;; as various derivatives are supported and easily derived from. Structured
29 ;; statements can be inserted with one command or abbrev. Completion is
30 ;; available for filenames, variables known from the script, the shell and
31 ;; the environment as well as commands.
35 ;; - Since GNU Emacs' syntax can't handle the context-sensitive meanings of
36 ;; the variable/number base/comment symbol `#', that has to be fontified by
37 ;; regexp. This alas means that a quote `'' or `"' in a comment will
38 ;; fontify VERY badly. The alternative is to have these frequent constructs
39 ;; with `#' fontify as comments. Or maybe we intoduce a 'syntax text-
41 ;; - Variables in `"' strings aren't fontified because there's no way of
42 ;; syntactically distinguishing those from `'' strings.
46 ;; page 1: variables and settings
47 ;; page 2: mode-command and utility functions
48 ;; page 3: statement syntax-commands for various shells
49 ;; page 4: various other commands
55 (or (assoc "sh" interpreter-mode-alist)
58 ;; - that have a suffix .sh, .csh or .shar (shell archive)
59 ;; - that contain ressources for the various shells
60 ;; - startup files for X11
61 (cons '("\\.c?sh\\'\\|\\.shar\\'\\|/\\.\\(z?profile\\|bash_profile\\|z?login\\|bash_login\\|z?logout\\|bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\|rcrc\\|[kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
63 interpreter-mode-alist
64 (nconc '(("ash" . sh-mode)
81 interpreter-mode-alist)))
84 (defvar sh-ancestor-alist
101 "*Alist showing the direct ancestor of various shells.
102 This is the basis for `sh-feature'. See also `sh-alias-alist'.
103 By default we have the following three hierarchies:
106 jcsh C Shell with Job Control
108 itcsh ? Toronto C Shell
113 jsh Bourne Shell with Job Control
114 bash GNU Bourne Again Shell
117 dtksh CDE Desktop Korn Shell
118 pdksh Public Domain Korn Shell
119 wksh Window Korn Shell
121 oash SCO OA (curses) Shell
122 posix IEEE 1003.2 Shell Standard
126 (defvar sh-alias-alist
127 (nconc (if (eq system-type 'linux)
131 ;; for the time being
134 "*Alist for transforming shell names to what they really are.
135 Use this where the name of the executable doesn't correspond to the type of
136 shell it really is.")
140 '(("ash") ("bash") ("csh") ("dtksh") ("es") ("itcsh") ("jsh") ("ksh")
141 ("oash") ("pdksh") ("rc") ("sh") ("tcsh") ("wksh") ("wsh") ("zsh"))
142 "*Alist of shells available for completing read in `sh-set-shell'.")
145 (defvar sh-shell-path (or (getenv "SHELL") "/bin/sh")
146 "*The executable of the shell being programmed.")
152 (ksh88 eval progn nil (if (file-exists-p "/etc/suid_profile") nil "-p"))
157 "*Single argument string for the magic number. See `sh-feature'.")
161 (defvar sh-shell (or (cdr (assq (intern (file-name-nondirectory sh-shell-path))
163 (intern (file-name-nondirectory sh-shell-path)))
164 "The shell being programmed. This is set by \\[sh-set-shell].")
169 '((csh eval sh-abbrevs shell
172 (es eval sh-abbrevs shell
173 "function" 'sh-function)
175 (ksh88 eval sh-abbrevs sh
178 (rc eval sh-abbrevs shell
180 "function" 'sh-function)
182 (sh eval sh-abbrevs shell
184 "function" 'sh-function
186 "getopts" 'sh-while-getopts)
188 ;; The next entry is only used for defining the others
190 "loop" sh-indexed-loop
192 "tmpfile" sh-tmp-file
195 (zsh eval sh-abbrevs ksh88
196 "repeat" 'sh-repeat))
197 "Abbrev-table used in Shell-Script mode. See `sh-feature'.
198 Due to the internal workings of abbrev tables, the shell name symbol is
199 actually defined as the table for the like of \\[edit-abbrevs].")
203 (defvar sh-mode-syntax-table
204 '((csh eval identity sh)
205 (sh eval sh-mode-syntax-table ()
206 ;; #'s meanings depend on context which can't be expressed here
220 (rc eval sh-mode-syntax-table sh
223 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
228 (let ((map (make-sparse-keymap)))
229 (define-key map "\C-c(" 'sh-function)
230 (define-key map "\C-c\C-w" 'sh-while)
231 (define-key map "\C-c\C-u" 'sh-until)
232 (define-key map "\C-c\C-t" 'sh-tmp-file)
233 (define-key map "\C-c\C-s" 'sh-select)
234 (define-key map "\C-c\C-r" 'sh-repeat)
235 (define-key map "\C-c\C-o" 'sh-while-getopts)
236 (define-key map "\C-c\C-l" 'sh-indexed-loop)
237 (define-key map "\C-c\C-i" 'sh-if)
238 (define-key map "\C-c\C-f" 'sh-for)
239 (define-key map "\C-c\C-c" 'sh-case)
241 (define-key map "=" 'sh-assignment)
242 (define-key map "\C-c+" 'sh-add)
243 (define-key map "\C-c|" 'sh-execute-region)
244 (define-key map "\C-c!" 'executable-interpret)
245 (define-key map "<" 'sh-maybe-here-document)
246 (define-key map "(" 'pair-insert-maybe)
247 (define-key map "{" 'pair-insert-maybe)
248 (define-key map "[" 'pair-insert-maybe)
249 (define-key map "'" 'pair-insert-maybe)
250 (define-key map "`" 'pair-insert-maybe)
251 (define-key map "\"" 'pair-insert-maybe)
253 (define-key map "\t" 'sh-indent-line)
254 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
255 map (current-global-map))
256 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
257 map (current-global-map))
258 (substitute-key-definition 'delete-backward-char
259 'backward-delete-char-untabify
260 map (current-global-map))
261 (define-key map "\C-c:" 'sh-set-shell)
262 (substitute-key-definition 'beginning-of-defun
263 'sh-beginning-of-compound-command
264 map (current-global-map))
265 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
266 map (current-global-map))
267 (substitute-key-definition 'forward-sentence 'sh-end-of-command
268 map (current-global-map))
269 (define-key map [menu-bar insert]
270 (cons "Insert" (make-sparse-keymap "Insert")))
271 (define-key map [menu-bar insert sh-while]
272 '("While loop" . sh-while))
273 (define-key map [menu-bar insert sh-until]
274 '("Until loop" . sh-until))
275 (define-key map [menu-bar insert sh-tmp-file]
276 '("Temporary file" . sh-tmp-file))
277 (define-key map [menu-bar insert sh-select]
278 '("Select statement" . sh-select))
279 (define-key map [menu-bar insert sh-repeat]
280 '("Repeat loop" . sh-repeat))
281 (define-key map [menu-bar insert sh-while-getopts]
282 '("Options loop" . sh-while-getopts))
283 (define-key map [menu-bar insert sh-indexed-loop]
284 '("Indexed loop" . sh-indexed-loop))
285 (define-key map [menu-bar insert sh-if]
286 '("If statement" . sh-if))
287 (define-key map [menu-bar insert sh-for]
288 '("For loop" . sh-for))
289 (define-key map [menu-bar insert sh-case]
290 '("Case statement" . sh-case))
292 "Keymap used in Shell-Script mode.")
296 (defvar sh-dynamic-complete-functions
297 '(shell-dynamic-complete-environment-variable
298 shell-dynamic-complete-command
299 comint-dynamic-complete-filename)
300 "*Functions for doing TAB dynamic completion.")
303 (defvar sh-require-final-newline
306 (rc eval . require-final-newline)
307 (sh eval . require-final-newline))
308 "*Value of `require-final-newline' in Shell-Script mode buffers.
312 (defvar sh-comment-prefix
313 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
314 (rc eval identity csh)
315 (sh . "\\(^\\|[ \t|&;()]\\)"))
316 "*Regexp matching what may come before a comment `#'.
317 This must contain one \\(grouping\\) since it is the basis for fontifying
318 comments as well as for `comment-start-skip'.
322 (defvar sh-assignment-regexp
323 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
324 ;; actually spaces are only supported in let/(( ... ))
325 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
326 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
327 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
328 "*Regexp for the variable name and what may follow in an assignment.
329 First grouping matches the variable name. This is upto and including the `='
330 sign. See `sh-feature'.")
333 (defvar sh-indentation 4
334 "The width for further indentation in Shell-Script mode.")
337 (defvar sh-remember-variable-min 3
338 "*Don't remember variables less than this length for completing reads.")
341 (defvar sh-header-marker nil
342 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
343 That command is also used for setting this variable.")
346 (defvar sh-beginning-of-command
347 "\\([;({`|&]\\|^\\)[ \t]*\\([/~:a-zA-Z0-9]\\)"
348 "*Regexp to determine the beginning of a shell command.
349 The actual command starts at the beginning of the second \\(grouping\\).")
352 (defvar sh-end-of-command
353 "\\([/~:a-zA-Z0-9]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
354 "*Regexp to determine the end of a shell command.
355 The actual command ends at the end of the first \\(grouping\\).")
359 (defvar sh-here-document-word "EOF"
360 "Word to delimit here documents.")
364 '((bash eval sh-append sh
365 "alias" "bg" "bind" "builtin" "bye" "command" "declare" "dirs"
366 "enable" "fc" "fg" "function" "help" "history" "jobs" "kill" "let"
367 "local" "logout" "popd" "pushd" "source" "suspend" "typeset"
370 ;; The next entry is only used for defining the others
371 (bourne eval sh-append shell
372 "do" "done" "elif" "esac" "export" "fi" "for" "getopts" "in"
373 "newgrp" "pwd" "read" "readonly" "return" "times" "trap" "ulimit"
376 (csh eval sh-append shell
377 "alias" "breaksw" "chdir" "default" "end" "endif" "endsw" "foreach"
378 "glob" "goto" "history" "limit" "logout" "nice" "nohup" "onintr"
379 "rehash" "repeat" "setenv" "source" "switch" "time" "unalias"
382 (es "access" "apids" "break" "catch" "cd" "echo" "eval" "exec" "exit"
383 "false" "fn" "for" "forever" "fork" "if" "let" "limit" "local"
384 "newpgrp" "result" "return" "throw" "time" "true" "umask"
385 "unwind-protect" "var" "vars" "wait" "whatis" "while")
387 (jsh eval sh-append sh
388 "bg" "fg" "jobs" "kill" "stop" "suspend")
390 (jcsh eval sh-append csh
391 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
393 (ksh88 eval sh-append bourne
394 "alias" "bg" "false" "fc" "fg" "function" "jobs" "kill" "let"
395 "print" "select" "time" "typeset" "unalias" "whence")
397 (oash eval sh-append sh
398 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
399 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
400 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
401 "wmtitle" "wrefresh")
403 (pdksh eval sh-append ksh88
406 (posix eval sh-append sh
409 (rc "break" "builtin" "case" "cd" "echo" "else" "eval" "exec" "exit" "fn"
410 "for" "if" "in" "limit" "newpgrp" "return" "shift" "switch" "umask"
411 "wait" "whatis" "while")
413 (sh eval sh-append bourne
414 "hash" "test" "type")
416 ;; The next entry is only used for defining the others
417 (shell "break" "case" "cd" "continue" "echo" "else" "eval" "exec" "exit"
418 "if" "set" "shift" "then" "umask" "unset" "wait" "while")
420 (zsh eval sh-append ksh88
421 "autoload" "bindkey" "builtin" "bye" "chdir" "compctl" "declare"
422 "dirs" "disable" "disown" "echotc" "enable" "functions" "getln"
423 "hash" "history" "integer" "limit" "local" "log" "logout" "popd"
424 "pushd" "r" "readonly" "rehash" "sched" "setopt" "source" "suspend"
425 "true" "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt"
427 "*List of all shell builtins for completing read and fontification.
428 Note that on some systems not all builtins are available or some are
429 implemented as aliases. See `sh-feature'.")
432 (defvar sh-leading-keywords
433 '((bash eval sh-append sh
434 "builtin" "command" "enable")
436 ;; The next entry is only used for defining the others
437 (bourne "do" "elif" "else" "eval" "if" "then" "trap" "until" "while")
441 (es "eval" "time" "true" "umask"
442 "unwind-protect" "whatis")
444 (ksh88 eval sh-append bourne
447 (posix eval sh-append sh
450 (rc "builtin" "else" "eval" "whatis")
452 (sh eval sh-append bourne
455 (zsh eval sh-append ksh88
456 "builtin" "disable" "enable" "type" "unhash" "which"))
457 "*List of keywords that may be immediately followed by a command(-name).
463 '((bash eval sh-append sh
464 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
465 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
466 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
467 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
468 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
469 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
470 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
471 "SECONDS" "SHLVL" "TMOUT" "UID")
473 (csh eval sh-append shell
474 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
475 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
476 "shell" "status" "time" "verbose")
478 (es eval sh-append shell
479 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
480 "pid" "prompt" "signals")
482 (jcsh eval sh-append csh
485 (ksh88 eval sh-append sh
486 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
487 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
490 (oash eval sh-append sh
491 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
493 (rc eval sh-append shell
494 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
497 (sh eval sh-append shell
498 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
500 ;; The next entry is only used for defining the others
501 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
502 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
503 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
504 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
506 (tcsh eval sh-append csh
507 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
508 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
509 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
510 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
511 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
512 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
513 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
514 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
517 (zsh eval sh-append ksh88
518 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
519 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
520 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
521 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
522 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
523 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
524 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
525 "List of all shell variables available for completing read.
530 (defvar sh-font-lock-keywords
531 '((csh eval sh-append shell
532 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
533 font-lock-function-name-face)
534 '("\\(^\\|[ \t]\\)\\(default\\):" 2
535 font-lock-keyword-face t))
537 (dtksh eval identity wksh)
539 (es eval sh-append executable-font-lock-keywords
540 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
541 font-lock-function-name-face))
543 (rc eval sh-append es
544 '("\\(^\\|[ \t]\\)\\(else\\( if\\)?\\)\\>" 2
545 font-lock-keyword-face t))
547 (sh eval sh-append shell
548 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
549 font-lock-function-name-face)
550 " in\\([ \t]\\|$\\)")
552 ;; The next entry is only used for defining the others
553 (shell eval sh-append executable-font-lock-keywords
554 '("\\\\." 0 font-lock-string-face)
555 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
556 font-lock-function-name-face))
558 (wksh eval sh-append ksh88
559 '("\\(^\\|[^-._A-Za-z0-9]\\)\\(Xt[A-Z][A-Za-z]*\\)\\($\\|[^-._A-Za-z0-9]\\)" 2 font-lock-keyword-face)))
560 "*Rules for highlighting shell scripts. See `sh-feature'.")
563 ;; mode-command and utility functions
567 "Major mode for editing shell scripts.
568 This mode works for many shells, since they all have roughly the same syntax,
569 as far as commands, arguments, variables, pipes, comments etc. are concerned.
570 Unless the file's magic number indicates the shell, your usual shell is
571 assumed. Since filenames rarely give a clue, they are not further analyzed.
573 This mode adapts to the variations between shells (see `sh-set-shell') by
574 means of an inheritance based feature lookup (see `sh-feature'). This
575 mechanism applies to all variables (including skeletons) that pertain to
576 shell-specific features.
578 The default style of this mode is that of Rosenblatt's Korn shell book.
579 The syntax of the statements varies with the shell being used. The
580 following commands are available, based on the current shell's syntax:
582 \\[sh-case] case statement
584 \\[sh-function] function definition
585 \\[sh-if] if statement
586 \\[sh-indexed-loop] indexed loop from 1 to n
587 \\[sh-while-getopts] while getopts loop
588 \\[sh-repeat] repeat loop
589 \\[sh-select] select loop
590 \\[sh-until] until loop
591 \\[sh-while] while loop
593 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
594 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
595 \\[sh-end-of-command] Go to end of successive commands.
596 \\[sh-beginning-of-command] Go to beginning of successive commands.
597 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
598 \\[sh-execute-region] Have optional header and region be executed in a subshell.
600 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
602 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
604 If you generally program a shell different from your login shell you can
605 set `sh-shell-path' accordingly. If your shell's file name doesn't correctly
606 indicate what shell it is use `sh-alias-alist' to translate.
608 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
609 with your script for an edit-interpret-debug cycle."
611 (kill-all-local-variables)
612 (use-local-map sh-mode-map)
613 (make-local-variable 'indent-line-function)
614 (make-local-variable 'indent-region-function)
615 (make-local-variable 'paragraph-start)
616 (make-local-variable 'paragraph-separate)
617 (make-local-variable 'comment-start)
618 (make-local-variable 'comment-start-skip)
619 (make-local-variable 'require-final-newline)
620 (make-local-variable 'sh-header-marker)
621 (make-local-variable 'sh-shell-path)
622 (make-local-variable 'sh-shell)
623 (make-local-variable 'pair-alist)
624 (make-local-variable 'pair-filter)
625 (make-local-variable 'font-lock-keywords)
626 (make-local-variable 'comint-dynamic-complete-functions)
627 (make-local-variable 'comint-prompt-regexp)
628 (make-local-variable 'font-lock-keywords-case-fold-search)
629 (make-local-variable 'skeleton-filter)
630 (make-local-variable 'process-environment)
631 (setq major-mode 'sh-mode
632 mode-name "Shell-script"
633 indent-line-function 'sh-indent-line
634 ;; not very clever, but enables wrapping skeletons around regions
635 indent-region-function (lambda (b e)
636 (indent-rigidly b e sh-indentation))
637 paragraph-start "^$\\|^
\f"
638 paragraph-separate paragraph-start
640 font-lock-keywords-case-fold-search nil
641 comint-dynamic-complete-functions sh-dynamic-complete-functions
642 ;; we can't look if previous line ended with `\'
643 comint-prompt-regexp "^[ \t]*"
644 pair-alist '((?` _ ?`))
645 pair-filter 'sh-quoted-p
646 skeleton-further-elements '((< '(- (min sh-indentation
648 skeleton-filter 'sh-feature)
649 ;; parse or insert magic number for exec() and set all variables depending
650 ;; on the shell thus determined
651 (goto-char (point-min))
653 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
654 (buffer-substring (match-beginning 1) (match-end 1))
656 (run-hooks 'sh-mode-hook))
658 (defalias 'shell-script-mode 'sh-mode)
662 (defun sh-set-shell (shell)
663 "Set this buffer's shell to SHELL (a string).
664 Makes this script executable via `executable-set-magic'.
665 Calls the value of `sh-set-shell-hook' if set."
666 (interactive (list (completing-read "Name or path of shell: " sh-shells)))
667 (if (eq this-command 'sh-set-shell)
669 (setq this-command 'executable-set-magic))
670 (setq sh-shell (intern (file-name-nondirectory shell))
671 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
673 sh-shell-path (executable-set-magic shell (sh-feature sh-shell-arg))
674 local-abbrev-table (sh-feature sh-abbrevs)
675 require-final-newline (sh-feature sh-require-final-newline)
678 sh-font-lock-keywords
681 (cons (concat (sh-feature sh-comment-prefix)
683 '(2 font-lock-comment-face t))
684 ;; first grouping should include all keywords such
685 ;; as while, do ... that may be followed by a
686 ;; command, but neither t nor keep will fontify it
687 (cons (concat "\\(^\\|[|&;()]\\)[ \t]*\\(\\(\\("
694 (sh-feature sh-builtins)
696 "\\)\\)\\($\\|[ \t|&;()]\\)")
697 '(2 font-lock-keyword-face 'keep))
698 (cons (sh-feature sh-assignment-regexp)
699 '(1 font-lock-function-name-face)))))
700 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
701 mode-line-process (format "[%s]" sh-shell)
702 process-environment (default-value 'process-environment)
703 shell (sh-feature sh-variables))
704 (set-syntax-table (sh-feature sh-mode-syntax-table))
706 (while (search-forward "=" nil t)
709 (sh-remember-variable (car shell))
710 (setq shell (cdr shell)))
711 (and (boundp 'font-lock-mode)
713 (font-lock-mode (font-lock-mode 0)))
714 (run-hooks 'sh-set-shell-hook))
718 (defun sh-feature (list &optional function)
719 "Index ALIST by the current shell.
720 If ALIST isn't a list where every element is a cons, it is returned as is.
721 Else indexing follows an inheritance logic which works in two ways:
723 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
724 the alist contains no value for the current shell.
726 - If the value thus looked up is a list starting with `eval' its `cdr' is
727 first evaluated. If that is also a list and the first argument is a
728 symbol in ALIST it is not evaluated, but rather recursively looked up in
729 ALIST to allow the function called to define the value for one shell to be
730 derived from another shell. While calling the function, is the car of the
731 alist element is the current shell.
732 The value thus determined is physically replaced into the alist.
734 Optional FUNCTION is applied to the determined value and the result is cached
738 (while (and l (consp (car l)))
742 (cdr (assoc (setq function (cons sh-shell function)) list)))
743 (let ((sh-shell sh-shell)
746 (not (setq elt (assq sh-shell list))))
747 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
748 (if (and (consp (setq val (cdr elt)))
749 (eq (car val) 'eval))
752 (eval (if (consp (setq val (cdr val)))
753 (let ((sh-shell (car (cdr val)))
755 (if (assq sh-shell list)
764 (setq sh-shell (car function)
765 val (funcall (cdr function) val))))))
770 (defun sh-abbrevs (ancestor &rest list)
771 "Iff it isn't, define the current shell as abbrev table and fill that.
772 Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
773 table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
774 according to the remaining arguments NAMEi EXPANSIONi ...
775 EXPANSION may be either a string or a skeleton command."
776 (or (if (boundp sh-shell)
777 (symbol-value sh-shell))
780 (nconc list ancestor))
781 (define-abbrev-table sh-shell ())
782 (if (vectorp ancestor)
783 (mapatoms (lambda (atom)
785 (define-abbrev (symbol-value sh-shell)
788 (symbol-function atom))))
791 (define-abbrev (symbol-value sh-shell)
793 (if (stringp (car (cdr list)))
796 (if (symbolp (car (cdr list)))
798 (setq list (cdr (cdr list)))))
799 (symbol-value sh-shell)))
802 (defun sh-mode-syntax-table (table &rest list)
803 "Copy TABLE and set syntax for succesive CHARs according to strings S."
804 (setq table (copy-syntax-table table))
806 (modify-syntax-entry (car list) (car (cdr list)) table)
807 (setq list (cdr (cdr list))))
811 (defun sh-append (ancestor &rest list)
812 "Return list composed of first argument (a list) physically appended to rest."
813 (nconc list ancestor))
816 (defun sh-modify (skeleton &rest list)
817 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
818 (setq skeleton (copy-sequence skeleton))
820 (setcar (or (nthcdr (car list) skeleton)
821 (error "Index %d out of bounds" (car list)))
823 (setq list (nthcdr 2 list)))
827 (defun sh-indent-line ()
828 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
829 Lines containing only comments are considered empty."
831 (let ((previous (save-excursion
834 (back-to-indentation)
836 (eq (following-char) ?#))))
840 (indent-to (if (eq this-command 'newline-and-indent)
842 (if (< (current-column)
843 (setq current (progn (back-to-indentation)
845 (if (eolp) previous 0)
846 (delete-region (point)
847 (progn (beginning-of-line) (point)))
849 (max previous (* (1+ (/ current sh-indentation))
851 (* (1+ (/ current sh-indentation)) sh-indentation))))))
852 (if (< (current-column) (current-indentation))
853 (skip-chars-forward " \t"))))
856 (defun sh-execute-region (start end &optional flag)
857 "Pass optional header and region to a subshell for noninteractive execution.
858 The working directory is that of the buffer, and only environment variables
859 are already set which is why you can mark a header within the script.
861 With a positive prefix ARG, instead of sending region, define header from
862 beginning of buffer to point. With a negative prefix ARG, instead of sending
863 region, clear header."
866 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
870 (let (buffer-undo-list)
871 (goto-char sh-header-marker)
872 (append-to-buffer (current-buffer) start end)
873 (shell-command-on-region (point-min)
874 (setq end (+ sh-header-marker
877 (delete-region sh-header-marker end)))
878 (shell-command-on-region start end (concat sh-shell-path " -")))))
881 (defun sh-remember-variable (var)
882 "Make VARIABLE available for future completing reads in this buffer."
883 (or (< (length var) sh-remember-variable-min)
885 (setq process-environment (cons (concat var "=0") process-environment)))
890 (defun sh-quoted-p ()
891 "Is point preceded by an odd number of backslashes?"
892 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
894 ;; statement syntax-commands for various shells
896 ;; You are welcome to add the syntax or even completely new statements as
897 ;; appropriate for your favorite shell.
899 (define-skeleton sh-case
900 "Insert a case/switch statement. See `sh-feature'."
902 "switch( " str " )" \n
903 > "case " (read-string "pattern: ") ?: \n
906 ( "other pattern, %s: "
916 "switch( " str " ) {" \n
917 > "case " (read-string "pattern: ") \n
919 ( "other pattern, %s: "
928 > (read-string "pattern: ") ?\) \n
931 ( "other pattern, %s: "
942 (define-skeleton sh-for
943 "Insert a for loop. See `sh-feature'."
944 (csh eval sh-modify sh
949 (es eval sh-modify rc
951 (rc eval sh-modify sh
955 (sh "Index variable: "
956 "for " str " in " _ "; do" \n
957 > _ | ?$ & (sh-remember-variable str) \n
962 (define-skeleton sh-indexed-loop
963 "Insert an indexed loop from 1 to n. See `sh-feature'."
964 (bash eval identity posix)
965 (csh "Index variable: "
967 "while( $" str " <= " (read-string "upper limit: ") " )" \n
971 (es eval sh-modify rc
973 (ksh88 "Index variable: "
974 "integer " str "=0" \n
975 "while (( ( " str " += 1 ) <= "
976 (read-string "upper limit: ")
978 > _ ?$ (sh-remember-variable str) \n
980 (posix "Index variable: "
982 "while [ $" str " -le "
983 (read-string "upper limit: ")
986 str ?= (sh-add (sh-remember-variable str) 1) \n
988 (rc "Index variable: "
989 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
990 (read-string "upper limit: ")
991 "; i++ ) print i }'}) {" \n
992 > _ ?$ (sh-remember-variable str) \n
994 (sh "Index variable: "
995 "for " str " in `awk 'BEGIN { for( i=1; i<="
996 (read-string "upper limit: ")
997 "; i++ ) print i }'`; do" \n
998 > _ ?$ (sh-remember-variable str) \n
1002 (defun sh-add (var delta)
1003 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1005 (list (completing-read "Variable: "
1006 (mapcar (lambda (var)
1007 (substring var 0 (string-match "=" var)))
1008 process-environment))
1009 (prefix-numeric-value current-prefix-arg)))
1010 (insert (sh-feature '((bash . "$[ ")
1016 (sh-remember-variable var)
1017 (if (< delta 0) " - " " + ")
1018 (number-to-string (abs delta))
1019 (sh-feature '((bash . " ]")
1028 (define-skeleton sh-function
1029 "Insert a function definition. See `sh-feature'."
1030 (bash eval sh-modify ksh88
1033 "function " str " {" \n
1036 (rc eval sh-modify ksh88
1045 (define-skeleton sh-if
1046 "Insert an if statement. See `sh-feature'."
1048 "if( " str " ) then" \n
1050 ( "other condition, %s: "
1051 < "else if( " str " ) then" \n
1058 "if { " str " } {" \n
1060 ( "other condition, %s: "
1061 < "} { " str " } {" \n
1067 (rc eval sh-modify csh
1069 8 '( "other condition, %s: "
1070 < "} else if( " str " ) {" \n
1075 "if [ " str " ]; then" \n
1077 ( "other condition, %s: "
1078 < "elif [ " str " ]; then" \n
1087 (define-skeleton sh-repeat
1088 "Insert a repeat loop definition. See `sh-feature'."
1094 "repeat " str "; do"\n
1097 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1101 (define-skeleton sh-select
1102 "Insert a select statement. See `sh-feature'."
1103 (ksh88 "Index variable: "
1104 "select " str " in " _ "; do" \n
1107 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1111 (define-skeleton sh-tmp-file
1112 "Insert code to setup temporary file handling. See `sh-feature'."
1113 (bash eval identity ksh88)
1114 (csh (file-name-nondirectory (buffer-file-name))
1115 "set tmp = /tmp/" str ".$$" \n
1117 (and (goto-char (point-max))
1121 "rm $tmp* >&/dev/null" >)
1122 (es (file-name-nondirectory (buffer-file-name))
1123 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1125 > "rm $tmp^* >[2]/dev/null" \n
1131 (ksh88 eval sh-modify sh
1133 (rc (file-name-nondirectory (buffer-file-name))
1134 "tmp = /tmp/" str ".$pid" \n
1135 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1136 (sh (file-name-nondirectory (buffer-file-name))
1137 "TMP=/tmp/" str ".$$" \n
1138 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1142 (define-skeleton sh-until
1143 "Insert an until loop. See `sh-feature'."
1145 "until [ " str " ]; do" \n
1148 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1152 (define-skeleton sh-while
1153 "Insert a while loop. See `sh-feature'."
1154 (csh eval sh-modify sh
1158 (es eval sh-modify rc
1161 (rc eval sh-modify csh
1165 "while [ " str " ]; do" \n
1171 (define-skeleton sh-while-getopts
1172 "Insert a while getopts loop. See `sh-feature'.
1173 Prompts for an options string which consists of letters for each recognized
1174 option followed by a colon `:' if the option accepts an argument."
1175 (bash eval sh-modify sh
1177 (ksh88 eval sh-modify sh
1181 (posix eval sh-modify sh
1182 18 "$(basename $0)")
1184 "while getopts :" str " OPT; do" \n
1187 '(setq v1 (append (vconcat str) nil))
1188 ( (prog1 (if v1 (char-to-string (car v1)))
1189 (if (eq (nth 1 v1) ?:)
1190 (setq v1 (nthcdr 2 v1)
1194 < str "|+" str ?\) \n
1198 > "echo" " \"usage: " "`basename $0`"
1199 "[ +-" '(setq v1 (point)) str
1201 (while (search-backward ":" v1 t)
1202 (replace-match " arg][ +-" t t)))
1203 (if (eq (preceding-char) ?-) -5)
1208 "shift " (sh-add "OPTIND" -1)))
1209 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1213 (defun sh-assignment (arg)
1214 "Remember preceding identifier for future completion and do self-insert."
1216 (self-insert-command arg)
1218 (sh-remember-variable
1220 (if (re-search-forward (sh-feature sh-assignment-regexp)
1222 (beginning-of-line 1))
1224 (buffer-substring (match-beginning 1) (match-end 1)))))))
1228 (defun sh-maybe-here-document (arg)
1229 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1230 The document is bounded by `sh-here-document-word'."
1232 (self-insert-command (prefix-numeric-value arg))
1234 (not (eq (char-after (- (point) 2)) last-command-char))
1239 (insert sh-here-document-word)
1240 (or (eolp) (looking-at "[ \t]") (insert ? ))
1246 (save-excursion (insert ?\n sh-here-document-word)))))
1249 ;; various other commands
1251 (autoload 'comint-dynamic-complete "comint"
1252 "Dynamically perform completion at point." t)
1254 (autoload 'shell-dynamic-complete-command "shell"
1255 "Dynamically complete the command at point." t)
1257 (autoload 'comint-dynamic-complete-filename "comint"
1258 "Dynamically complete the filename at point." t)
1260 (autoload 'shell-dynamic-complete-environment-variable "shell"
1261 "Dynamically complete the environment variable at point." t)
1265 (defun sh-newline-and-indent (&optional arg)
1266 "Strip unquoted whitespace, insert newline, and indent like current line.
1267 Unquoted whitespace is stripped from the current line's end, unless a
1268 prefix ARG is given."
1270 (let ((previous (current-indentation)))
1278 (indent-to previous)))
1282 (defun sh-beginning-of-command ()
1283 "Move point to successive beginnings of commands."
1285 (if (re-search-backward sh-beginning-of-command nil t)
1286 (goto-char (match-beginning 2))))
1289 (defun sh-end-of-command ()
1290 "Move point to successive ends of commands."
1292 (if (re-search-forward sh-end-of-command nil t)
1293 (goto-char (match-end 1))))
1295 ;; sh-script.el ends here