1 ;;; sh-script.el --- shell-script editing commands for Emacs
2 ;; Copyright (C) 1993, 1994, 1995 by Free Software Foundation, Inc.
4 ;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
7 ;; Keywords: languages, unix
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to
23 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
27 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
28 ;; as various derivatives are supported and easily derived from. Structured
29 ;; statements can be inserted with one command or abbrev. Completion is
30 ;; available for filenames, variables known from the script, the shell and
31 ;; the environment as well as commands.
35 ;; - Since GNU Emacs' syntax can't handle the context-sensitive meanings of
36 ;; the variable/number base/comment symbol `#', that has to be fontified by
37 ;; regexp. This alas means that a quote `'' or `"' in a comment will
38 ;; fontify VERY badly. The alternative is to have these frequent constructs
39 ;; with `#' fontify as comments. Or maybe we intoduce a 'syntax text-
41 ;; - Variables in `"' strings aren't fontified because there's no way of
42 ;; syntactically distinguishing those from `'' strings.
46 ;; page 1: variables and settings
47 ;; page 2: mode-command and utility functions
48 ;; page 3: statement syntax-commands for various shells
49 ;; page 4: various other commands
55 ;; Autoload cookie deleted here because it made loaddefs.el fail to load.
57 (or (assoc "sh" interpreter-mode-alist)
60 ;; - that have a suffix .sh, .csh or .shar (shell archive)
61 ;; - that contain ressources for the various shells
62 ;; - startup files for X11
63 (cons '("\\.c?sh\\'\\|\\.shar\\'\\|/\\.\\(z?profile\\|bash_profile\\|z?login\\|bash_login\\|z?logout\\|bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\|rcrc\\|[kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
65 interpreter-mode-alist
66 (nconc '(("ash" . sh-mode)
83 interpreter-mode-alist)))
86 (defvar sh-ancestor-alist
103 "*Alist showing the direct ancestor of various shells.
104 This is the basis for `sh-feature'. See also `sh-alias-alist'.
105 By default we have the following three hierarchies:
108 jcsh C Shell with Job Control
110 itcsh ? Toronto C Shell
115 jsh Bourne Shell with Job Control
116 bash GNU Bourne Again Shell
119 dtksh CDE Desktop Korn Shell
120 pdksh Public Domain Korn Shell
121 wksh Window Korn Shell
123 oash SCO OA (curses) Shell
124 posix IEEE 1003.2 Shell Standard
128 (defvar sh-alias-alist
129 (nconc (if (eq system-type 'linux)
133 ;; for the time being
136 "*Alist for transforming shell names to what they really are.
137 Use this where the name of the executable doesn't correspond to the type of
138 shell it really is.")
141 (defvar sh-shell-path (or (getenv "SHELL") "/bin/sh")
142 "*The executable of the shell being programmed.")
148 (ksh88 eval progn nil (if (file-exists-p "/etc/suid_profile") nil "-p"))
153 "*Single argument string for the magic number. See `sh-feature'.")
157 (defvar sh-shell (or (cdr (assq (intern (file-name-nondirectory sh-shell-path))
159 (intern (file-name-nondirectory sh-shell-path)))
160 "The shell being programmed. This is set by \\[sh-set-shell].")
165 '((csh eval sh-abbrevs shell
167 "getopts" 'sh-while-getopts)
169 (es eval sh-abbrevs shell
170 "function" 'sh-function)
172 (ksh88 eval sh-abbrevs sh
175 (rc eval sh-abbrevs shell
177 "function" 'sh-function)
179 (sh eval sh-abbrevs shell
181 "function" 'sh-function
183 "getopts" 'sh-while-getopts)
185 ;; The next entry is only used for defining the others
187 "loop" sh-indexed-loop
189 "tmpfile" sh-tmp-file
192 (zsh eval sh-abbrevs ksh88
193 "repeat" 'sh-repeat))
194 "Abbrev-table used in Shell-Script mode. See `sh-feature'.
195 Due to the internal workings of abbrev tables, the shell name symbol is
196 actually defined as the table for the like of \\[edit-abbrevs].")
200 (defvar sh-mode-syntax-table
201 '((csh eval identity sh)
202 (sh eval sh-mode-syntax-table ()
203 ;; #'s meanings depend on context which can't be expressed here
217 (rc eval sh-mode-syntax-table sh
220 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
225 (let ((map (make-sparse-keymap)))
226 (define-key map "\C-c(" 'sh-function)
227 (define-key map "\C-c\C-w" 'sh-while)
228 (define-key map "\C-c\C-u" 'sh-until)
229 (define-key map "\C-c\C-t" 'sh-tmp-file)
230 (define-key map "\C-c\C-s" 'sh-select)
231 (define-key map "\C-c\C-r" 'sh-repeat)
232 (define-key map "\C-c\C-o" 'sh-while-getopts)
233 (define-key map "\C-c\C-l" 'sh-indexed-loop)
234 (define-key map "\C-c\C-i" 'sh-if)
235 (define-key map "\C-c\C-f" 'sh-for)
236 (define-key map "\C-c\C-c" 'sh-case)
238 (define-key map "=" 'sh-assignment)
239 (define-key map "\C-c+" 'sh-add)
240 (define-key map "\C-\M-x" 'sh-execute-region)
241 (define-key map "\C-c\C-x" 'executable-interpret)
242 (define-key map "<" 'sh-maybe-here-document)
243 (define-key map "(" 'skeleton-pair-insert-maybe)
244 (define-key map "{" 'skeleton-pair-insert-maybe)
245 (define-key map "[" 'skeleton-pair-insert-maybe)
246 (define-key map "'" 'skeleton-pair-insert-maybe)
247 (define-key map "`" 'skeleton-pair-insert-maybe)
248 (define-key map "\"" 'skeleton-pair-insert-maybe)
250 (define-key map "\t" 'sh-indent-line)
251 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
252 map (current-global-map))
253 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
254 map (current-global-map))
255 (substitute-key-definition 'delete-backward-char
256 'backward-delete-char-untabify
257 map (current-global-map))
258 (define-key map "\C-c:" 'sh-set-shell)
259 (substitute-key-definition 'beginning-of-defun
260 'sh-beginning-of-compound-command
261 map (current-global-map))
262 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
263 map (current-global-map))
264 (substitute-key-definition 'forward-sentence 'sh-end-of-command
265 map (current-global-map))
266 (define-key map [menu-bar insert]
267 (cons "Insert" (make-sparse-keymap "Insert")))
268 (define-key map [menu-bar insert sh-while]
269 '("While loop" . sh-while))
270 (define-key map [menu-bar insert sh-until]
271 '("Until loop" . sh-until))
272 (define-key map [menu-bar insert sh-tmp-file]
273 '("Temporary file" . sh-tmp-file))
274 (define-key map [menu-bar insert sh-select]
275 '("Select statement" . sh-select))
276 (define-key map [menu-bar insert sh-repeat]
277 '("Repeat loop" . sh-repeat))
278 (define-key map [menu-bar insert sh-while-getopts]
279 '("Options loop" . sh-while-getopts))
280 (define-key map [menu-bar insert sh-indexed-loop]
281 '("Indexed loop" . sh-indexed-loop))
282 (define-key map [menu-bar insert sh-if]
283 '("If statement" . sh-if))
284 (define-key map [menu-bar insert sh-for]
285 '("For loop" . sh-for))
286 (define-key map [menu-bar insert sh-case]
287 '("Case statement" . sh-case))
289 "Keymap used in Shell-Script mode.")
293 (defvar sh-dynamic-complete-functions
294 '(shell-dynamic-complete-environment-variable
295 shell-dynamic-complete-command
296 comint-dynamic-complete-filename)
297 "*Functions for doing TAB dynamic completion.")
300 (defvar sh-require-final-newline
303 (rc eval . require-final-newline)
304 (sh eval . require-final-newline))
305 "*Value of `require-final-newline' in Shell-Script mode buffers.
309 (defvar sh-comment-prefix
310 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
311 (rc eval identity csh)
312 (sh . "\\(^\\|[ \t|&;()]\\)"))
313 "*Regexp matching what may come before a comment `#'.
314 This must contain one \\(grouping\\) since it is the basis for fontifying
315 comments as well as for `comment-start-skip'.
319 (defvar sh-assignment-regexp
320 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
321 ;; actually spaces are only supported in let/(( ... ))
322 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
323 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
324 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
325 "*Regexp for the variable name and what may follow in an assignment.
326 First grouping matches the variable name. This is upto and including the `='
327 sign. See `sh-feature'.")
330 (defvar sh-indentation 4
331 "The width for further indentation in Shell-Script mode.")
334 (defvar sh-remember-variable-min 3
335 "*Don't remember variables less than this length for completing reads.")
338 (defvar sh-header-marker nil
339 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
340 That command is also used for setting this variable.")
343 (defvar sh-beginning-of-command
344 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
345 "*Regexp to determine the beginning of a shell command.
346 The actual command starts at the beginning of the second \\(grouping\\).")
349 (defvar sh-end-of-command
350 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
351 "*Regexp to determine the end of a shell command.
352 The actual command ends at the end of the first \\(grouping\\).")
356 (defvar sh-here-document-word "EOF"
357 "Word to delimit here documents.")
362 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
366 '((bash eval sh-append posix
367 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
368 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
369 "suspend" "typeset" "unalias")
371 ;; The next entry is only used for defining the others
372 (bourne eval sh-append shell
373 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
376 (csh eval sh-append shell
377 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
378 "setenv" "source" "time" "unalias" "unhash")
380 (dtksh eval identity wksh)
382 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
383 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
385 (jsh eval sh-append sh
386 "bg" "fg" "jobs" "kill" "stop" "suspend")
388 (jcsh eval sh-append csh
389 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
391 (ksh88 eval sh-append bourne
392 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
393 "typeset" "unalias" "whence")
395 (oash eval sh-append sh
396 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
397 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
398 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
399 "wmtitle" "wrefresh")
401 (pdksh eval sh-append ksh88
404 (posix eval sh-append sh
407 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
410 (sh eval sh-append bourne
411 "hash" "test" "type")
413 ;; The next entry is only used for defining the others
414 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
416 (wksh eval sh-append ksh88
419 (zsh eval sh-append ksh88
420 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
421 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
422 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
423 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
424 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
426 "*List of all shell builtins for completing read and fontification.
427 Note that on some systems not all builtins are available or some are
428 implemented as aliases. See `sh-feature'.")
432 (defvar sh-leading-keywords
435 (es "true" "unwind-protect" "whatis")
439 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
440 "*List of keywords that may be immediately followed by a builtin or keyword.
441 Given some confusion between keywords and builtins depending on shell and
442 system, the distinction here has been based on whether they influence the
443 flow of control or syntax. See `sh-feature'.")
446 (defvar sh-other-keywords
447 '((bash eval sh-append bourne
450 ;; The next entry is only used for defining the others
451 (bourne eval sh-append shell
452 "done" "esac" "fi" "for" "function" "in" "return")
454 (csh eval sh-append shell
455 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
456 "if" "logout" "onintr" "repeat" "switch" "then" "while")
458 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
459 "return" "throw" "while")
461 (ksh88 eval sh-append bourne
464 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
467 ;; The next entry is only used for defining the others
468 (shell "break" "case" "continue" "exec" "exit")
470 (zsh eval sh-append bash
472 "*List of keywords not in `sh-leading-keywords'.
478 '((bash eval sh-append sh
479 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
480 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
481 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
482 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
483 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
484 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
485 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
486 "SECONDS" "SHLVL" "TMOUT" "UID")
488 (csh eval sh-append shell
489 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
490 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
491 "shell" "status" "time" "verbose")
493 (es eval sh-append shell
494 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
495 "pid" "prompt" "signals")
497 (jcsh eval sh-append csh
500 (ksh88 eval sh-append sh
501 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
502 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
505 (oash eval sh-append sh
506 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
508 (rc eval sh-append shell
509 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
512 (sh eval sh-append shell
513 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
515 ;; The next entry is only used for defining the others
516 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
517 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
518 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
519 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
521 (tcsh eval sh-append csh
522 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
523 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
524 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
525 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
526 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
527 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
528 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
529 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
532 (zsh eval sh-append ksh88
533 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
534 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
535 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
536 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
537 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
538 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
539 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
540 "List of all shell variables available for completing read.
545 (defvar sh-font-lock-keywords
546 '((csh eval sh-append shell
547 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
548 font-lock-variable-name-face))
550 (es eval sh-append executable-font-lock-keywords
551 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
552 font-lock-variable-name-face))
554 (rc eval identity es)
556 (sh eval sh-append shell
557 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
558 font-lock-variable-name-face))
560 ;; The next entry is only used for defining the others
561 (shell eval sh-append executable-font-lock-keywords
562 '("\\\\." 0 font-lock-string-face)
563 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
564 font-lock-variable-name-face)))
565 "*Rules for highlighting shell scripts. See `sh-feature'.")
567 (defvar sh-font-lock-keywords-1
568 '((sh "[ \t]in[ \t]"))
569 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
571 (defvar sh-font-lock-keywords-2 ()
572 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
575 ;; mode-command and utility functions
579 "Major mode for editing shell scripts.
580 This mode works for many shells, since they all have roughly the same syntax,
581 as far as commands, arguments, variables, pipes, comments etc. are concerned.
582 Unless the file's magic number indicates the shell, your usual shell is
583 assumed. Since filenames rarely give a clue, they are not further analyzed.
585 This mode adapts to the variations between shells (see `sh-set-shell') by
586 means of an inheritance based feature lookup (see `sh-feature'). This
587 mechanism applies to all variables (including skeletons) that pertain to
588 shell-specific features.
590 The default style of this mode is that of Rosenblatt's Korn shell book.
591 The syntax of the statements varies with the shell being used. The
592 following commands are available, based on the current shell's syntax:
594 \\[sh-case] case statement
596 \\[sh-function] function definition
597 \\[sh-if] if statement
598 \\[sh-indexed-loop] indexed loop from 1 to n
599 \\[sh-while-getopts] while getopts loop
600 \\[sh-repeat] repeat loop
601 \\[sh-select] select loop
602 \\[sh-until] until loop
603 \\[sh-while] while loop
605 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
606 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
607 \\[sh-end-of-command] Go to end of successive commands.
608 \\[sh-beginning-of-command] Go to beginning of successive commands.
609 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
610 \\[sh-execute-region] Have optional header and region be executed in a subshell.
612 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
614 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
616 If you generally program a shell different from your login shell you can
617 set `sh-shell-path' accordingly. If your shell's file name doesn't correctly
618 indicate what shell it is use `sh-alias-alist' to translate.
620 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
621 with your script for an edit-interpret-debug cycle."
623 (kill-all-local-variables)
624 (use-local-map sh-mode-map)
625 (make-local-variable 'indent-line-function)
626 (make-local-variable 'indent-region-function)
627 (make-local-variable 'skeleton-end-hook)
628 (make-local-variable 'paragraph-start)
629 (make-local-variable 'paragraph-separate)
630 (make-local-variable 'comment-start)
631 (make-local-variable 'comment-start-skip)
632 (make-local-variable 'require-final-newline)
633 (make-local-variable 'sh-header-marker)
634 (make-local-variable 'sh-shell-path)
635 (make-local-variable 'sh-shell)
636 (make-local-variable 'skeleton-pair-alist)
637 (make-local-variable 'skeleton-pair-filter)
638 (make-local-variable 'comint-dynamic-complete-functions)
639 (make-local-variable 'comint-prompt-regexp)
640 (make-local-variable 'font-lock-keywords)
641 (make-local-variable 'font-lock-defaults)
642 (make-local-variable 'skeleton-filter)
643 (make-local-variable 'skeleton-newline-indent-rigidly)
644 (make-local-variable 'process-environment)
645 (setq major-mode 'sh-mode
646 mode-name "Shell-script"
647 indent-line-function 'sh-indent-line
648 ;; not very clever, but enables wrapping skeletons around regions
649 indent-region-function (lambda (b e)
652 (skip-syntax-backward "-")
655 (skip-syntax-backward "-")
656 (indent-rigidly b (point) sh-indentation)))
657 skeleton-end-hook (lambda ()
658 (or (eolp) (newline) (indent-relative)))
659 ! paragraph-start (concat page-delimiter "\\|$")
660 paragraph-separate paragraph-start
662 comint-dynamic-complete-functions sh-dynamic-complete-functions
663 ;; we can't look if previous line ended with `\'
664 comint-prompt-regexp "^[ \t]*"
666 '((sh-font-lock-keywords
667 sh-font-lock-keywords-1
668 sh-font-lock-keywords-2)
670 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
671 skeleton-pair-alist '((?` _ ?`))
672 skeleton-pair-filter 'sh-quoted-p
673 skeleton-further-elements '((< '(- (min sh-indentation
675 skeleton-filter 'sh-feature
676 skeleton-newline-indent-rigidly t)
677 ;; parse or insert magic number for exec() and set all variables depending
678 ;; on the shell thus determined
679 (goto-char (point-min))
681 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
684 (run-hooks 'sh-mode-hook))
686 (defalias 'shell-script-mode 'sh-mode)
689 (defun sh-font-lock-keywords (&optional keywords)
690 "Function to get simple fontification based on `sh-font-lock-keywords'.
691 This adds rules for comments and assignments."
692 (sh-feature sh-font-lock-keywords
694 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
695 2 font-lock-comment-face t)
696 (,(sh-feature sh-assignment-regexp)
697 1 font-lock-variable-name-face)
701 (defun sh-font-lock-keywords-1 (&optional builtins)
702 "Function to get better fontification including keywords."
703 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
705 (sh-feature sh-leading-keywords)
709 (append (sh-feature sh-leading-keywords)
710 (sh-feature sh-other-keywords))
713 (sh-font-lock-keywords
715 `((,(concat keywords "[ \t]+\\)?\\("
716 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
718 (2 font-lock-keyword-face nil t)
719 (6 font-lock-function-name-face))
720 ,@(sh-feature sh-font-lock-keywords-2)))
721 (,(concat keywords "\\)\\>")
722 2 font-lock-keyword-face)
723 ,@(sh-feature sh-font-lock-keywords-1)))))
725 (defun sh-font-lock-keywords-2 ()
726 "Function to get better fontification including keywords and builtins."
727 (sh-font-lock-keywords-1 t))
730 (defun sh-set-shell (shell)
731 "Set this buffer's shell to SHELL (a string).
732 Makes this script executable via `executable-set-magic'.
733 Calls the value of `sh-set-shell-hook' if set."
734 (interactive (list (completing-read "Name or path of shell: "
735 interpreter-mode-alist
736 (lambda (x) (eq (cdr x) 'sh-mode)))))
737 (if (eq this-command 'sh-set-shell)
739 (setq this-command 'executable-set-magic))
740 (setq sh-shell (intern (file-name-nondirectory shell))
741 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
743 sh-shell-path (executable-set-magic shell (sh-feature sh-shell-arg))
744 local-abbrev-table (sh-feature sh-abbrevs)
745 require-final-newline (sh-feature sh-require-final-newline)
746 font-lock-keywords nil ; force resetting
747 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
748 mode-line-process (format "[%s]" sh-shell)
749 process-environment (default-value 'process-environment)
750 shell (sh-feature sh-variables))
751 (set-syntax-table (sh-feature sh-mode-syntax-table))
752 (setq font-lock-syntax-table)
754 (while (search-forward "=" nil t)
757 (sh-remember-variable (car shell))
758 (setq shell (cdr shell)))
759 (and (boundp 'font-lock-mode)
761 (font-lock-mode (font-lock-mode 0)))
762 (run-hooks 'sh-set-shell-hook))
766 (defun sh-feature (list &optional function)
767 "Index ALIST by the current shell.
768 If ALIST isn't a list where every element is a cons, it is returned as is.
769 Else indexing follows an inheritance logic which works in two ways:
771 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
772 the alist contains no value for the current shell.
774 - If the value thus looked up is a list starting with `eval' its `cdr' is
775 first evaluated. If that is also a list and the first argument is a
776 symbol in ALIST it is not evaluated, but rather recursively looked up in
777 ALIST to allow the function called to define the value for one shell to be
778 derived from another shell. While calling the function, is the car of the
779 alist element is the current shell.
780 The value thus determined is physically replaced into the alist.
782 Optional FUNCTION is applied to the determined value and the result is cached
786 (while (and l (consp (car l)))
790 (cdr (assoc (setq function (cons sh-shell function)) list)))
791 (let ((sh-shell sh-shell)
794 (not (setq elt (assq sh-shell list))))
795 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
796 (if (and (consp (setq val (cdr elt)))
797 (eq (car val) 'eval))
800 (eval (if (consp (setq val (cdr val)))
801 (let ((sh-shell (car (cdr val)))
803 (if (assq sh-shell list)
812 (setq sh-shell (car function)
813 val (funcall (cdr function) val))))))
818 (defun sh-abbrevs (ancestor &rest list)
819 "Iff it isn't, define the current shell as abbrev table and fill that.
820 Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
821 table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
822 according to the remaining arguments NAMEi EXPANSIONi ...
823 EXPANSION may be either a string or a skeleton command."
824 (or (if (boundp sh-shell)
825 (symbol-value sh-shell))
828 (nconc list ancestor))
829 (define-abbrev-table sh-shell ())
830 (if (vectorp ancestor)
831 (mapatoms (lambda (atom)
833 (define-abbrev (symbol-value sh-shell)
836 (symbol-function atom))))
839 (define-abbrev (symbol-value sh-shell)
841 (if (stringp (car (cdr list)))
844 (if (symbolp (car (cdr list)))
846 (setq list (cdr (cdr list)))))
847 (symbol-value sh-shell)))
850 (defun sh-mode-syntax-table (table &rest list)
851 "Copy TABLE and set syntax for succesive CHARs according to strings S."
852 (setq table (copy-syntax-table table))
854 (modify-syntax-entry (car list) (car (cdr list)) table)
855 (setq list (cdr (cdr list))))
859 (defun sh-append (ancestor &rest list)
860 "Return list composed of first argument (a list) physically appended to rest."
861 (nconc list ancestor))
864 (defun sh-modify (skeleton &rest list)
865 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
866 (setq skeleton (copy-sequence skeleton))
868 (setcar (or (nthcdr (car list) skeleton)
869 (error "Index %d out of bounds" (car list)))
871 (setq list (nthcdr 2 list)))
875 (defun sh-indent-line ()
876 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
877 Lines containing only comments are considered empty."
879 (let ((previous (save-excursion
882 (back-to-indentation)
884 (eq (following-char) ?#))))
888 (indent-to (if (eq this-command 'newline-and-indent)
890 (if (< (current-column)
891 (setq current (progn (back-to-indentation)
893 (if (eolp) previous 0)
894 (delete-region (point)
895 (progn (beginning-of-line) (point)))
897 (max previous (* (1+ (/ current sh-indentation))
899 (* (1+ (/ current sh-indentation)) sh-indentation))))))
900 (if (< (current-column) (current-indentation))
901 (skip-chars-forward " \t"))))
904 (defun sh-execute-region (start end &optional flag)
905 "Pass optional header and region to a subshell for noninteractive execution.
906 The working directory is that of the buffer, and only environment variables
907 are already set which is why you can mark a header within the script.
909 With a positive prefix ARG, instead of sending region, define header from
910 beginning of buffer to point. With a negative prefix ARG, instead of sending
911 region, clear header."
914 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
918 (let (buffer-undo-list)
919 (goto-char sh-header-marker)
920 (append-to-buffer (current-buffer) start end)
921 (shell-command-on-region (point-min)
922 (setq end (+ sh-header-marker
925 (delete-region sh-header-marker end)))
926 (shell-command-on-region start end (concat sh-shell-path " -")))))
929 (defun sh-remember-variable (var)
930 "Make VARIABLE available for future completing reads in this buffer."
931 (or (< (length var) sh-remember-variable-min)
933 (setq process-environment (cons (concat var "=") process-environment)))
938 (defun sh-quoted-p ()
939 "Is point preceded by an odd number of backslashes?"
940 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
942 ;; statement syntax-commands for various shells
944 ;; You are welcome to add the syntax or even completely new statements as
945 ;; appropriate for your favorite shell.
947 (define-skeleton sh-case
948 "Insert a case/switch statement. See `sh-feature'."
950 "switch( " str " )" \n
951 > "case " (read-string "pattern: ") ?: \n
954 ( "other pattern, %s: "
964 "switch( " str " ) {" \n
965 > "case " (read-string "pattern: ") \n
967 ( "other pattern, %s: "
976 > (read-string "pattern: ") ?\) \n
979 ( "other pattern, %s: "
987 (put 'sh-case 'menu-enable '(sh-feature sh-case))
991 (define-skeleton sh-for
992 "Insert a for loop. See `sh-feature'."
993 (csh eval sh-modify sh
998 (es eval sh-modify rc
1000 (rc eval sh-modify sh
1004 (sh "Index variable: "
1005 "for " str " in " _ "; do" \n
1006 > _ | ?$ & (sh-remember-variable str) \n
1011 (define-skeleton sh-indexed-loop
1012 "Insert an indexed loop from 1 to n. See `sh-feature'."
1013 (bash eval identity posix)
1014 (csh "Index variable: "
1016 "while( $" str " <= " (read-string "upper limit: ") " )" \n
1020 (es eval sh-modify rc
1022 (ksh88 "Index variable: "
1023 "integer " str "=0" \n
1024 "while (( ( " str " += 1 ) <= "
1025 (read-string "upper limit: ")
1027 > _ ?$ (sh-remember-variable str) \n
1029 (posix "Index variable: "
1031 "while [ $" str " -le "
1032 (read-string "upper limit: ")
1035 str ?= (sh-add (sh-remember-variable str) 1) \n
1037 (rc "Index variable: "
1038 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
1039 (read-string "upper limit: ")
1040 "; i++ ) print i }'}) {" \n
1041 > _ ?$ (sh-remember-variable str) \n
1043 (sh "Index variable: "
1044 "for " str " in `awk 'BEGIN { for( i=1; i<="
1045 (read-string "upper limit: ")
1046 "; i++ ) print i }'`; do" \n
1047 > _ ?$ (sh-remember-variable str) \n
1051 (defun sh-add (var delta)
1052 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1054 (list (completing-read "Variable: "
1055 (mapcar (lambda (var)
1056 (substring var 0 (string-match "=" var)))
1057 process-environment))
1058 (prefix-numeric-value current-prefix-arg)))
1059 (insert (sh-feature '((bash . "$[ ")
1065 (sh-remember-variable var)
1066 (if (< delta 0) " - " " + ")
1067 (number-to-string (abs delta))
1068 (sh-feature '((bash . " ]")
1077 (define-skeleton sh-function
1078 "Insert a function definition. See `sh-feature'."
1079 (bash eval sh-modify ksh88
1082 "function " str " {" \n
1085 (rc eval sh-modify ksh88
1094 (define-skeleton sh-if
1095 "Insert an if statement. See `sh-feature'."
1097 "if( " str " ) then" \n
1099 ( "other condition, %s: "
1100 < "else if( " str " ) then" \n
1107 "if { " str " } {" \n
1109 ( "other condition, %s: "
1110 < "} { " str " } {" \n
1116 (rc eval sh-modify csh
1118 8 '( "other condition, %s: "
1119 < "} else if( " str " ) {" \n
1124 '(setq input (sh-feature sh-test))
1125 "if " str "; then" \n
1127 ( "other condition, %s: "
1128 < "elif " str "; then" \n
1137 (define-skeleton sh-repeat
1138 "Insert a repeat loop definition. See `sh-feature'."
1144 "repeat " str "; do"\n
1147 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1151 (define-skeleton sh-select
1152 "Insert a select statement. See `sh-feature'."
1153 (ksh88 "Index variable: "
1154 "select " str " in " _ "; do" \n
1157 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1161 (define-skeleton sh-tmp-file
1162 "Insert code to setup temporary file handling. See `sh-feature'."
1163 (bash eval identity ksh88)
1164 (csh (file-name-nondirectory (buffer-file-name))
1165 "set tmp = /tmp/" str ".$$" \n
1167 (and (goto-char (point-max))
1171 "rm $tmp* >&/dev/null" >)
1172 (es (file-name-nondirectory (buffer-file-name))
1173 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1175 > "rm $tmp^* >[2]/dev/null" \n
1181 (ksh88 eval sh-modify sh
1183 (rc (file-name-nondirectory (buffer-file-name))
1184 "tmp = /tmp/" str ".$pid" \n
1185 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1186 (sh (file-name-nondirectory (buffer-file-name))
1187 "TMP=/tmp/" str ".$$" \n
1188 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1192 (define-skeleton sh-until
1193 "Insert an until loop. See `sh-feature'."
1195 '(setq input (sh-feature sh-test))
1196 "until " str "; do" \n
1199 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1203 (define-skeleton sh-while
1204 "Insert a while loop. See `sh-feature'."
1205 (csh eval sh-modify sh
1209 (es eval sh-modify rc
1212 (rc eval sh-modify csh
1216 '(setq input (sh-feature sh-test))
1217 "while " str "; do" \n
1223 (define-skeleton sh-while-getopts
1224 "Insert a while getopts loop. See `sh-feature'.
1225 Prompts for an options string which consists of letters for each recognized
1226 option followed by a colon `:' if the option accepts an argument."
1227 (bash eval sh-modify sh
1231 > "switch( \"$1\" )" \n
1232 '(setq input '("- x" . 2))
1235 < "case " '(eval str)
1236 '(if (string-match " +" str)
1237 (setq v1 (substring str (match-end 0))
1238 str (substring str 0 (match-beginning 0)))
1241 > "set " v1 & " = $2" | -4 & _ \n
1242 (if v1 "shift") & \n
1252 (ksh88 eval sh-modify sh
1256 (posix eval sh-modify sh
1257 18 "$(basename $0)")
1259 "while getopts :" str " OPT; do" \n
1262 '(setq v1 (append (vconcat str) nil))
1263 ( (prog1 (if v1 (char-to-string (car v1)))
1264 (if (eq (nth 1 v1) ?:)
1265 (setq v1 (nthcdr 2 v1)
1269 < str "|+" str ?\) \n
1273 > "echo" " \"usage: " "`basename $0`"
1274 "[ +-" '(setq v1 (point)) str
1276 (while (search-backward ":" v1 t)
1277 (replace-match " arg][ +-" t t)))
1278 (if (eq (preceding-char) ?-) -5)
1283 "shift " (sh-add "OPTIND" -1)))
1284 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1288 (defun sh-assignment (arg)
1289 "Remember preceding identifier for future completion and do self-insert."
1291 (self-insert-command arg)
1293 (sh-remember-variable
1295 (if (re-search-forward (sh-feature sh-assignment-regexp)
1297 (beginning-of-line 1))
1299 (match-string 1))))))
1303 (defun sh-maybe-here-document (arg)
1304 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1305 The document is bounded by `sh-here-document-word'."
1307 (self-insert-command (prefix-numeric-value arg))
1309 (not (eq (char-after (- (point) 2)) last-command-char))
1314 (insert sh-here-document-word)
1315 (or (eolp) (looking-at "[ \t]") (insert ? ))
1321 (save-excursion (insert ?\n sh-here-document-word)))))
1324 ;; various other commands
1326 (autoload 'comint-dynamic-complete "comint"
1327 "Dynamically perform completion at point." t)
1329 (autoload 'shell-dynamic-complete-command "shell"
1330 "Dynamically complete the command at point." t)
1332 (autoload 'comint-dynamic-complete-filename "comint"
1333 "Dynamically complete the filename at point." t)
1335 (autoload 'shell-dynamic-complete-environment-variable "shell"
1336 "Dynamically complete the environment variable at point." t)
1340 (defun sh-newline-and-indent ()
1341 "Strip unquoted whitespace, insert newline, and indent like current line."
1343 (indent-to (prog1 (current-indentation)
1344 (delete-region (point)
1346 (or (zerop (skip-chars-backward " \t"))
1354 (defun sh-beginning-of-command ()
1355 "Move point to successive beginnings of commands."
1357 (if (re-search-backward sh-beginning-of-command nil t)
1358 (goto-char (match-beginning 2))))
1361 (defun sh-end-of-command ()
1362 "Move point to successive ends of commands."
1364 (if (re-search-forward sh-end-of-command nil t)
1365 (goto-char (match-end 1))))
1367 ;; sh-script.el ends here