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 'gnu/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
106 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
107 ;; the executable extension, so comparisons with the list of
108 ;; known shells work.
109 (and (memq system-type '(ms-dos windows-nt))
110 (file-name-sans-extension (downcase (getenv "SHELL"))))
113 "*The executable file name for the shell being programmed.")
117 ;; bash does not need any options when run in a shell script,
121 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
123 ;; -p means don't initialize functions from the environment.
125 ;; Someone proposed -motif, but we don't want to encourage
126 ;; use of a non-free widget set.
128 ;; -f means don't run .zshrc.
130 "*Single argument string for the magic number. See `sh-feature'.")
132 (defvar sh-shell-variables nil
133 "Alist of shell variable names that should be included in completion.
134 These are used for completion in addition to all the variables named
135 in `process-environment'. Each element looks like (VAR . VAR), where
136 the car and cdr are the same symbol.")
138 (defvar sh-shell-variables-initialized nil
139 "Non-nil if `sh-shell-variables' is initialized.")
141 (defun sh-canonicalize-shell (shell)
142 "Convert a shell name SHELL to the one we should handle it as."
144 (setq shell (intern shell)))
145 (or (cdr (assq shell sh-alias-alist))
148 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
149 "The shell being programmed. This is set by \\[sh-set-shell].")
151 ;;; I turned off this feature because it doesn't permit typing commands
152 ;;; in the usual way without help.
153 ;;;(defvar sh-abbrevs
154 ;;; '((csh eval sh-abbrevs shell
155 ;;; "switch" 'sh-case
156 ;;; "getopts" 'sh-while-getopts)
158 ;;; (es eval sh-abbrevs shell
159 ;;; "function" 'sh-function)
161 ;;; (ksh88 eval sh-abbrevs sh
162 ;;; "select" 'sh-select)
164 ;;; (rc eval sh-abbrevs shell
166 ;;; "function" 'sh-function)
168 ;;; (sh eval sh-abbrevs shell
170 ;;; "function" 'sh-function
171 ;;; "until" 'sh-until
172 ;;; "getopts" 'sh-while-getopts)
174 ;;; ;; The next entry is only used for defining the others
175 ;;; (shell "for" sh-for
176 ;;; "loop" sh-indexed-loop
178 ;;; "tmpfile" sh-tmp-file
179 ;;; "while" sh-while)
181 ;;; (zsh eval sh-abbrevs ksh88
182 ;;; "repeat" 'sh-repeat))
183 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
184 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
185 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
189 (defvar sh-mode-syntax-table
190 '((sh eval sh-mode-syntax-table ()
197 ?$ "\\" ; `escape' so $# doesn't start a comment
204 (csh eval identity sh)
205 (rc eval identity sh))
206 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
211 (let ((map (make-sparse-keymap))
212 (menu-map (make-sparse-keymap "Insert")))
213 (define-key map "\C-c(" 'sh-function)
214 (define-key map "\C-c\C-w" 'sh-while)
215 (define-key map "\C-c\C-u" 'sh-until)
216 (define-key map "\C-c\C-t" 'sh-tmp-file)
217 (define-key map "\C-c\C-s" 'sh-select)
218 (define-key map "\C-c\C-r" 'sh-repeat)
219 (define-key map "\C-c\C-o" 'sh-while-getopts)
220 (define-key map "\C-c\C-l" 'sh-indexed-loop)
221 (define-key map "\C-c\C-i" 'sh-if)
222 (define-key map "\C-c\C-f" 'sh-for)
223 (define-key map "\C-c\C-c" 'sh-case)
225 (define-key map "=" 'sh-assignment)
226 (define-key map "\C-c+" 'sh-add)
227 (define-key map "\C-\M-x" 'sh-execute-region)
228 (define-key map "\C-c\C-x" 'executable-interpret)
229 (define-key map "<" 'sh-maybe-here-document)
230 (define-key map "(" 'skeleton-pair-insert-maybe)
231 (define-key map "{" 'skeleton-pair-insert-maybe)
232 (define-key map "[" 'skeleton-pair-insert-maybe)
233 (define-key map "'" 'skeleton-pair-insert-maybe)
234 (define-key map "`" 'skeleton-pair-insert-maybe)
235 (define-key map "\"" 'skeleton-pair-insert-maybe)
237 (define-key map "\t" 'sh-indent-line)
238 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
239 map (current-global-map))
240 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
241 map (current-global-map))
242 (substitute-key-definition 'delete-backward-char
243 'backward-delete-char-untabify
244 map (current-global-map))
245 (define-key map "\C-c:" 'sh-set-shell)
246 (substitute-key-definition 'beginning-of-defun
247 'sh-beginning-of-compound-command
248 map (current-global-map))
249 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
250 map (current-global-map))
251 (substitute-key-definition 'forward-sentence 'sh-end-of-command
252 map (current-global-map))
253 (define-key map [menu-bar insert] (cons "Insert" menu-map))
254 (define-key menu-map [sh-while] '("While Loop" . sh-while))
255 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
256 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
257 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
258 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
259 (define-key menu-map [sh-while-getopts]
260 '("Options Loop" . sh-while-getopts))
261 (define-key menu-map [sh-indexed-loop]
262 '("Indexed Loop" . sh-indexed-loop))
263 (define-key menu-map [sh-if] '("If Statement" . sh-if))
264 (define-key menu-map [sh-for] '("For Loop" . sh-for))
265 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
267 "Keymap used in Shell-Script mode.")
271 (defvar sh-dynamic-complete-functions
272 '(shell-dynamic-complete-environment-variable
273 shell-dynamic-complete-command
274 comint-dynamic-complete-filename)
275 "*Functions for doing TAB dynamic completion.")
278 (defvar sh-require-final-newline
281 (rc eval . require-final-newline)
282 (sh eval . require-final-newline))
283 "*Value of `require-final-newline' in Shell-Script mode buffers.
287 (defvar sh-assignment-regexp
288 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
289 ;; actually spaces are only supported in let/(( ... ))
290 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
291 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
292 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
293 "*Regexp for the variable name and what may follow in an assignment.
294 First grouping matches the variable name. This is upto and including the `='
295 sign. See `sh-feature'.")
298 (defvar sh-indentation 4
299 "The width for further indentation in Shell-Script mode.")
302 (defvar sh-remember-variable-min 3
303 "*Don't remember variables less than this length for completing reads.")
306 (defvar sh-header-marker nil
307 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
308 That command is also used for setting this variable.")
311 (defvar sh-beginning-of-command
312 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
313 "*Regexp to determine the beginning of a shell command.
314 The actual command starts at the beginning of the second \\(grouping\\).")
317 (defvar sh-end-of-command
318 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
319 "*Regexp to determine the end of a shell command.
320 The actual command ends at the end of the first \\(grouping\\).")
324 (defvar sh-here-document-word "EOF"
325 "Word to delimit here documents.")
330 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
334 '((bash eval sh-append posix
335 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
336 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
337 "suspend" "typeset" "unalias")
339 ;; The next entry is only used for defining the others
340 (bourne eval sh-append shell
341 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
344 (csh eval sh-append shell
345 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
346 "setenv" "source" "time" "unalias" "unhash")
348 (dtksh eval identity wksh)
350 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
351 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
353 (jsh eval sh-append sh
354 "bg" "fg" "jobs" "kill" "stop" "suspend")
356 (jcsh eval sh-append csh
357 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
359 (ksh88 eval sh-append bourne
360 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
361 "typeset" "unalias" "whence")
363 (oash eval sh-append sh
364 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
365 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
366 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
367 "wmtitle" "wrefresh")
369 (pdksh eval sh-append ksh88
372 (posix eval sh-append sh
375 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
378 (sh eval sh-append bourne
379 "hash" "test" "type")
381 ;; The next entry is only used for defining the others
382 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
384 (wksh eval sh-append ksh88
387 (zsh eval sh-append ksh88
388 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
389 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
390 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
391 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
392 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
394 "*List of all shell builtins for completing read and fontification.
395 Note that on some systems not all builtins are available or some are
396 implemented as aliases. See `sh-feature'.")
400 (defvar sh-leading-keywords
403 (es "true" "unwind-protect" "whatis")
407 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
408 "*List of keywords that may be immediately followed by a builtin or keyword.
409 Given some confusion between keywords and builtins depending on shell and
410 system, the distinction here has been based on whether they influence the
411 flow of control or syntax. See `sh-feature'.")
414 (defvar sh-other-keywords
415 '((bash eval sh-append bourne
418 ;; The next entry is only used for defining the others
419 (bourne eval sh-append sh
422 (csh eval sh-append shell
423 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
424 "if" "logout" "onintr" "repeat" "switch" "then" "while")
426 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
427 "return" "throw" "while")
429 (ksh88 eval sh-append bourne
432 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
435 (sh eval sh-append shell
436 "done" "esac" "fi" "for" "in" "return")
438 ;; The next entry is only used for defining the others
439 (shell "break" "case" "continue" "exec" "exit")
441 (zsh eval sh-append bash
443 "*List of keywords not in `sh-leading-keywords'.
449 '((bash eval sh-append sh
450 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
451 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
452 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
453 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
454 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
455 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
456 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
457 "SECONDS" "SHLVL" "TMOUT" "UID")
459 (csh eval sh-append shell
460 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
461 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
462 "shell" "status" "time" "verbose")
464 (es eval sh-append shell
465 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
466 "pid" "prompt" "signals")
468 (jcsh eval sh-append csh
471 (ksh88 eval sh-append sh
472 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
473 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
476 (oash eval sh-append sh
477 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
479 (rc eval sh-append shell
480 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
483 (sh eval sh-append shell
484 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
486 ;; The next entry is only used for defining the others
487 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
488 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
489 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
490 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
492 (tcsh eval sh-append csh
493 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
494 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
495 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
496 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
497 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
498 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
499 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
500 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
503 (zsh eval sh-append ksh88
504 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
505 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
506 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
507 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
508 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
509 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
510 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
511 "List of all shell variables available for completing read.
516 (defvar sh-font-lock-keywords
517 '((csh eval sh-append shell
518 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
519 font-lock-variable-name-face))
521 (es eval sh-append executable-font-lock-keywords
522 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
523 font-lock-variable-name-face))
525 (rc eval identity es)
527 (sh eval sh-append shell
528 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
529 font-lock-variable-name-face))
531 ;; The next entry is only used for defining the others
532 (shell eval sh-append executable-font-lock-keywords
533 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
534 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
535 font-lock-variable-name-face)))
536 "*Rules for highlighting shell scripts. See `sh-feature'.")
538 (defvar sh-font-lock-keywords-1
540 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
542 (defvar sh-font-lock-keywords-2 ()
543 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
546 ;; mode-command and utility functions
549 (put 'sh-mode 'mode-class 'special)
553 "Major mode for editing shell scripts.
554 This mode works for many shells, since they all have roughly the same syntax,
555 as far as commands, arguments, variables, pipes, comments etc. are concerned.
556 Unless the file's magic number indicates the shell, your usual shell is
557 assumed. Since filenames rarely give a clue, they are not further analyzed.
559 This mode adapts to the variations between shells (see `sh-set-shell') by
560 means of an inheritance based feature lookup (see `sh-feature'). This
561 mechanism applies to all variables (including skeletons) that pertain to
562 shell-specific features.
564 The default style of this mode is that of Rosenblatt's Korn shell book.
565 The syntax of the statements varies with the shell being used. The
566 following commands are available, based on the current shell's syntax:
568 \\[sh-case] case statement
570 \\[sh-function] function definition
571 \\[sh-if] if statement
572 \\[sh-indexed-loop] indexed loop from 1 to n
573 \\[sh-while-getopts] while getopts loop
574 \\[sh-repeat] repeat loop
575 \\[sh-select] select loop
576 \\[sh-until] until loop
577 \\[sh-while] while loop
579 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
580 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
581 \\[sh-end-of-command] Go to end of successive commands.
582 \\[sh-beginning-of-command] Go to beginning of successive commands.
583 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
584 \\[sh-execute-region] Have optional header and region be executed in a subshell.
586 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
588 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
590 If you generally program a shell different from your login shell you can
591 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
592 indicate what shell it is use `sh-alias-alist' to translate.
594 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
595 with your script for an edit-interpret-debug cycle."
597 (kill-all-local-variables)
598 (use-local-map sh-mode-map)
599 (make-local-variable 'indent-line-function)
600 (make-local-variable 'indent-region-function)
601 (make-local-variable 'skeleton-end-hook)
602 (make-local-variable 'paragraph-start)
603 (make-local-variable 'paragraph-separate)
604 (make-local-variable 'comment-start)
605 (make-local-variable 'comment-start-skip)
606 (make-local-variable 'require-final-newline)
607 (make-local-variable 'sh-header-marker)
608 (make-local-variable 'sh-shell-file)
609 (make-local-variable 'sh-shell)
610 (make-local-variable 'skeleton-pair-alist)
611 (make-local-variable 'skeleton-pair-filter)
612 (make-local-variable 'comint-dynamic-complete-functions)
613 (make-local-variable 'comint-prompt-regexp)
614 (make-local-variable 'font-lock-defaults)
615 (make-local-variable 'skeleton-filter)
616 (make-local-variable 'skeleton-newline-indent-rigidly)
617 (make-local-variable 'sh-shell-variables)
618 (make-local-variable 'sh-shell-variables-initialized)
619 (setq major-mode 'sh-mode
620 mode-name "Shell-script"
621 indent-line-function 'sh-indent-line
622 ;; not very clever, but enables wrapping skeletons around regions
623 indent-region-function (lambda (b e)
626 (skip-syntax-backward "-")
629 (skip-syntax-backward "-")
630 (indent-rigidly b (point) sh-indentation)))
631 skeleton-end-hook (lambda ()
632 (or (eolp) (newline) (indent-relative)))
633 paragraph-start (concat page-delimiter "\\|$")
634 paragraph-separate paragraph-start
636 comint-dynamic-complete-functions sh-dynamic-complete-functions
637 ;; we can't look if previous line ended with `\'
638 comint-prompt-regexp "^[ \t]*"
640 `((sh-font-lock-keywords
641 sh-font-lock-keywords-1
642 sh-font-lock-keywords-2)
644 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
645 skeleton-pair-alist '((?` _ ?`))
646 skeleton-pair-filter 'sh-quoted-p
647 skeleton-further-elements '((< '(- (min sh-indentation
649 skeleton-filter 'sh-feature
650 skeleton-newline-indent-rigidly t)
651 ;; Parse or insert magic number for exec, and set all variables depending
652 ;; on the shell thus determined.
655 (goto-char (point-min))
656 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
657 (buffer-substring (match-beginning 2)
660 (sh-set-shell interpreter nil nil)))
661 (run-hooks 'sh-mode-hook))
663 (defalias 'shell-script-mode 'sh-mode)
666 (defun sh-font-lock-keywords (&optional keywords)
667 "Function to get simple fontification based on `sh-font-lock-keywords'.
668 This adds rules for comments and assignments."
669 (sh-feature sh-font-lock-keywords
671 `((,(sh-feature sh-assignment-regexp)
672 1 font-lock-variable-name-face)
676 (defun sh-font-lock-keywords-1 (&optional builtins)
677 "Function to get better fontification including keywords."
678 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
680 (sh-feature sh-leading-keywords)
684 (append (sh-feature sh-leading-keywords)
685 (sh-feature sh-other-keywords))
688 (sh-font-lock-keywords
690 `((,(concat keywords "[ \t]+\\)?\\("
691 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
693 (2 font-lock-keyword-face nil t)
694 (6 font-lock-builtin-face))
695 ,@(sh-feature sh-font-lock-keywords-2)))
696 (,(concat keywords "\\)\\>")
697 2 font-lock-keyword-face)
698 ,@(sh-feature sh-font-lock-keywords-1)))))
700 (defun sh-font-lock-keywords-2 ()
701 "Function to get better fontification including keywords and builtins."
702 (sh-font-lock-keywords-1 t))
705 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
706 "Set this buffer's shell to SHELL (a string).
707 Makes this script executable via `executable-set-magic', and sets up the
708 proper starting #!-line, if INSERT-FLAG is non-nil.
709 Calls the value of `sh-set-shell-hook' if set."
710 (interactive (list (completing-read "Name or path of shell: "
711 interpreter-mode-alist
712 (lambda (x) (eq (cdr x) 'sh-mode)))
713 (eq executable-query 'function)
715 (setq sh-shell (intern (file-name-nondirectory shell))
716 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
720 (executable-set-magic shell (sh-feature sh-shell-arg)
721 no-query-flag insert-flag)))
722 (setq require-final-newline (sh-feature sh-require-final-newline)
723 ;;; local-abbrev-table (sh-feature sh-abbrevs)
724 font-lock-keywords nil ; force resetting
725 font-lock-syntax-table nil
726 comment-start-skip "#+[\t ]*"
727 mode-line-process (format "[%s]" sh-shell)
728 sh-shell-variables nil
729 sh-shell-variables-initialized nil
730 shell (sh-feature sh-variables))
731 (set-syntax-table (sh-feature sh-mode-syntax-table))
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)
1299 "] [--] ARGS...\"" \n
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