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 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
36 ;; - Variables in `"' strings aren't fontified because there's no way of
37 ;; syntactically distinguishing those from `'' strings.
41 ;; page 1: variables and settings
42 ;; page 2: mode-command and utility functions
43 ;; page 3: statement syntax-commands for various shells
44 ;; page 4: various other commands
50 ;; Autoload cookie deleted here because it made loaddefs.el fail to load.
52 (or (assoc "sh" interpreter-mode-alist)
55 ;; - that have a suffix .sh, .csh or .shar (shell archive)
56 ;; - that contain ressources for the various shells
57 ;; - startup files for X11
58 (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)
60 interpreter-mode-alist
61 (nconc '(("ash" . sh-mode)
78 interpreter-mode-alist)))
81 (defvar sh-ancestor-alist
98 "*Alist showing the direct ancestor of various shells.
99 This is the basis for `sh-feature'. See also `sh-alias-alist'.
100 By default we have the following three hierarchies:
103 jcsh C Shell with Job Control
105 itcsh ? Toronto C Shell
110 jsh Bourne Shell with Job Control
111 bash GNU Bourne Again Shell
114 dtksh CDE Desktop Korn Shell
115 pdksh Public Domain Korn Shell
116 wksh Window Korn Shell
118 oash SCO OA (curses) Shell
119 posix IEEE 1003.2 Shell Standard
123 (defvar sh-alias-alist
124 (nconc (if (eq system-type 'linux)
128 ;; for the time being
131 "*Alist for transforming shell names to what they really are.
132 Use this where the name of the executable doesn't correspond to the type of
133 shell it really is.")
136 (defvar sh-shell-path (or (getenv "SHELL") "/bin/sh")
137 "*The executable of the shell being programmed.")
143 (ksh88 eval progn nil (if (file-exists-p "/etc/suid_profile") nil "-p"))
148 "*Single argument string for the magic number. See `sh-feature'.")
152 (defvar sh-shell (or (cdr (assq (intern (file-name-nondirectory sh-shell-path))
154 (intern (file-name-nondirectory sh-shell-path)))
155 "The shell being programmed. This is set by \\[sh-set-shell].")
160 '((csh eval sh-abbrevs shell
162 "getopts" 'sh-while-getopts)
164 (es eval sh-abbrevs shell
165 "function" 'sh-function)
167 (ksh88 eval sh-abbrevs sh
170 (rc eval sh-abbrevs shell
172 "function" 'sh-function)
174 (sh eval sh-abbrevs shell
176 "function" 'sh-function
178 "getopts" 'sh-while-getopts)
180 ;; The next entry is only used for defining the others
182 "loop" sh-indexed-loop
184 "tmpfile" sh-tmp-file
187 (zsh eval sh-abbrevs ksh88
188 "repeat" 'sh-repeat))
189 "Abbrev-table used in Shell-Script mode. See `sh-feature'.
190 Due to the internal workings of abbrev tables, the shell name symbol is
191 actually defined as the table for the like of \\[edit-abbrevs].")
195 (defvar sh-mode-syntax-table
196 '((csh eval identity sh)
197 (sh eval sh-mode-syntax-table ()
198 ;; #'s meanings depend on context which can't be expressed here
212 (rc eval sh-mode-syntax-table sh
215 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
220 (let ((map (make-sparse-keymap))
221 (menu-map (make-sparse-keymap "Insert")))
222 (define-key map "\C-c(" 'sh-function)
223 (define-key map "\C-c\C-w" 'sh-while)
224 (define-key map "\C-c\C-u" 'sh-until)
225 (define-key map "\C-c\C-t" 'sh-tmp-file)
226 (define-key map "\C-c\C-s" 'sh-select)
227 (define-key map "\C-c\C-r" 'sh-repeat)
228 (define-key map "\C-c\C-o" 'sh-while-getopts)
229 (define-key map "\C-c\C-l" 'sh-indexed-loop)
230 (define-key map "\C-c\C-i" 'sh-if)
231 (define-key map "\C-c\C-f" 'sh-for)
232 (define-key map "\C-c\C-c" 'sh-case)
234 (define-key map "=" 'sh-assignment)
235 (define-key map "\C-c+" 'sh-add)
236 (define-key map "\C-\M-x" 'sh-execute-region)
237 (define-key map "\C-c\C-x" 'executable-interpret)
238 (define-key map "<" 'sh-maybe-here-document)
239 (define-key map "(" 'skeleton-pair-insert-maybe)
240 (define-key map "{" 'skeleton-pair-insert-maybe)
241 (define-key map "[" 'skeleton-pair-insert-maybe)
242 (define-key map "'" 'skeleton-pair-insert-maybe)
243 (define-key map "`" 'skeleton-pair-insert-maybe)
244 (define-key map "\"" 'skeleton-pair-insert-maybe)
246 (define-key map "\t" 'sh-indent-line)
247 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
248 map (current-global-map))
249 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
250 map (current-global-map))
251 (substitute-key-definition 'delete-backward-char
252 'backward-delete-char-untabify
253 map (current-global-map))
254 (define-key map "\C-c:" 'sh-set-shell)
255 (substitute-key-definition 'beginning-of-defun
256 'sh-beginning-of-compound-command
257 map (current-global-map))
258 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
259 map (current-global-map))
260 (substitute-key-definition 'forward-sentence 'sh-end-of-command
261 map (current-global-map))
262 (define-key map [menu-bar insert] (cons "Insert" menu-map))
263 (define-key menu-map [sh-while] '("While Loop" . sh-while))
264 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
265 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
266 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
267 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
268 (define-key menu-map [sh-while-getopts]
269 '("Options Loop" . sh-while-getopts))
270 (define-key menu-map [sh-indexed-loop]
271 '("Indexed Loop" . sh-indexed-loop))
272 (define-key menu-map [sh-if] '("If Statement" . sh-if))
273 (define-key menu-map [sh-for] '("For Loop" . sh-for))
274 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
276 "Keymap used in Shell-Script mode.")
280 (defvar sh-dynamic-complete-functions
281 '(shell-dynamic-complete-environment-variable
282 shell-dynamic-complete-command
283 comint-dynamic-complete-filename)
284 "*Functions for doing TAB dynamic completion.")
287 (defvar sh-require-final-newline
290 (rc eval . require-final-newline)
291 (sh eval . require-final-newline))
292 "*Value of `require-final-newline' in Shell-Script mode buffers.
296 (defvar sh-comment-prefix
297 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
298 (rc eval identity csh)
299 (sh . "\\(^\\|[ \t|&;()]\\)"))
300 "*Regexp matching what may come before a comment `#'.
301 This must contain one \\(grouping\\) since it is the basis for fontifying
302 comments as well as for `comment-start-skip'.
306 (defvar sh-assignment-regexp
307 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
308 ;; actually spaces are only supported in let/(( ... ))
309 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
310 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
311 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
312 "*Regexp for the variable name and what may follow in an assignment.
313 First grouping matches the variable name. This is upto and including the `='
314 sign. See `sh-feature'.")
317 (defvar sh-indentation 4
318 "The width for further indentation in Shell-Script mode.")
321 (defvar sh-remember-variable-min 3
322 "*Don't remember variables less than this length for completing reads.")
325 (defvar sh-header-marker nil
326 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
327 That command is also used for setting this variable.")
330 (defvar sh-beginning-of-command
331 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
332 "*Regexp to determine the beginning of a shell command.
333 The actual command starts at the beginning of the second \\(grouping\\).")
336 (defvar sh-end-of-command
337 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
338 "*Regexp to determine the end of a shell command.
339 The actual command ends at the end of the first \\(grouping\\).")
343 (defvar sh-here-document-word "EOF"
344 "Word to delimit here documents.")
349 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
353 '((bash eval sh-append posix
354 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
355 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
356 "suspend" "typeset" "unalias")
358 ;; The next entry is only used for defining the others
359 (bourne eval sh-append shell
360 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
363 (csh eval sh-append shell
364 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
365 "setenv" "source" "time" "unalias" "unhash")
367 (dtksh eval identity wksh)
369 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
370 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
372 (jsh eval sh-append sh
373 "bg" "fg" "jobs" "kill" "stop" "suspend")
375 (jcsh eval sh-append csh
376 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
378 (ksh88 eval sh-append bourne
379 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
380 "typeset" "unalias" "whence")
382 (oash eval sh-append sh
383 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
384 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
385 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
386 "wmtitle" "wrefresh")
388 (pdksh eval sh-append ksh88
391 (posix eval sh-append sh
394 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
397 (sh eval sh-append bourne
398 "hash" "test" "type")
400 ;; The next entry is only used for defining the others
401 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
403 (wksh eval sh-append ksh88
406 (zsh eval sh-append ksh88
407 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
408 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
409 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
410 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
411 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
413 "*List of all shell builtins for completing read and fontification.
414 Note that on some systems not all builtins are available or some are
415 implemented as aliases. See `sh-feature'.")
419 (defvar sh-leading-keywords
422 (es "true" "unwind-protect" "whatis")
426 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
427 "*List of keywords that may be immediately followed by a builtin or keyword.
428 Given some confusion between keywords and builtins depending on shell and
429 system, the distinction here has been based on whether they influence the
430 flow of control or syntax. See `sh-feature'.")
433 (defvar sh-other-keywords
434 '((bash eval sh-append bourne
437 ;; The next entry is only used for defining the others
438 (bourne eval sh-append shell
439 "done" "esac" "fi" "for" "function" "in" "return")
441 (csh eval sh-append shell
442 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
443 "if" "logout" "onintr" "repeat" "switch" "then" "while")
445 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
446 "return" "throw" "while")
448 (ksh88 eval sh-append bourne
451 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
454 ;; The next entry is only used for defining the others
455 (shell "break" "case" "continue" "exec" "exit")
457 (zsh eval sh-append bash
459 "*List of keywords not in `sh-leading-keywords'.
465 '((bash eval sh-append sh
466 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
467 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
468 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
469 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
470 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
471 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
472 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
473 "SECONDS" "SHLVL" "TMOUT" "UID")
475 (csh eval sh-append shell
476 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
477 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
478 "shell" "status" "time" "verbose")
480 (es eval sh-append shell
481 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
482 "pid" "prompt" "signals")
484 (jcsh eval sh-append csh
487 (ksh88 eval sh-append sh
488 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
489 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
492 (oash eval sh-append sh
493 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
495 (rc eval sh-append shell
496 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
499 (sh eval sh-append shell
500 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
502 ;; The next entry is only used for defining the others
503 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
504 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
505 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
506 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
508 (tcsh eval sh-append csh
509 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
510 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
511 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
512 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
513 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
514 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
515 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
516 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
519 (zsh eval sh-append ksh88
520 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
521 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
522 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
523 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
524 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
525 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
526 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
527 "List of all shell variables available for completing read.
532 (defvar sh-font-lock-keywords
533 '((csh eval sh-append shell
534 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
535 font-lock-variable-name-face))
537 (es eval sh-append executable-font-lock-keywords
538 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
539 font-lock-variable-name-face))
541 (rc eval identity es)
543 (sh eval sh-append shell
544 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
545 font-lock-variable-name-face))
547 ;; The next entry is only used for defining the others
548 (shell eval sh-append executable-font-lock-keywords
549 '("\\\\." 0 font-lock-string-face)
550 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
551 font-lock-variable-name-face)))
552 "*Rules for highlighting shell scripts. See `sh-feature'.")
554 (defvar sh-font-lock-keywords-1
556 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
558 (defvar sh-font-lock-keywords-2 ()
559 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
561 (defvar sh-font-lock-keywords-only t
562 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
563 Default value is `t' because Emacs' syntax is not expressive enough to
564 detect that $# does not start a comment. Thus comments are fontified by
565 regexp which means that a single apostrophe in a comment turns everything
566 upto the next one or end of buffer into a string.")
568 ;; mode-command and utility functions
572 "Major mode for editing shell scripts.
573 This mode works for many shells, since they all have roughly the same syntax,
574 as far as commands, arguments, variables, pipes, comments etc. are concerned.
575 Unless the file's magic number indicates the shell, your usual shell is
576 assumed. Since filenames rarely give a clue, they are not further analyzed.
578 This mode adapts to the variations between shells (see `sh-set-shell') by
579 means of an inheritance based feature lookup (see `sh-feature'). This
580 mechanism applies to all variables (including skeletons) that pertain to
581 shell-specific features.
583 The default style of this mode is that of Rosenblatt's Korn shell book.
584 The syntax of the statements varies with the shell being used. The
585 following commands are available, based on the current shell's syntax:
587 \\[sh-case] case statement
589 \\[sh-function] function definition
590 \\[sh-if] if statement
591 \\[sh-indexed-loop] indexed loop from 1 to n
592 \\[sh-while-getopts] while getopts loop
593 \\[sh-repeat] repeat loop
594 \\[sh-select] select loop
595 \\[sh-until] until loop
596 \\[sh-while] while loop
598 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
599 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
600 \\[sh-end-of-command] Go to end of successive commands.
601 \\[sh-beginning-of-command] Go to beginning of successive commands.
602 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
603 \\[sh-execute-region] Have optional header and region be executed in a subshell.
605 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
607 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
609 If you generally program a shell different from your login shell you can
610 set `sh-shell-path' accordingly. If your shell's file name doesn't correctly
611 indicate what shell it is use `sh-alias-alist' to translate.
613 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
614 with your script for an edit-interpret-debug cycle."
616 (kill-all-local-variables)
617 (use-local-map sh-mode-map)
618 (make-local-variable 'indent-line-function)
619 (make-local-variable 'indent-region-function)
620 (make-local-variable 'skeleton-end-hook)
621 (make-local-variable 'paragraph-start)
622 (make-local-variable 'paragraph-separate)
623 (make-local-variable 'comment-start)
624 (make-local-variable 'comment-start-skip)
625 (make-local-variable 'require-final-newline)
626 (make-local-variable 'sh-header-marker)
627 (make-local-variable 'sh-shell-path)
628 (make-local-variable 'sh-shell)
629 (make-local-variable 'skeleton-pair-alist)
630 (make-local-variable 'skeleton-pair-filter)
631 (make-local-variable 'comint-dynamic-complete-functions)
632 (make-local-variable 'comint-prompt-regexp)
633 (make-local-variable 'font-lock-keywords)
634 (make-local-variable 'font-lock-defaults)
635 (make-local-variable 'skeleton-filter)
636 (make-local-variable 'skeleton-newline-indent-rigidly)
637 (make-local-variable 'process-environment)
638 (setq major-mode 'sh-mode
639 mode-name "Shell-script"
640 indent-line-function 'sh-indent-line
641 ;; not very clever, but enables wrapping skeletons around regions
642 indent-region-function (lambda (b e)
645 (skip-syntax-backward "-")
648 (skip-syntax-backward "-")
649 (indent-rigidly b (point) sh-indentation)))
650 skeleton-end-hook (lambda ()
651 (or (eolp) (newline) (indent-relative)))
652 paragraph-start (concat page-delimiter "\\|$")
653 paragraph-separate paragraph-start
655 comint-dynamic-complete-functions sh-dynamic-complete-functions
656 ;; we can't look if previous line ended with `\'
657 comint-prompt-regexp "^[ \t]*"
659 `((sh-font-lock-keywords
660 sh-font-lock-keywords-1
661 sh-font-lock-keywords-2)
662 ,sh-font-lock-keywords-only
664 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
665 skeleton-pair-alist '((?` _ ?`))
666 skeleton-pair-filter 'sh-quoted-p
667 skeleton-further-elements '((< '(- (min sh-indentation
669 skeleton-filter 'sh-feature
670 skeleton-newline-indent-rigidly t)
671 ;; parse or insert magic number for exec() and set all variables depending
672 ;; on the shell thus determined
673 (goto-char (point-min))
675 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
678 (run-hooks 'sh-mode-hook))
680 (defalias 'shell-script-mode 'sh-mode)
683 (defun sh-font-lock-keywords (&optional keywords)
684 "Function to get simple fontification based on `sh-font-lock-keywords'.
685 This adds rules for comments and assignments."
686 (sh-feature sh-font-lock-keywords
688 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
689 2 font-lock-comment-face t)
690 (,(sh-feature sh-assignment-regexp)
691 1 font-lock-variable-name-face)
695 (defun sh-font-lock-keywords-1 (&optional builtins)
696 "Function to get better fontification including keywords."
697 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
699 (sh-feature sh-leading-keywords)
703 (append (sh-feature sh-leading-keywords)
704 (sh-feature sh-other-keywords))
707 (sh-font-lock-keywords
709 `((,(concat keywords "[ \t]+\\)?\\("
710 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
712 (2 font-lock-keyword-face nil t)
713 (6 font-lock-function-name-face))
714 ,@(sh-feature sh-font-lock-keywords-2)))
715 (,(concat keywords "\\)\\>")
716 2 font-lock-keyword-face)
717 ,@(sh-feature sh-font-lock-keywords-1)))))
719 (defun sh-font-lock-keywords-2 ()
720 "Function to get better fontification including keywords and builtins."
721 (sh-font-lock-keywords-1 t))
724 (defun sh-set-shell (shell)
725 "Set this buffer's shell to SHELL (a string).
726 Makes this script executable via `executable-set-magic'.
727 Calls the value of `sh-set-shell-hook' if set."
728 (interactive (list (completing-read "Name or path of shell: "
729 interpreter-mode-alist
730 (lambda (x) (eq (cdr x) 'sh-mode)))))
731 (if (eq this-command 'sh-set-shell)
733 (setq this-command 'executable-set-magic))
734 (setq sh-shell (intern (file-name-nondirectory shell))
735 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
737 sh-shell-path (executable-set-magic shell (sh-feature sh-shell-arg))
738 local-abbrev-table (sh-feature sh-abbrevs)
739 require-final-newline (sh-feature sh-require-final-newline)
740 font-lock-keywords nil ; force resetting
741 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
742 mode-line-process (format "[%s]" sh-shell)
743 process-environment (default-value 'process-environment)
744 shell (sh-feature sh-variables))
745 (set-syntax-table (sh-feature sh-mode-syntax-table))
746 (setq font-lock-syntax-table)
748 (while (search-forward "=" nil t)
751 (sh-remember-variable (car shell))
752 (setq shell (cdr shell)))
753 (and (boundp 'font-lock-mode)
755 (font-lock-mode (font-lock-mode 0)))
756 (run-hooks 'sh-set-shell-hook))
760 (defun sh-feature (list &optional function)
761 "Index ALIST by the current shell.
762 If ALIST isn't a list where every element is a cons, it is returned as is.
763 Else indexing follows an inheritance logic which works in two ways:
765 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
766 the alist contains no value for the current shell.
768 - If the value thus looked up is a list starting with `eval' its `cdr' is
769 first evaluated. If that is also a list and the first argument is a
770 symbol in ALIST it is not evaluated, but rather recursively looked up in
771 ALIST to allow the function called to define the value for one shell to be
772 derived from another shell. While calling the function, is the car of the
773 alist element is the current shell.
774 The value thus determined is physically replaced into the alist.
776 Optional FUNCTION is applied to the determined value and the result is cached
780 (while (and l (consp (car l)))
784 (cdr (assoc (setq function (cons sh-shell function)) list)))
785 (let ((sh-shell sh-shell)
788 (not (setq elt (assq sh-shell list))))
789 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
790 (if (and (consp (setq val (cdr elt)))
791 (eq (car val) 'eval))
794 (eval (if (consp (setq val (cdr val)))
795 (let ((sh-shell (car (cdr val)))
797 (if (assq sh-shell list)
806 (setq sh-shell (car function)
807 val (funcall (cdr function) val))))))
812 (defun sh-abbrevs (ancestor &rest list)
813 "Iff it isn't, define the current shell as abbrev table and fill that.
814 Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
815 table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
816 according to the remaining arguments NAMEi EXPANSIONi ...
817 EXPANSION may be either a string or a skeleton command."
818 (or (if (boundp sh-shell)
819 (symbol-value sh-shell))
822 (nconc list ancestor))
823 (define-abbrev-table sh-shell ())
824 (if (vectorp ancestor)
825 (mapatoms (lambda (atom)
827 (define-abbrev (symbol-value sh-shell)
830 (symbol-function atom))))
833 (define-abbrev (symbol-value sh-shell)
835 (if (stringp (car (cdr list)))
838 (if (symbolp (car (cdr list)))
840 (setq list (cdr (cdr list)))))
841 (symbol-value sh-shell)))
844 (defun sh-mode-syntax-table (table &rest list)
845 "Copy TABLE and set syntax for succesive CHARs according to strings S."
846 (setq table (copy-syntax-table table))
848 (modify-syntax-entry (car list) (car (cdr list)) table)
849 (setq list (cdr (cdr list))))
853 (defun sh-append (ancestor &rest list)
854 "Return list composed of first argument (a list) physically appended to rest."
855 (nconc list ancestor))
858 (defun sh-modify (skeleton &rest list)
859 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
860 (setq skeleton (copy-sequence skeleton))
862 (setcar (or (nthcdr (car list) skeleton)
863 (error "Index %d out of bounds" (car list)))
865 (setq list (nthcdr 2 list)))
869 (defun sh-indent-line ()
870 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
871 Lines containing only comments are considered empty."
873 (let ((previous (save-excursion
876 (back-to-indentation)
878 (eq (following-char) ?#))))
882 (indent-to (if (eq this-command 'newline-and-indent)
884 (if (< (current-column)
885 (setq current (progn (back-to-indentation)
887 (if (eolp) previous 0)
888 (delete-region (point)
889 (progn (beginning-of-line) (point)))
891 (max previous (* (1+ (/ current sh-indentation))
893 (* (1+ (/ current sh-indentation)) sh-indentation))))))
894 (if (< (current-column) (current-indentation))
895 (skip-chars-forward " \t"))))
898 (defun sh-execute-region (start end &optional flag)
899 "Pass optional header and region to a subshell for noninteractive execution.
900 The working directory is that of the buffer, and only environment variables
901 are already set which is why you can mark a header within the script.
903 With a positive prefix ARG, instead of sending region, define header from
904 beginning of buffer to point. With a negative prefix ARG, instead of sending
905 region, clear header."
908 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
912 (let (buffer-undo-list)
913 (goto-char sh-header-marker)
914 (append-to-buffer (current-buffer) start end)
915 (shell-command-on-region (point-min)
916 (setq end (+ sh-header-marker
919 (delete-region sh-header-marker end)))
920 (shell-command-on-region start end (concat sh-shell-path " -")))))
923 (defun sh-remember-variable (var)
924 "Make VARIABLE available for future completing reads in this buffer."
925 (or (< (length var) sh-remember-variable-min)
927 (setq process-environment (cons (concat var "=") process-environment)))
932 (defun sh-quoted-p ()
933 "Is point preceded by an odd number of backslashes?"
934 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
936 ;; statement syntax-commands for various shells
938 ;; You are welcome to add the syntax or even completely new statements as
939 ;; appropriate for your favorite shell.
941 (define-skeleton sh-case
942 "Insert a case/switch statement. See `sh-feature'."
944 "switch( " str " )" \n
945 > "case " (read-string "pattern: ") ?: \n
948 ( "other pattern, %s: "
958 "switch( " str " ) {" \n
959 > "case " (read-string "pattern: ") \n
961 ( "other pattern, %s: "
970 > (read-string "pattern: ") ?\) \n
973 ( "other pattern, %s: "
981 (put 'sh-case 'menu-enable '(sh-feature sh-case))
985 (define-skeleton sh-for
986 "Insert a for loop. See `sh-feature'."
987 (csh eval sh-modify sh
992 (es eval sh-modify rc
994 (rc eval sh-modify sh
998 (sh "Index variable: "
999 "for " str " in " _ "; do" \n
1000 > _ | ?$ & (sh-remember-variable str) \n
1005 (define-skeleton sh-indexed-loop
1006 "Insert an indexed loop from 1 to n. See `sh-feature'."
1007 (bash eval identity posix)
1008 (csh "Index variable: "
1010 "while( $" str " <= " (read-string "upper limit: ") " )" \n
1014 (es eval sh-modify rc
1016 (ksh88 "Index variable: "
1017 "integer " str "=0" \n
1018 "while (( ( " str " += 1 ) <= "
1019 (read-string "upper limit: ")
1021 > _ ?$ (sh-remember-variable str) \n
1023 (posix "Index variable: "
1025 "while [ $" str " -le "
1026 (read-string "upper limit: ")
1029 str ?= (sh-add (sh-remember-variable str) 1) \n
1031 (rc "Index variable: "
1032 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
1033 (read-string "upper limit: ")
1034 "; i++ ) print i }'}) {" \n
1035 > _ ?$ (sh-remember-variable str) \n
1037 (sh "Index variable: "
1038 "for " str " in `awk 'BEGIN { for( i=1; i<="
1039 (read-string "upper limit: ")
1040 "; i++ ) print i }'`; do" \n
1041 > _ ?$ (sh-remember-variable str) \n
1045 (defun sh-add (var delta)
1046 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1048 (list (completing-read "Variable: "
1049 (mapcar (lambda (var)
1050 (substring var 0 (string-match "=" var)))
1051 process-environment))
1052 (prefix-numeric-value current-prefix-arg)))
1053 (insert (sh-feature '((bash . "$[ ")
1059 (sh-remember-variable var)
1060 (if (< delta 0) " - " " + ")
1061 (number-to-string (abs delta))
1062 (sh-feature '((bash . " ]")
1071 (define-skeleton sh-function
1072 "Insert a function definition. See `sh-feature'."
1073 (bash eval sh-modify ksh88
1076 "function " str " {" \n
1079 (rc eval sh-modify ksh88
1088 (define-skeleton sh-if
1089 "Insert an if statement. See `sh-feature'."
1091 "if( " str " ) then" \n
1093 ( "other condition, %s: "
1094 < "else if( " str " ) then" \n
1101 "if { " str " } {" \n
1103 ( "other condition, %s: "
1104 < "} { " str " } {" \n
1110 (rc eval sh-modify csh
1112 8 '( "other condition, %s: "
1113 < "} else if( " str " ) {" \n
1118 '(setq input (sh-feature sh-test))
1119 "if " str "; then" \n
1121 ( "other condition, %s: "
1122 < "elif " str "; then" \n
1131 (define-skeleton sh-repeat
1132 "Insert a repeat loop definition. See `sh-feature'."
1138 "repeat " str "; do"\n
1141 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1145 (define-skeleton sh-select
1146 "Insert a select statement. See `sh-feature'."
1147 (ksh88 "Index variable: "
1148 "select " str " in " _ "; do" \n
1151 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1155 (define-skeleton sh-tmp-file
1156 "Insert code to setup temporary file handling. See `sh-feature'."
1157 (bash eval identity ksh88)
1158 (csh (file-name-nondirectory (buffer-file-name))
1159 "set tmp = /tmp/" str ".$$" \n
1161 (and (goto-char (point-max))
1165 "rm $tmp* >&/dev/null" >)
1166 (es (file-name-nondirectory (buffer-file-name))
1167 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1169 > "rm $tmp^* >[2]/dev/null" \n
1175 (ksh88 eval sh-modify sh
1177 (rc (file-name-nondirectory (buffer-file-name))
1178 "tmp = /tmp/" str ".$pid" \n
1179 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1180 (sh (file-name-nondirectory (buffer-file-name))
1181 "TMP=/tmp/" str ".$$" \n
1182 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1186 (define-skeleton sh-until
1187 "Insert an until loop. See `sh-feature'."
1189 '(setq input (sh-feature sh-test))
1190 "until " str "; do" \n
1193 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1197 (define-skeleton sh-while
1198 "Insert a while loop. See `sh-feature'."
1199 (csh eval sh-modify sh
1203 (es eval sh-modify rc
1206 (rc eval sh-modify csh
1210 '(setq input (sh-feature sh-test))
1211 "while " str "; do" \n
1217 (define-skeleton sh-while-getopts
1218 "Insert a while getopts loop. See `sh-feature'.
1219 Prompts for an options string which consists of letters for each recognized
1220 option followed by a colon `:' if the option accepts an argument."
1221 (bash eval sh-modify sh
1225 > "switch( \"$1\" )" \n
1226 '(setq input '("- x" . 2))
1229 < "case " '(eval str)
1230 '(if (string-match " +" str)
1231 (setq v1 (substring str (match-end 0))
1232 str (substring str 0 (match-beginning 0)))
1235 > "set " v1 & " = $2" | -4 & _ \n
1236 (if v1 "shift") & \n
1246 (ksh88 eval sh-modify sh
1250 (posix eval sh-modify sh
1251 18 "$(basename $0)")
1253 "while getopts :" str " OPT; do" \n
1256 '(setq v1 (append (vconcat str) nil))
1257 ( (prog1 (if v1 (char-to-string (car v1)))
1258 (if (eq (nth 1 v1) ?:)
1259 (setq v1 (nthcdr 2 v1)
1263 < str "|+" str ?\) \n
1267 > "echo" " \"usage: " "`basename $0`"
1268 "[ +-" '(setq v1 (point)) str
1270 (while (search-backward ":" v1 t)
1271 (replace-match " arg][ +-" t t)))
1272 (if (eq (preceding-char) ?-) -5)
1277 "shift " (sh-add "OPTIND" -1)))
1278 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1282 (defun sh-assignment (arg)
1283 "Remember preceding identifier for future completion and do self-insert."
1285 (self-insert-command arg)
1287 (sh-remember-variable
1289 (if (re-search-forward (sh-feature sh-assignment-regexp)
1291 (beginning-of-line 1))
1293 (match-string 1))))))
1297 (defun sh-maybe-here-document (arg)
1298 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1299 The document is bounded by `sh-here-document-word'."
1301 (self-insert-command (prefix-numeric-value arg))
1303 (not (eq (char-after (- (point) 2)) last-command-char))
1308 (insert sh-here-document-word)
1309 (or (eolp) (looking-at "[ \t]") (insert ? ))
1315 (save-excursion (insert ?\n sh-here-document-word)))))
1318 ;; various other commands
1320 (autoload 'comint-dynamic-complete "comint"
1321 "Dynamically perform completion at point." t)
1323 (autoload 'shell-dynamic-complete-command "shell"
1324 "Dynamically complete the command at point." t)
1326 (autoload 'comint-dynamic-complete-filename "comint"
1327 "Dynamically complete the filename at point." t)
1329 (autoload 'shell-dynamic-complete-environment-variable "shell"
1330 "Dynamically complete the environment variable at point." t)
1334 (defun sh-newline-and-indent ()
1335 "Strip unquoted whitespace, insert newline, and indent like current line."
1337 (indent-to (prog1 (current-indentation)
1338 (delete-region (point)
1340 (or (zerop (skip-chars-backward " \t"))
1348 (defun sh-beginning-of-command ()
1349 "Move point to successive beginnings of commands."
1351 (if (re-search-backward sh-beginning-of-command nil t)
1352 (goto-char (match-beginning 2))))
1355 (defun sh-end-of-command ()
1356 "Move point to successive ends of commands."
1358 (if (re-search-forward sh-end-of-command nil t)
1359 (goto-char (match-end 1))))
1361 (provide 'sh-script)
1362 ;; sh-script.el ends here