1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 1994, 1995, 1996 by Free Software Foundation, Inc.
5 ;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
8 ;; Keywords: languages, unix
10 ;; This file is part of GNU Emacs.
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)
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.
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.
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.
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.
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
50 (defvar sh-ancestor-alist
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:
72 jcsh C Shell with Job Control
74 itcsh ? Toronto C Shell
79 jsh Bourne Shell with Job Control
80 bash GNU Bourne Again Shell
83 dtksh CDE Desktop Korn Shell
84 pdksh Public Domain Korn Shell
85 wksh Window Korn Shell
87 oash SCO OA (curses) Shell
88 posix IEEE 1003.2 Shell Standard
92 (defvar sh-alias-alist
93 (nconc (if (eq system-type 'linux)
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.")
104 (defvar sh-shell-file (or (getenv "SHELL") "/bin/sh")
105 "*The executable file name for the shell being programmed.")
111 (ksh88 eval progn nil (if (file-exists-p "/etc/suid_profile") nil "-p"))
116 "*Single argument string for the magic number. See `sh-feature'.")
118 (defvar sh-shell-variables nil
119 "Alist of shell variable names that should be included in completion.
120 These are used for completion in addition to all the variables named
121 in `process-environment'. Each element looks like (VAR . VAR), where
122 the car and cdr are the same symbol.")
124 (defvar sh-shell-variables-initialized nil
125 "Non-nil if `sh-shell-variables' is initialized.")
127 (defun sh-canonicalize-shell (shell)
128 "Convert a shell name SHELL to the one we should handle it as."
130 (setq shell (intern shell)))
131 (or (cdr (assq shell sh-alias-alist))
134 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
135 "The shell being programmed. This is set by \\[sh-set-shell].")
137 ;;; I turned off this feature because it doesn't permit typing commands
138 ;;; in the usual way without help.
139 ;;;(defvar sh-abbrevs
140 ;;; '((csh eval sh-abbrevs shell
141 ;;; "switch" 'sh-case
142 ;;; "getopts" 'sh-while-getopts)
144 ;;; (es eval sh-abbrevs shell
145 ;;; "function" 'sh-function)
147 ;;; (ksh88 eval sh-abbrevs sh
148 ;;; "select" 'sh-select)
150 ;;; (rc eval sh-abbrevs shell
152 ;;; "function" 'sh-function)
154 ;;; (sh eval sh-abbrevs shell
156 ;;; "function" 'sh-function
157 ;;; "until" 'sh-until
158 ;;; "getopts" 'sh-while-getopts)
160 ;;; ;; The next entry is only used for defining the others
161 ;;; (shell "for" sh-for
162 ;;; "loop" sh-indexed-loop
164 ;;; "tmpfile" sh-tmp-file
165 ;;; "while" sh-while)
167 ;;; (zsh eval sh-abbrevs ksh88
168 ;;; "repeat" 'sh-repeat))
169 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
170 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
171 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
175 (defvar sh-mode-syntax-table
176 '((csh eval identity sh)
177 (sh eval sh-mode-syntax-table ()
178 ;; #'s meanings depend on context which can't be expressed here
192 (rc eval sh-mode-syntax-table sh
195 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
200 (let ((map (make-sparse-keymap))
201 (menu-map (make-sparse-keymap "Insert")))
202 (define-key map "\C-c(" 'sh-function)
203 (define-key map "\C-c\C-w" 'sh-while)
204 (define-key map "\C-c\C-u" 'sh-until)
205 (define-key map "\C-c\C-t" 'sh-tmp-file)
206 (define-key map "\C-c\C-s" 'sh-select)
207 (define-key map "\C-c\C-r" 'sh-repeat)
208 (define-key map "\C-c\C-o" 'sh-while-getopts)
209 (define-key map "\C-c\C-l" 'sh-indexed-loop)
210 (define-key map "\C-c\C-i" 'sh-if)
211 (define-key map "\C-c\C-f" 'sh-for)
212 (define-key map "\C-c\C-c" 'sh-case)
214 (define-key map "=" 'sh-assignment)
215 (define-key map "\C-c+" 'sh-add)
216 (define-key map "\C-\M-x" 'sh-execute-region)
217 (define-key map "\C-c\C-x" 'executable-interpret)
218 (define-key map "<" 'sh-maybe-here-document)
219 (define-key map "(" 'skeleton-pair-insert-maybe)
220 (define-key map "{" 'skeleton-pair-insert-maybe)
221 (define-key map "[" 'skeleton-pair-insert-maybe)
222 (define-key map "'" 'skeleton-pair-insert-maybe)
223 (define-key map "`" 'skeleton-pair-insert-maybe)
224 (define-key map "\"" 'skeleton-pair-insert-maybe)
226 (define-key map "\t" 'sh-indent-line)
227 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
228 map (current-global-map))
229 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
230 map (current-global-map))
231 (substitute-key-definition 'delete-backward-char
232 'backward-delete-char-untabify
233 map (current-global-map))
234 (define-key map "\C-c:" 'sh-set-shell)
235 (substitute-key-definition 'beginning-of-defun
236 'sh-beginning-of-compound-command
237 map (current-global-map))
238 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
239 map (current-global-map))
240 (substitute-key-definition 'forward-sentence 'sh-end-of-command
241 map (current-global-map))
242 (define-key map [menu-bar insert] (cons "Insert" menu-map))
243 (define-key menu-map [sh-while] '("While Loop" . sh-while))
244 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
245 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
246 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
247 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
248 (define-key menu-map [sh-while-getopts]
249 '("Options Loop" . sh-while-getopts))
250 (define-key menu-map [sh-indexed-loop]
251 '("Indexed Loop" . sh-indexed-loop))
252 (define-key menu-map [sh-if] '("If Statement" . sh-if))
253 (define-key menu-map [sh-for] '("For Loop" . sh-for))
254 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
256 "Keymap used in Shell-Script mode.")
260 (defvar sh-dynamic-complete-functions
261 '(shell-dynamic-complete-environment-variable
262 shell-dynamic-complete-command
263 comint-dynamic-complete-filename)
264 "*Functions for doing TAB dynamic completion.")
267 (defvar sh-require-final-newline
270 (rc eval . require-final-newline)
271 (sh eval . require-final-newline))
272 "*Value of `require-final-newline' in Shell-Script mode buffers.
276 (defvar sh-comment-prefix
277 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
278 (rc eval identity csh)
279 (sh . "\\(^\\|[ \t|&;()]\\)"))
280 "*Regexp matching what may come before a comment `#'.
281 This must contain one \\(grouping\\) since it is the basis for fontifying
282 comments as well as for `comment-start-skip'.
286 (defvar sh-assignment-regexp
287 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
288 ;; actually spaces are only supported in let/(( ... ))
289 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
290 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
291 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
292 "*Regexp for the variable name and what may follow in an assignment.
293 First grouping matches the variable name. This is upto and including the `='
294 sign. See `sh-feature'.")
297 (defvar sh-indentation 4
298 "The width for further indentation in Shell-Script mode.")
301 (defvar sh-remember-variable-min 3
302 "*Don't remember variables less than this length for completing reads.")
305 (defvar sh-header-marker nil
306 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
307 That command is also used for setting this variable.")
310 (defvar sh-beginning-of-command
311 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
312 "*Regexp to determine the beginning of a shell command.
313 The actual command starts at the beginning of the second \\(grouping\\).")
316 (defvar sh-end-of-command
317 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
318 "*Regexp to determine the end of a shell command.
319 The actual command ends at the end of the first \\(grouping\\).")
323 (defvar sh-here-document-word "EOF"
324 "Word to delimit here documents.")
329 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
333 '((bash eval sh-append posix
334 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
335 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
336 "suspend" "typeset" "unalias")
338 ;; The next entry is only used for defining the others
339 (bourne eval sh-append shell
340 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
343 (csh eval sh-append shell
344 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
345 "setenv" "source" "time" "unalias" "unhash")
347 (dtksh eval identity wksh)
349 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
350 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
352 (jsh eval sh-append sh
353 "bg" "fg" "jobs" "kill" "stop" "suspend")
355 (jcsh eval sh-append csh
356 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
358 (ksh88 eval sh-append bourne
359 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
360 "typeset" "unalias" "whence")
362 (oash eval sh-append sh
363 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
364 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
365 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
366 "wmtitle" "wrefresh")
368 (pdksh eval sh-append ksh88
371 (posix eval sh-append sh
374 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
377 (sh eval sh-append bourne
378 "hash" "test" "type")
380 ;; The next entry is only used for defining the others
381 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
383 (wksh eval sh-append ksh88
386 (zsh eval sh-append ksh88
387 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
388 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
389 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
390 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
391 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
393 "*List of all shell builtins for completing read and fontification.
394 Note that on some systems not all builtins are available or some are
395 implemented as aliases. See `sh-feature'.")
399 (defvar sh-leading-keywords
402 (es "true" "unwind-protect" "whatis")
406 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
407 "*List of keywords that may be immediately followed by a builtin or keyword.
408 Given some confusion between keywords and builtins depending on shell and
409 system, the distinction here has been based on whether they influence the
410 flow of control or syntax. See `sh-feature'.")
413 (defvar sh-other-keywords
414 '((bash eval sh-append bourne
417 ;; The next entry is only used for defining the others
418 (bourne eval sh-append shell
419 "done" "esac" "fi" "for" "function" "in" "return")
421 (csh eval sh-append shell
422 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
423 "if" "logout" "onintr" "repeat" "switch" "then" "while")
425 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
426 "return" "throw" "while")
428 (ksh88 eval sh-append bourne
431 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
434 ;; The next entry is only used for defining the others
435 (shell "break" "case" "continue" "exec" "exit")
437 (zsh eval sh-append bash
439 "*List of keywords not in `sh-leading-keywords'.
445 '((bash eval sh-append sh
446 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
447 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
448 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
449 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
450 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
451 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
452 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
453 "SECONDS" "SHLVL" "TMOUT" "UID")
455 (csh eval sh-append shell
456 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
457 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
458 "shell" "status" "time" "verbose")
460 (es eval sh-append shell
461 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
462 "pid" "prompt" "signals")
464 (jcsh eval sh-append csh
467 (ksh88 eval sh-append sh
468 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
469 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
472 (oash eval sh-append sh
473 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
475 (rc eval sh-append shell
476 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
479 (sh eval sh-append shell
480 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
482 ;; The next entry is only used for defining the others
483 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
484 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
485 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
486 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
488 (tcsh eval sh-append csh
489 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
490 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
491 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
492 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
493 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
494 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
495 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
496 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
499 (zsh eval sh-append ksh88
500 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
501 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
502 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
503 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
504 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
505 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
506 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
507 "List of all shell variables available for completing read.
512 (defvar sh-font-lock-keywords
513 '((csh eval sh-append shell
514 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
515 font-lock-variable-name-face))
517 (es eval sh-append executable-font-lock-keywords
518 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
519 font-lock-variable-name-face))
521 (rc eval identity es)
523 (sh eval sh-append shell
524 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
525 font-lock-variable-name-face))
527 ;; The next entry is only used for defining the others
528 (shell eval sh-append executable-font-lock-keywords
529 '("\\\\." 0 font-lock-string-face)
530 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
531 font-lock-variable-name-face)))
532 "*Rules for highlighting shell scripts. See `sh-feature'.")
534 (defvar sh-font-lock-keywords-1
536 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
538 (defvar sh-font-lock-keywords-2 ()
539 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
541 (defvar sh-font-lock-keywords-only t
542 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
543 Default value is `t' because Emacs' syntax is not expressive enough to
544 detect that $# does not start a comment. Thus comments are fontified by
545 regexp which means that a single apostrophe in a comment turns everything
546 upto the next one or end of buffer into a string.")
548 ;; mode-command and utility functions
551 (put 'sh-mode 'mode-class 'special)
555 "Major mode for editing shell scripts.
556 This mode works for many shells, since they all have roughly the same syntax,
557 as far as commands, arguments, variables, pipes, comments etc. are concerned.
558 Unless the file's magic number indicates the shell, your usual shell is
559 assumed. Since filenames rarely give a clue, they are not further analyzed.
561 This mode adapts to the variations between shells (see `sh-set-shell') by
562 means of an inheritance based feature lookup (see `sh-feature'). This
563 mechanism applies to all variables (including skeletons) that pertain to
564 shell-specific features.
566 The default style of this mode is that of Rosenblatt's Korn shell book.
567 The syntax of the statements varies with the shell being used. The
568 following commands are available, based on the current shell's syntax:
570 \\[sh-case] case statement
572 \\[sh-function] function definition
573 \\[sh-if] if statement
574 \\[sh-indexed-loop] indexed loop from 1 to n
575 \\[sh-while-getopts] while getopts loop
576 \\[sh-repeat] repeat loop
577 \\[sh-select] select loop
578 \\[sh-until] until loop
579 \\[sh-while] while loop
581 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
582 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
583 \\[sh-end-of-command] Go to end of successive commands.
584 \\[sh-beginning-of-command] Go to beginning of successive commands.
585 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
586 \\[sh-execute-region] Have optional header and region be executed in a subshell.
588 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
590 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
592 If you generally program a shell different from your login shell you can
593 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
594 indicate what shell it is use `sh-alias-alist' to translate.
596 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
597 with your script for an edit-interpret-debug cycle."
599 (kill-all-local-variables)
600 (use-local-map sh-mode-map)
601 (make-local-variable 'indent-line-function)
602 (make-local-variable 'indent-region-function)
603 (make-local-variable 'skeleton-end-hook)
604 (make-local-variable 'paragraph-start)
605 (make-local-variable 'paragraph-separate)
606 (make-local-variable 'comment-start)
607 (make-local-variable 'comment-start-skip)
608 (make-local-variable 'require-final-newline)
609 (make-local-variable 'sh-header-marker)
610 (make-local-variable 'sh-shell-file)
611 (make-local-variable 'sh-shell)
612 (make-local-variable 'skeleton-pair-alist)
613 (make-local-variable 'skeleton-pair-filter)
614 (make-local-variable 'comint-dynamic-complete-functions)
615 (make-local-variable 'comint-prompt-regexp)
616 (make-local-variable 'font-lock-keywords)
617 (make-local-variable 'font-lock-defaults)
618 (make-local-variable 'skeleton-filter)
619 (make-local-variable 'skeleton-newline-indent-rigidly)
620 (make-local-variable 'sh-shell-variables)
621 (make-local-variable 'sh-shell-variables-initialized)
622 (setq major-mode 'sh-mode
623 mode-name "Shell-script"
624 indent-line-function 'sh-indent-line
625 ;; not very clever, but enables wrapping skeletons around regions
626 indent-region-function (lambda (b e)
629 (skip-syntax-backward "-")
632 (skip-syntax-backward "-")
633 (indent-rigidly b (point) sh-indentation)))
634 skeleton-end-hook (lambda ()
635 (or (eolp) (newline) (indent-relative)))
636 paragraph-start (concat page-delimiter "\\|$")
637 paragraph-separate paragraph-start
639 comint-dynamic-complete-functions sh-dynamic-complete-functions
640 ;; we can't look if previous line ended with `\'
641 comint-prompt-regexp "^[ \t]*"
643 `((sh-font-lock-keywords
644 sh-font-lock-keywords-1
645 sh-font-lock-keywords-2)
646 ,sh-font-lock-keywords-only
648 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
649 skeleton-pair-alist '((?` _ ?`))
650 skeleton-pair-filter 'sh-quoted-p
651 skeleton-further-elements '((< '(- (min sh-indentation
653 skeleton-filter 'sh-feature
654 skeleton-newline-indent-rigidly t)
656 ;; parse or insert magic number for exec() and set all variables depending
657 ;; on the shell thus determined
658 (goto-char (point-min))
660 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
663 (run-hooks 'sh-mode-hook))
665 (defalias 'shell-script-mode 'sh-mode)
668 (defun sh-font-lock-keywords (&optional keywords)
669 "Function to get simple fontification based on `sh-font-lock-keywords'.
670 This adds rules for comments and assignments."
671 (sh-feature sh-font-lock-keywords
673 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
674 2 font-lock-comment-face t)
675 (,(sh-feature sh-assignment-regexp)
676 1 font-lock-variable-name-face)
680 (defun sh-font-lock-keywords-1 (&optional builtins)
681 "Function to get better fontification including keywords."
682 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
684 (sh-feature sh-leading-keywords)
688 (append (sh-feature sh-leading-keywords)
689 (sh-feature sh-other-keywords))
692 (sh-font-lock-keywords
694 `((,(concat keywords "[ \t]+\\)?\\("
695 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
697 (2 font-lock-keyword-face nil t)
698 (6 font-lock-function-name-face))
699 ,@(sh-feature sh-font-lock-keywords-2)))
700 (,(concat keywords "\\)\\>")
701 2 font-lock-keyword-face)
702 ,@(sh-feature sh-font-lock-keywords-1)))))
704 (defun sh-font-lock-keywords-2 ()
705 "Function to get better fontification including keywords and builtins."
706 (sh-font-lock-keywords-1 t))
709 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
710 "Set this buffer's shell to SHELL (a string).
711 Makes this script executable via `executable-set-magic'.
712 Calls the value of `sh-set-shell-hook' if set."
713 (interactive (list (completing-read "Name or path of shell: "
714 interpreter-mode-alist
715 (lambda (x) (eq (cdr x) 'sh-mode)))
716 (eq executable-query 'function)
718 (setq sh-shell (intern (file-name-nondirectory shell))
719 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
721 (setq sh-shell-file (executable-set-magic shell (sh-feature sh-shell-arg)))
722 (setq require-final-newline (sh-feature sh-require-final-newline)
723 ;;; local-abbrev-table (sh-feature sh-abbrevs)
724 font-lock-keywords nil ; force resetting
725 font-lock-syntax-table nil
726 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
727 mode-line-process (format "[%s]" sh-shell)
728 sh-shell-variables nil
729 sh-shell-variables-initialized nil
730 shell (sh-feature sh-variables))
731 (set-syntax-table (sh-feature sh-mode-syntax-table))
733 (sh-remember-variable (car shell))
734 (setq shell (cdr shell)))
735 (and (boundp 'font-lock-mode)
737 (font-lock-mode (font-lock-mode 0)))
738 (run-hooks 'sh-set-shell-hook))
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:
747 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
748 the alist contains no value for the current shell.
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.
758 Optional FUNCTION is applied to the determined value and the result is cached
762 (while (and l (consp (car l)))
766 (cdr (assoc (setq function (cons sh-shell function)) list)))
767 (let ((sh-shell 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))
776 (eval (if (consp (setq val (cdr val)))
777 (let ((sh-shell (car (cdr val)))
779 (if (assq sh-shell list)
788 (setq sh-shell (car function)
789 val (funcall (cdr function) val))))))
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))
804 ;;; (if (listp ancestor)
805 ;;; (nconc list ancestor))
806 ;;; (define-abbrev-table sh-shell ())
807 ;;; (if (vectorp ancestor)
808 ;;; (mapatoms (lambda (atom)
810 ;;; (define-abbrev (symbol-value sh-shell)
811 ;;; (symbol-name atom)
812 ;;; (symbol-value atom)
813 ;;; (symbol-function atom))))
816 ;;; (define-abbrev (symbol-value sh-shell)
818 ;;; (if (stringp (car (cdr list)))
821 ;;; (if (symbolp (car (cdr list)))
822 ;;; (car (cdr list))))
823 ;;; (setq list (cdr (cdr list)))))
824 ;;; (symbol-value sh-shell)))
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))
831 (modify-syntax-entry (car list) (car (cdr list)) table)
832 (setq list (cdr (cdr list))))
836 (defun sh-append (ancestor &rest list)
837 "Return list composed of first argument (a list) physically appended to rest."
838 (nconc list ancestor))
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))
845 (setcar (or (nthcdr (car list) skeleton)
846 (error "Index %d out of bounds" (car list)))
848 (setq list (nthcdr 2 list)))
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."
856 (let ((previous (save-excursion
857 (while (and (not (bobp))
860 (back-to-indentation)
862 (eq (following-char) ?#)))))
866 (indent-to (if (eq this-command 'newline-and-indent)
868 (if (< (current-column)
869 (setq current (progn (back-to-indentation)
871 (if (eolp) previous 0)
872 (delete-region (point)
873 (progn (beginning-of-line) (point)))
875 (max previous (* (1+ (/ current sh-indentation))
877 (* (1+ (/ current sh-indentation)) sh-indentation))))))
878 (if (< (current-column) (current-indentation))
879 (skip-chars-forward " \t"))))
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.
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."
892 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
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
903 (delete-region sh-header-marker end)))
904 (shell-command-on-region start end (concat sh-shell-file " -")))))
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)
911 (assoc var sh-shell-variables)
912 (setq sh-shell-variables (cons (cons var var) sh-shell-variables)))
917 (defun sh-quoted-p ()
918 "Is point preceded by an odd number of backslashes?"
919 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
921 ;; statement syntax-commands for various shells
923 ;; You are welcome to add the syntax or even completely new statements as
924 ;; appropriate for your favorite shell.
926 (define-skeleton sh-case
927 "Insert a case/switch statement. See `sh-feature'."
929 "switch( " str " )" \n
930 > "case " (read-string "pattern: ") ?: \n
933 ( "other pattern, %s: "
943 "switch( " str " ) {" \n
944 > "case " (read-string "pattern: ") \n
946 ( "other pattern, %s: "
955 > (read-string "pattern: ") ?\) \n
958 ( "other pattern, %s: "
966 (put 'sh-case 'menu-enable '(sh-feature sh-case))
970 (define-skeleton sh-for
971 "Insert a for loop. See `sh-feature'."
972 (csh eval sh-modify sh
977 (es eval sh-modify rc
979 (rc eval sh-modify sh
983 (sh "Index variable: "
984 "for " str " in " _ "; do" \n
985 > _ | ?$ & (sh-remember-variable str) \n
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: "
995 "while( $" str " <= " (read-string "upper limit: ") " )" \n
999 (es eval sh-modify rc
1001 (ksh88 "Index variable: "
1002 "integer " str "=0" \n
1003 "while (( ( " str " += 1 ) <= "
1004 (read-string "upper limit: ")
1006 > _ ?$ (sh-remember-variable str) \n
1008 (posix "Index variable: "
1010 "while [ $" str " -le "
1011 (read-string "upper limit: ")
1014 str ?= (sh-add (sh-remember-variable str) 1) \n
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
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
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))
1035 (goto-char (point-min))
1036 (setq sh-shell-variables-initialized t)
1037 (while (search-forward "=" nil t)
1039 (message "Scanning buffer `%s' for variable assignments...done"
1042 (defvar sh-add-buffer)
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
1057 (set-buffer sh-add-buffer)
1058 (or sh-shell-variables-initialized
1059 (sh-shell-initialize-variables))
1060 (nconc (mapcar (lambda (var)
1062 (substring var 0 (string-match "=" var))))
1064 process-environment)
1065 sh-shell-variables))))
1067 (try-completion string sh-shell-variables predicate))
1069 (all-completions string sh-shell-variables predicate))
1071 (assoc string sh-shell-variables)))))
1073 (defun sh-add (var delta)
1074 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
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 . "$[ ")
1085 (sh-remember-variable var)
1086 (if (< delta 0) " - " " + ")
1087 (number-to-string (abs delta))
1088 (sh-feature '((bash . " ]")
1097 (define-skeleton sh-function
1098 "Insert a function definition. See `sh-feature'."
1099 (bash eval sh-modify ksh88
1102 "function " str " {" \n
1105 (rc eval sh-modify ksh88
1114 (define-skeleton sh-if
1115 "Insert an if statement. See `sh-feature'."
1117 "if( " str " ) then" \n
1119 ( "other condition, %s: "
1120 < "else if( " str " ) then" \n
1127 "if { " str " } {" \n
1129 ( "other condition, %s: "
1130 < "} { " str " } {" \n
1136 (rc eval sh-modify csh
1138 8 '( "other condition, %s: "
1139 < "} else if( " str " ) {" \n
1144 '(setq input (sh-feature sh-test))
1145 "if " str "; then" \n
1147 ( "other condition, %s: "
1148 < "elif " str "; then" \n
1157 (define-skeleton sh-repeat
1158 "Insert a repeat loop definition. See `sh-feature'."
1164 "repeat " str "; do"\n
1167 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1171 (define-skeleton sh-select
1172 "Insert a select statement. See `sh-feature'."
1173 (ksh88 "Index variable: "
1174 "select " str " in " _ "; do" \n
1177 (put 'sh-select 'menu-enable '(sh-feature sh-select))
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
1187 (and (goto-char (point-max))
1191 "rm $tmp* >&/dev/null" >)
1192 (es (file-name-nondirectory (buffer-file-name))
1193 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1195 > "rm $tmp^* >[2]/dev/null" \n
1201 (ksh88 eval sh-modify sh
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))
1212 (define-skeleton sh-until
1213 "Insert an until loop. See `sh-feature'."
1215 '(setq input (sh-feature sh-test))
1216 "until " str "; do" \n
1219 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1223 (define-skeleton sh-while
1224 "Insert a while loop. See `sh-feature'."
1225 (csh eval sh-modify sh
1229 (es eval sh-modify rc
1232 (rc eval sh-modify csh
1236 '(setq input (sh-feature sh-test))
1237 "while " str "; do" \n
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
1251 > "switch( \"$1\" )" \n
1252 '(setq input '("- x" . 2))
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)))
1261 > "set " v1 & " = $2" | -4 & _ \n
1262 (if v1 "shift") & \n
1272 (ksh88 eval sh-modify sh
1276 (posix eval sh-modify sh
1277 18 "$(basename $0)")
1279 "while getopts :" str " OPT; do" \n
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)
1289 < str "|+" str ?\) \n
1293 > "echo" " \"usage: " "`basename $0`"
1294 "[ +-" '(setq v1 (point)) str
1296 (while (search-backward ":" v1 t)
1297 (replace-match " arg][ +-" t t)))
1298 (if (eq (preceding-char) ?-) -5)
1303 "shift " (sh-add "OPTIND" -1)))
1304 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1308 (defun sh-assignment (arg)
1309 "Remember preceding identifier for future completion and do self-insert."
1311 (self-insert-command arg)
1313 (sh-remember-variable
1315 (if (re-search-forward (sh-feature sh-assignment-regexp)
1317 (beginning-of-line 1))
1319 (match-string 1))))))
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'."
1327 (self-insert-command (prefix-numeric-value arg))
1329 (not (eq (char-after (- (point) 2)) last-command-char))
1334 (insert sh-here-document-word)
1335 (or (eolp) (looking-at "[ \t]") (insert ? ))
1341 (save-excursion (insert ?\n sh-here-document-word)))))
1344 ;; various other commands
1346 (autoload 'comint-dynamic-complete "comint"
1347 "Dynamically perform completion at point." t)
1349 (autoload 'shell-dynamic-complete-command "shell"
1350 "Dynamically complete the command at point." t)
1352 (autoload 'comint-dynamic-complete-filename "comint"
1353 "Dynamically complete the filename at point." t)
1355 (autoload 'shell-dynamic-complete-environment-variable "shell"
1356 "Dynamically complete the environment variable at point." t)
1360 (defun sh-newline-and-indent ()
1361 "Strip unquoted whitespace, insert newline, and indent like current line."
1363 (indent-to (prog1 (current-indentation)
1364 (delete-region (point)
1366 (or (zerop (skip-chars-backward " \t"))
1374 (defun sh-beginning-of-command ()
1375 "Move point to successive beginnings of commands."
1377 (if (re-search-backward sh-beginning-of-command nil t)
1378 (goto-char (match-beginning 2))))
1381 (defun sh-end-of-command ()
1382 "Move point to successive ends of commands."
1384 (if (re-search-forward sh-end-of-command nil t)
1385 (goto-char (match-end 1))))
1387 (provide 'sh-script)
1388 ;; sh-script.el ends here