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 (defun sh-canonicalize-shell (shell)
125 "Convert a shell name SHELL to the one we should handle it as."
127 (setq shell (intern shell)))
128 (or (cdr (assq shell sh-alias-alist))
131 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
132 "The shell being programmed. This is set by \\[sh-set-shell].")
134 ;;; I turned off this feature because it doesn't permit typing commands
135 ;;; in the usual way without help.
136 ;;;(defvar sh-abbrevs
137 ;;; '((csh eval sh-abbrevs shell
138 ;;; "switch" 'sh-case
139 ;;; "getopts" 'sh-while-getopts)
141 ;;; (es eval sh-abbrevs shell
142 ;;; "function" 'sh-function)
144 ;;; (ksh88 eval sh-abbrevs sh
145 ;;; "select" 'sh-select)
147 ;;; (rc eval sh-abbrevs shell
149 ;;; "function" 'sh-function)
151 ;;; (sh eval sh-abbrevs shell
153 ;;; "function" 'sh-function
154 ;;; "until" 'sh-until
155 ;;; "getopts" 'sh-while-getopts)
157 ;;; ;; The next entry is only used for defining the others
158 ;;; (shell "for" sh-for
159 ;;; "loop" sh-indexed-loop
161 ;;; "tmpfile" sh-tmp-file
162 ;;; "while" sh-while)
164 ;;; (zsh eval sh-abbrevs ksh88
165 ;;; "repeat" 'sh-repeat))
166 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
167 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
168 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
172 (defvar sh-mode-syntax-table
173 '((csh eval identity sh)
174 (sh eval sh-mode-syntax-table ()
175 ;; #'s meanings depend on context which can't be expressed here
189 (rc eval sh-mode-syntax-table sh
192 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
197 (let ((map (make-sparse-keymap))
198 (menu-map (make-sparse-keymap "Insert")))
199 (define-key map "\C-c(" 'sh-function)
200 (define-key map "\C-c\C-w" 'sh-while)
201 (define-key map "\C-c\C-u" 'sh-until)
202 (define-key map "\C-c\C-t" 'sh-tmp-file)
203 (define-key map "\C-c\C-s" 'sh-select)
204 (define-key map "\C-c\C-r" 'sh-repeat)
205 (define-key map "\C-c\C-o" 'sh-while-getopts)
206 (define-key map "\C-c\C-l" 'sh-indexed-loop)
207 (define-key map "\C-c\C-i" 'sh-if)
208 (define-key map "\C-c\C-f" 'sh-for)
209 (define-key map "\C-c\C-c" 'sh-case)
211 (define-key map "=" 'sh-assignment)
212 (define-key map "\C-c+" 'sh-add)
213 (define-key map "\C-\M-x" 'sh-execute-region)
214 (define-key map "\C-c\C-x" 'executable-interpret)
215 (define-key map "<" 'sh-maybe-here-document)
216 (define-key map "(" 'skeleton-pair-insert-maybe)
217 (define-key map "{" 'skeleton-pair-insert-maybe)
218 (define-key map "[" 'skeleton-pair-insert-maybe)
219 (define-key map "'" 'skeleton-pair-insert-maybe)
220 (define-key map "`" 'skeleton-pair-insert-maybe)
221 (define-key map "\"" 'skeleton-pair-insert-maybe)
223 (define-key map "\t" 'sh-indent-line)
224 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
225 map (current-global-map))
226 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
227 map (current-global-map))
228 (substitute-key-definition 'delete-backward-char
229 'backward-delete-char-untabify
230 map (current-global-map))
231 (define-key map "\C-c:" 'sh-set-shell)
232 (substitute-key-definition 'beginning-of-defun
233 'sh-beginning-of-compound-command
234 map (current-global-map))
235 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
236 map (current-global-map))
237 (substitute-key-definition 'forward-sentence 'sh-end-of-command
238 map (current-global-map))
239 (define-key map [menu-bar insert] (cons "Insert" menu-map))
240 (define-key menu-map [sh-while] '("While Loop" . sh-while))
241 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
242 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
243 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
244 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
245 (define-key menu-map [sh-while-getopts]
246 '("Options Loop" . sh-while-getopts))
247 (define-key menu-map [sh-indexed-loop]
248 '("Indexed Loop" . sh-indexed-loop))
249 (define-key menu-map [sh-if] '("If Statement" . sh-if))
250 (define-key menu-map [sh-for] '("For Loop" . sh-for))
251 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
253 "Keymap used in Shell-Script mode.")
257 (defvar sh-dynamic-complete-functions
258 '(shell-dynamic-complete-environment-variable
259 shell-dynamic-complete-command
260 comint-dynamic-complete-filename)
261 "*Functions for doing TAB dynamic completion.")
264 (defvar sh-require-final-newline
267 (rc eval . require-final-newline)
268 (sh eval . require-final-newline))
269 "*Value of `require-final-newline' in Shell-Script mode buffers.
273 (defvar sh-comment-prefix
274 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
275 (rc eval identity csh)
276 (sh . "\\(^\\|[ \t|&;()]\\)"))
277 "*Regexp matching what may come before a comment `#'.
278 This must contain one \\(grouping\\) since it is the basis for fontifying
279 comments as well as for `comment-start-skip'.
283 (defvar sh-assignment-regexp
284 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
285 ;; actually spaces are only supported in let/(( ... ))
286 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
287 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
288 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
289 "*Regexp for the variable name and what may follow in an assignment.
290 First grouping matches the variable name. This is upto and including the `='
291 sign. See `sh-feature'.")
294 (defvar sh-indentation 4
295 "The width for further indentation in Shell-Script mode.")
298 (defvar sh-remember-variable-min 3
299 "*Don't remember variables less than this length for completing reads.")
302 (defvar sh-header-marker nil
303 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
304 That command is also used for setting this variable.")
307 (defvar sh-beginning-of-command
308 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
309 "*Regexp to determine the beginning of a shell command.
310 The actual command starts at the beginning of the second \\(grouping\\).")
313 (defvar sh-end-of-command
314 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
315 "*Regexp to determine the end of a shell command.
316 The actual command ends at the end of the first \\(grouping\\).")
320 (defvar sh-here-document-word "EOF"
321 "Word to delimit here documents.")
326 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
330 '((bash eval sh-append posix
331 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
332 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
333 "suspend" "typeset" "unalias")
335 ;; The next entry is only used for defining the others
336 (bourne eval sh-append shell
337 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
340 (csh eval sh-append shell
341 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
342 "setenv" "source" "time" "unalias" "unhash")
344 (dtksh eval identity wksh)
346 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
347 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
349 (jsh eval sh-append sh
350 "bg" "fg" "jobs" "kill" "stop" "suspend")
352 (jcsh eval sh-append csh
353 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
355 (ksh88 eval sh-append bourne
356 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
357 "typeset" "unalias" "whence")
359 (oash eval sh-append sh
360 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
361 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
362 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
363 "wmtitle" "wrefresh")
365 (pdksh eval sh-append ksh88
368 (posix eval sh-append sh
371 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
374 (sh eval sh-append bourne
375 "hash" "test" "type")
377 ;; The next entry is only used for defining the others
378 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
380 (wksh eval sh-append ksh88
383 (zsh eval sh-append ksh88
384 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
385 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
386 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
387 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
388 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
390 "*List of all shell builtins for completing read and fontification.
391 Note that on some systems not all builtins are available or some are
392 implemented as aliases. See `sh-feature'.")
396 (defvar sh-leading-keywords
399 (es "true" "unwind-protect" "whatis")
403 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
404 "*List of keywords that may be immediately followed by a builtin or keyword.
405 Given some confusion between keywords and builtins depending on shell and
406 system, the distinction here has been based on whether they influence the
407 flow of control or syntax. See `sh-feature'.")
410 (defvar sh-other-keywords
411 '((bash eval sh-append bourne
414 ;; The next entry is only used for defining the others
415 (bourne eval sh-append shell
416 "done" "esac" "fi" "for" "function" "in" "return")
418 (csh eval sh-append shell
419 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
420 "if" "logout" "onintr" "repeat" "switch" "then" "while")
422 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
423 "return" "throw" "while")
425 (ksh88 eval sh-append bourne
428 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
431 ;; The next entry is only used for defining the others
432 (shell "break" "case" "continue" "exec" "exit")
434 (zsh eval sh-append bash
436 "*List of keywords not in `sh-leading-keywords'.
442 '((bash eval sh-append sh
443 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
444 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
445 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
446 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
447 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
448 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
449 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
450 "SECONDS" "SHLVL" "TMOUT" "UID")
452 (csh eval sh-append shell
453 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
454 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
455 "shell" "status" "time" "verbose")
457 (es eval sh-append shell
458 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
459 "pid" "prompt" "signals")
461 (jcsh eval sh-append csh
464 (ksh88 eval sh-append sh
465 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
466 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
469 (oash eval sh-append sh
470 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
472 (rc eval sh-append shell
473 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
476 (sh eval sh-append shell
477 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
479 ;; The next entry is only used for defining the others
480 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
481 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
482 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
483 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
485 (tcsh eval sh-append csh
486 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
487 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
488 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
489 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
490 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
491 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
492 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
493 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
496 (zsh eval sh-append ksh88
497 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
498 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
499 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
500 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
501 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
502 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
503 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
504 "List of all shell variables available for completing read.
509 (defvar sh-font-lock-keywords
510 '((csh eval sh-append shell
511 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
512 font-lock-variable-name-face))
514 (es eval sh-append executable-font-lock-keywords
515 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
516 font-lock-variable-name-face))
518 (rc eval identity es)
520 (sh eval sh-append shell
521 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
522 font-lock-variable-name-face))
524 ;; The next entry is only used for defining the others
525 (shell eval sh-append executable-font-lock-keywords
526 '("\\\\." 0 font-lock-string-face)
527 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
528 font-lock-variable-name-face)))
529 "*Rules for highlighting shell scripts. See `sh-feature'.")
531 (defvar sh-font-lock-keywords-1
533 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
535 (defvar sh-font-lock-keywords-2 ()
536 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
538 (defvar sh-font-lock-keywords-only t
539 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
540 Default value is `t' because Emacs' syntax is not expressive enough to
541 detect that $# does not start a comment. Thus comments are fontified by
542 regexp which means that a single apostrophe in a comment turns everything
543 upto the next one or end of buffer into a string.")
545 ;; mode-command and utility functions
548 (put 'sh-mode 'mode-class 'special)
550 "Major mode for editing shell scripts.
551 This mode works for many shells, since they all have roughly the same syntax,
552 as far as commands, arguments, variables, pipes, comments etc. are concerned.
553 Unless the file's magic number indicates the shell, your usual shell is
554 assumed. Since filenames rarely give a clue, they are not further analyzed.
556 This mode adapts to the variations between shells (see `sh-set-shell') by
557 means of an inheritance based feature lookup (see `sh-feature'). This
558 mechanism applies to all variables (including skeletons) that pertain to
559 shell-specific features.
561 The default style of this mode is that of Rosenblatt's Korn shell book.
562 The syntax of the statements varies with the shell being used. The
563 following commands are available, based on the current shell's syntax:
565 \\[sh-case] case statement
567 \\[sh-function] function definition
568 \\[sh-if] if statement
569 \\[sh-indexed-loop] indexed loop from 1 to n
570 \\[sh-while-getopts] while getopts loop
571 \\[sh-repeat] repeat loop
572 \\[sh-select] select loop
573 \\[sh-until] until loop
574 \\[sh-while] while loop
576 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
577 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
578 \\[sh-end-of-command] Go to end of successive commands.
579 \\[sh-beginning-of-command] Go to beginning of successive commands.
580 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
581 \\[sh-execute-region] Have optional header and region be executed in a subshell.
583 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
585 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
587 If you generally program a shell different from your login shell you can
588 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
589 indicate what shell it is use `sh-alias-alist' to translate.
591 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
592 with your script for an edit-interpret-debug cycle."
594 (kill-all-local-variables)
595 (use-local-map sh-mode-map)
596 (make-local-variable 'indent-line-function)
597 (make-local-variable 'indent-region-function)
598 (make-local-variable 'skeleton-end-hook)
599 (make-local-variable 'paragraph-start)
600 (make-local-variable 'paragraph-separate)
601 (make-local-variable 'comment-start)
602 (make-local-variable 'comment-start-skip)
603 (make-local-variable 'require-final-newline)
604 (make-local-variable 'sh-header-marker)
605 (make-local-variable 'sh-shell-file)
606 (make-local-variable 'sh-shell)
607 (make-local-variable 'skeleton-pair-alist)
608 (make-local-variable 'skeleton-pair-filter)
609 (make-local-variable 'comint-dynamic-complete-functions)
610 (make-local-variable 'comint-prompt-regexp)
611 (make-local-variable 'font-lock-keywords)
612 (make-local-variable 'font-lock-defaults)
613 (make-local-variable 'skeleton-filter)
614 (make-local-variable 'skeleton-newline-indent-rigidly)
615 (setq major-mode 'sh-mode
616 mode-name "Shell-script"
617 indent-line-function 'sh-indent-line
618 ;; not very clever, but enables wrapping skeletons around regions
619 indent-region-function (lambda (b e)
622 (skip-syntax-backward "-")
625 (skip-syntax-backward "-")
626 (indent-rigidly b (point) sh-indentation)))
627 skeleton-end-hook (lambda ()
628 (or (eolp) (newline) (indent-relative)))
629 paragraph-start (concat page-delimiter "\\|$")
630 paragraph-separate paragraph-start
632 comint-dynamic-complete-functions sh-dynamic-complete-functions
633 ;; we can't look if previous line ended with `\'
634 comint-prompt-regexp "^[ \t]*"
636 `((sh-font-lock-keywords
637 sh-font-lock-keywords-1
638 sh-font-lock-keywords-2)
639 ,sh-font-lock-keywords-only
641 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
642 skeleton-pair-alist '((?` _ ?`))
643 skeleton-pair-filter 'sh-quoted-p
644 skeleton-further-elements '((< '(- (min sh-indentation
646 skeleton-filter 'sh-feature
647 skeleton-newline-indent-rigidly t)
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 ]+\\)")
656 (run-hooks 'sh-mode-hook))
658 (defalias 'shell-script-mode 'sh-mode)
661 (defun sh-font-lock-keywords (&optional keywords)
662 "Function to get simple fontification based on `sh-font-lock-keywords'.
663 This adds rules for comments and assignments."
664 (sh-feature sh-font-lock-keywords
666 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
667 2 font-lock-comment-face t)
668 (,(sh-feature sh-assignment-regexp)
669 1 font-lock-variable-name-face)
673 (defun sh-font-lock-keywords-1 (&optional builtins)
674 "Function to get better fontification including keywords."
675 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
677 (sh-feature sh-leading-keywords)
681 (append (sh-feature sh-leading-keywords)
682 (sh-feature sh-other-keywords))
685 (sh-font-lock-keywords
687 `((,(concat keywords "[ \t]+\\)?\\("
688 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
690 (2 font-lock-keyword-face nil t)
691 (6 font-lock-function-name-face))
692 ,@(sh-feature sh-font-lock-keywords-2)))
693 (,(concat keywords "\\)\\>")
694 2 font-lock-keyword-face)
695 ,@(sh-feature sh-font-lock-keywords-1)))))
697 (defun sh-font-lock-keywords-2 ()
698 "Function to get better fontification including keywords and builtins."
699 (sh-font-lock-keywords-1 t))
702 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
703 "Set this buffer's shell to SHELL (a string).
704 Makes this script executable via `executable-set-magic'.
705 Calls the value of `sh-set-shell-hook' if set."
706 (interactive (list (completing-read "Name or path of shell: "
707 interpreter-mode-alist
708 (lambda (x) (eq (cdr x) 'sh-mode)))
709 (eq executable-query 'function)
711 (setq sh-shell (intern (file-name-nondirectory shell))
712 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
714 (setq sh-shell-file (executable-set-magic shell (sh-feature sh-shell-arg)))
715 (setq require-final-newline (sh-feature sh-require-final-newline)
716 ;;; local-abbrev-table (sh-feature sh-abbrevs)
717 font-lock-keywords nil ; force resetting
718 font-lock-syntax-table nil
719 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
720 mode-line-process (format "[%s]" sh-shell)
721 sh-shell-variables nil
722 shell (sh-feature sh-variables))
723 (set-syntax-table (sh-feature sh-mode-syntax-table))
725 (while (search-forward "=" nil t)
728 (sh-remember-variable (car shell))
729 (setq shell (cdr shell)))
730 (and (boundp 'font-lock-mode)
732 (font-lock-mode (font-lock-mode 0)))
733 (run-hooks 'sh-set-shell-hook))
737 (defun sh-feature (list &optional function)
738 "Index ALIST by the current shell.
739 If ALIST isn't a list where every element is a cons, it is returned as is.
740 Else indexing follows an inheritance logic which works in two ways:
742 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
743 the alist contains no value for the current shell.
745 - If the value thus looked up is a list starting with `eval' its `cdr' is
746 first evaluated. If that is also a list and the first argument is a
747 symbol in ALIST it is not evaluated, but rather recursively looked up in
748 ALIST to allow the function called to define the value for one shell to be
749 derived from another shell. While calling the function, is the car of the
750 alist element is the current shell.
751 The value thus determined is physically replaced into the alist.
753 Optional FUNCTION is applied to the determined value and the result is cached
757 (while (and l (consp (car l)))
761 (cdr (assoc (setq function (cons sh-shell function)) list)))
762 (let ((sh-shell sh-shell)
765 (not (setq elt (assq sh-shell list))))
766 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
767 (if (and (consp (setq val (cdr elt)))
768 (eq (car val) 'eval))
771 (eval (if (consp (setq val (cdr val)))
772 (let ((sh-shell (car (cdr val)))
774 (if (assq sh-shell list)
783 (setq sh-shell (car function)
784 val (funcall (cdr function) val))))))
789 ;;; I commented this out because nobody calls it -- rms.
790 ;;;(defun sh-abbrevs (ancestor &rest list)
791 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
792 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
793 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
794 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
795 ;;;EXPANSION may be either a string or a skeleton command."
796 ;;; (or (if (boundp sh-shell)
797 ;;; (symbol-value sh-shell))
799 ;;; (if (listp ancestor)
800 ;;; (nconc list ancestor))
801 ;;; (define-abbrev-table sh-shell ())
802 ;;; (if (vectorp ancestor)
803 ;;; (mapatoms (lambda (atom)
805 ;;; (define-abbrev (symbol-value sh-shell)
806 ;;; (symbol-name atom)
807 ;;; (symbol-value atom)
808 ;;; (symbol-function atom))))
811 ;;; (define-abbrev (symbol-value sh-shell)
813 ;;; (if (stringp (car (cdr list)))
816 ;;; (if (symbolp (car (cdr list)))
817 ;;; (car (cdr list))))
818 ;;; (setq list (cdr (cdr list)))))
819 ;;; (symbol-value sh-shell)))
822 (defun sh-mode-syntax-table (table &rest list)
823 "Copy TABLE and set syntax for successive CHARs according to strings S."
824 (setq table (copy-syntax-table table))
826 (modify-syntax-entry (car list) (car (cdr list)) table)
827 (setq list (cdr (cdr list))))
831 (defun sh-append (ancestor &rest list)
832 "Return list composed of first argument (a list) physically appended to rest."
833 (nconc list ancestor))
836 (defun sh-modify (skeleton &rest list)
837 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
838 (setq skeleton (copy-sequence skeleton))
840 (setcar (or (nthcdr (car list) skeleton)
841 (error "Index %d out of bounds" (car list)))
843 (setq list (nthcdr 2 list)))
847 (defun sh-indent-line ()
848 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
849 Lines containing only comments are considered empty."
851 (let ((previous (save-excursion
852 (while (and (not (bobp))
855 (back-to-indentation)
857 (eq (following-char) ?#)))))
861 (indent-to (if (eq this-command 'newline-and-indent)
863 (if (< (current-column)
864 (setq current (progn (back-to-indentation)
866 (if (eolp) previous 0)
867 (delete-region (point)
868 (progn (beginning-of-line) (point)))
870 (max previous (* (1+ (/ current sh-indentation))
872 (* (1+ (/ current sh-indentation)) sh-indentation))))))
873 (if (< (current-column) (current-indentation))
874 (skip-chars-forward " \t"))))
877 (defun sh-execute-region (start end &optional flag)
878 "Pass optional header and region to a subshell for noninteractive execution.
879 The working directory is that of the buffer, and only environment variables
880 are already set which is why you can mark a header within the script.
882 With a positive prefix ARG, instead of sending region, define header from
883 beginning of buffer to point. With a negative prefix ARG, instead of sending
884 region, clear header."
887 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
891 (let (buffer-undo-list)
892 (goto-char sh-header-marker)
893 (append-to-buffer (current-buffer) start end)
894 (shell-command-on-region (point-min)
895 (setq end (+ sh-header-marker
898 (delete-region sh-header-marker end)))
899 (shell-command-on-region start end (concat sh-shell-file " -")))))
902 (defun sh-remember-variable (var)
903 "Make VARIABLE available for future completing reads in this buffer."
904 (or (< (length var) sh-remember-variable-min)
906 (assoc var sh-shell-variables)
907 (setq sh-shell-variables (cons (cons var var) sh-shell-variables)))
912 (defun sh-quoted-p ()
913 "Is point preceded by an odd number of backslashes?"
914 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
916 ;; statement syntax-commands for various shells
918 ;; You are welcome to add the syntax or even completely new statements as
919 ;; appropriate for your favorite shell.
921 (define-skeleton sh-case
922 "Insert a case/switch statement. See `sh-feature'."
924 "switch( " str " )" \n
925 > "case " (read-string "pattern: ") ?: \n
928 ( "other pattern, %s: "
938 "switch( " str " ) {" \n
939 > "case " (read-string "pattern: ") \n
941 ( "other pattern, %s: "
950 > (read-string "pattern: ") ?\) \n
953 ( "other pattern, %s: "
961 (put 'sh-case 'menu-enable '(sh-feature sh-case))
965 (define-skeleton sh-for
966 "Insert a for loop. See `sh-feature'."
967 (csh eval sh-modify sh
972 (es eval sh-modify rc
974 (rc eval sh-modify sh
978 (sh "Index variable: "
979 "for " str " in " _ "; do" \n
980 > _ | ?$ & (sh-remember-variable str) \n
985 (define-skeleton sh-indexed-loop
986 "Insert an indexed loop from 1 to n. See `sh-feature'."
987 (bash eval identity posix)
988 (csh "Index variable: "
990 "while( $" str " <= " (read-string "upper limit: ") " )" \n
994 (es eval sh-modify rc
996 (ksh88 "Index variable: "
997 "integer " str "=0" \n
998 "while (( ( " str " += 1 ) <= "
999 (read-string "upper limit: ")
1001 > _ ?$ (sh-remember-variable str) \n
1003 (posix "Index variable: "
1005 "while [ $" str " -le "
1006 (read-string "upper limit: ")
1009 str ?= (sh-add (sh-remember-variable str) 1) \n
1011 (rc "Index variable: "
1012 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
1013 (read-string "upper limit: ")
1014 "; i++ ) print i }'}) {" \n
1015 > _ ?$ (sh-remember-variable str) \n
1017 (sh "Index variable: "
1018 "for " str " in `awk 'BEGIN { for( i=1; i<="
1019 (read-string "upper limit: ")
1020 "; i++ ) print i }'`; do" \n
1021 > _ ?$ (sh-remember-variable str) \n
1025 (defun sh-add (var delta)
1026 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1028 (list (completing-read "Variable: "
1029 (nconc (mapcar (lambda (var)
1031 (substring var 0 (string-match "=" var))))
1033 process-environment)
1034 sh-shell-variables))
1035 (prefix-numeric-value current-prefix-arg)))
1036 (insert (sh-feature '((bash . "$[ ")
1042 (sh-remember-variable var)
1043 (if (< delta 0) " - " " + ")
1044 (number-to-string (abs delta))
1045 (sh-feature '((bash . " ]")
1054 (define-skeleton sh-function
1055 "Insert a function definition. See `sh-feature'."
1056 (bash eval sh-modify ksh88
1059 "function " str " {" \n
1062 (rc eval sh-modify ksh88
1071 (define-skeleton sh-if
1072 "Insert an if statement. See `sh-feature'."
1074 "if( " str " ) then" \n
1076 ( "other condition, %s: "
1077 < "else if( " str " ) then" \n
1084 "if { " str " } {" \n
1086 ( "other condition, %s: "
1087 < "} { " str " } {" \n
1093 (rc eval sh-modify csh
1095 8 '( "other condition, %s: "
1096 < "} else if( " str " ) {" \n
1101 '(setq input (sh-feature sh-test))
1102 "if " str "; then" \n
1104 ( "other condition, %s: "
1105 < "elif " str "; then" \n
1114 (define-skeleton sh-repeat
1115 "Insert a repeat loop definition. See `sh-feature'."
1121 "repeat " str "; do"\n
1124 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1128 (define-skeleton sh-select
1129 "Insert a select statement. See `sh-feature'."
1130 (ksh88 "Index variable: "
1131 "select " str " in " _ "; do" \n
1134 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1138 (define-skeleton sh-tmp-file
1139 "Insert code to setup temporary file handling. See `sh-feature'."
1140 (bash eval identity ksh88)
1141 (csh (file-name-nondirectory (buffer-file-name))
1142 "set tmp = /tmp/" str ".$$" \n
1144 (and (goto-char (point-max))
1148 "rm $tmp* >&/dev/null" >)
1149 (es (file-name-nondirectory (buffer-file-name))
1150 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1152 > "rm $tmp^* >[2]/dev/null" \n
1158 (ksh88 eval sh-modify sh
1160 (rc (file-name-nondirectory (buffer-file-name))
1161 "tmp = /tmp/" str ".$pid" \n
1162 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1163 (sh (file-name-nondirectory (buffer-file-name))
1164 "TMP=/tmp/" str ".$$" \n
1165 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1169 (define-skeleton sh-until
1170 "Insert an until loop. See `sh-feature'."
1172 '(setq input (sh-feature sh-test))
1173 "until " str "; do" \n
1176 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1180 (define-skeleton sh-while
1181 "Insert a while loop. See `sh-feature'."
1182 (csh eval sh-modify sh
1186 (es eval sh-modify rc
1189 (rc eval sh-modify csh
1193 '(setq input (sh-feature sh-test))
1194 "while " str "; do" \n
1200 (define-skeleton sh-while-getopts
1201 "Insert a while getopts loop. See `sh-feature'.
1202 Prompts for an options string which consists of letters for each recognized
1203 option followed by a colon `:' if the option accepts an argument."
1204 (bash eval sh-modify sh
1208 > "switch( \"$1\" )" \n
1209 '(setq input '("- x" . 2))
1212 < "case " '(eval str)
1213 '(if (string-match " +" str)
1214 (setq v1 (substring str (match-end 0))
1215 str (substring str 0 (match-beginning 0)))
1218 > "set " v1 & " = $2" | -4 & _ \n
1219 (if v1 "shift") & \n
1229 (ksh88 eval sh-modify sh
1233 (posix eval sh-modify sh
1234 18 "$(basename $0)")
1236 "while getopts :" str " OPT; do" \n
1239 '(setq v1 (append (vconcat str) nil))
1240 ( (prog1 (if v1 (char-to-string (car v1)))
1241 (if (eq (nth 1 v1) ?:)
1242 (setq v1 (nthcdr 2 v1)
1246 < str "|+" str ?\) \n
1250 > "echo" " \"usage: " "`basename $0`"
1251 "[ +-" '(setq v1 (point)) str
1253 (while (search-backward ":" v1 t)
1254 (replace-match " arg][ +-" t t)))
1255 (if (eq (preceding-char) ?-) -5)
1260 "shift " (sh-add "OPTIND" -1)))
1261 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1265 (defun sh-assignment (arg)
1266 "Remember preceding identifier for future completion and do self-insert."
1268 (self-insert-command arg)
1270 (sh-remember-variable
1272 (if (re-search-forward (sh-feature sh-assignment-regexp)
1274 (beginning-of-line 1))
1276 (match-string 1))))))
1280 (defun sh-maybe-here-document (arg)
1281 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1282 The document is bounded by `sh-here-document-word'."
1284 (self-insert-command (prefix-numeric-value arg))
1286 (not (eq (char-after (- (point) 2)) last-command-char))
1291 (insert sh-here-document-word)
1292 (or (eolp) (looking-at "[ \t]") (insert ? ))
1298 (save-excursion (insert ?\n sh-here-document-word)))))
1301 ;; various other commands
1303 (autoload 'comint-dynamic-complete "comint"
1304 "Dynamically perform completion at point." t)
1306 (autoload 'shell-dynamic-complete-command "shell"
1307 "Dynamically complete the command at point." t)
1309 (autoload 'comint-dynamic-complete-filename "comint"
1310 "Dynamically complete the filename at point." t)
1312 (autoload 'shell-dynamic-complete-environment-variable "shell"
1313 "Dynamically complete the environment variable at point." t)
1317 (defun sh-newline-and-indent ()
1318 "Strip unquoted whitespace, insert newline, and indent like current line."
1320 (indent-to (prog1 (current-indentation)
1321 (delete-region (point)
1323 (or (zerop (skip-chars-backward " \t"))
1331 (defun sh-beginning-of-command ()
1332 "Move point to successive beginnings of commands."
1334 (if (re-search-backward sh-beginning-of-command nil t)
1335 (goto-char (match-beginning 2))))
1338 (defun sh-end-of-command ()
1339 "Move point to successive ends of commands."
1341 (if (re-search-forward sh-end-of-command nil t)
1342 (goto-char (match-end 1))))
1344 (provide 'sh-script)
1345 ;; sh-script.el ends here