1 ;;; sh-script.el --- shell-script editing commands for Emacs
2 ;; Copyright (C) 1993, 1994, 1995, 1996 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
48 (defvar sh-ancestor-alist
65 "*Alist showing the direct ancestor of various shells.
66 This is the basis for `sh-feature'. See also `sh-alias-alist'.
67 By default we have the following three hierarchies:
70 jcsh C Shell with Job Control
72 itcsh ? Toronto C Shell
77 jsh Bourne Shell with Job Control
78 bash GNU Bourne Again Shell
81 dtksh CDE Desktop Korn Shell
82 pdksh Public Domain Korn Shell
83 wksh Window Korn Shell
85 oash SCO OA (curses) Shell
86 posix IEEE 1003.2 Shell Standard
90 (defvar sh-alias-alist
91 (nconc (if (eq system-type 'linux)
97 "*Alist for transforming shell names to what they really are.
98 Use this where the name of the executable doesn't correspond to the type of
102 (defvar sh-shell-file (or (getenv "SHELL") "/bin/sh")
103 "*The executable file name for the shell being programmed.")
109 (ksh88 eval progn nil (if (file-exists-p "/etc/suid_profile") nil "-p"))
114 "*Single argument string for the magic number. See `sh-feature'.")
118 (defun sh-canonicalize-shell (shell)
119 "Convert a shell name SHELL to the one we should handle it as."
121 (setq shell (intern shell)))
122 (or (cdr (assq shell sh-alias-alist))
125 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
126 "The shell being programmed. This is set by \\[sh-set-shell].")
128 ;;; I turned off this feature because it doesn't permit typing commands
129 ;;; in the usual way without help.
130 ;;;(defvar sh-abbrevs
131 ;;; '((csh eval sh-abbrevs shell
132 ;;; "switch" 'sh-case
133 ;;; "getopts" 'sh-while-getopts)
135 ;;; (es eval sh-abbrevs shell
136 ;;; "function" 'sh-function)
138 ;;; (ksh88 eval sh-abbrevs sh
139 ;;; "select" 'sh-select)
141 ;;; (rc eval sh-abbrevs shell
143 ;;; "function" 'sh-function)
145 ;;; (sh eval sh-abbrevs shell
147 ;;; "function" 'sh-function
148 ;;; "until" 'sh-until
149 ;;; "getopts" 'sh-while-getopts)
151 ;;; ;; The next entry is only used for defining the others
152 ;;; (shell "for" sh-for
153 ;;; "loop" sh-indexed-loop
155 ;;; "tmpfile" sh-tmp-file
156 ;;; "while" sh-while)
158 ;;; (zsh eval sh-abbrevs ksh88
159 ;;; "repeat" 'sh-repeat))
160 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
161 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
162 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
166 (defvar sh-mode-syntax-table
167 '((csh eval identity sh)
168 (sh eval sh-mode-syntax-table ()
169 ;; #'s meanings depend on context which can't be expressed here
183 (rc eval sh-mode-syntax-table sh
186 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
191 (let ((map (make-sparse-keymap))
192 (menu-map (make-sparse-keymap "Insert")))
193 (define-key map "\C-c(" 'sh-function)
194 (define-key map "\C-c\C-w" 'sh-while)
195 (define-key map "\C-c\C-u" 'sh-until)
196 (define-key map "\C-c\C-t" 'sh-tmp-file)
197 (define-key map "\C-c\C-s" 'sh-select)
198 (define-key map "\C-c\C-r" 'sh-repeat)
199 (define-key map "\C-c\C-o" 'sh-while-getopts)
200 (define-key map "\C-c\C-l" 'sh-indexed-loop)
201 (define-key map "\C-c\C-i" 'sh-if)
202 (define-key map "\C-c\C-f" 'sh-for)
203 (define-key map "\C-c\C-c" 'sh-case)
205 (define-key map "=" 'sh-assignment)
206 (define-key map "\C-c+" 'sh-add)
207 (define-key map "\C-\M-x" 'sh-execute-region)
208 (define-key map "\C-c\C-x" 'executable-interpret)
209 (define-key map "<" 'sh-maybe-here-document)
210 (define-key map "(" 'skeleton-pair-insert-maybe)
211 (define-key map "{" 'skeleton-pair-insert-maybe)
212 (define-key map "[" 'skeleton-pair-insert-maybe)
213 (define-key map "'" 'skeleton-pair-insert-maybe)
214 (define-key map "`" 'skeleton-pair-insert-maybe)
215 (define-key map "\"" 'skeleton-pair-insert-maybe)
217 (define-key map "\t" 'sh-indent-line)
218 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
219 map (current-global-map))
220 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
221 map (current-global-map))
222 (substitute-key-definition 'delete-backward-char
223 'backward-delete-char-untabify
224 map (current-global-map))
225 (define-key map "\C-c:" 'sh-set-shell)
226 (substitute-key-definition 'beginning-of-defun
227 'sh-beginning-of-compound-command
228 map (current-global-map))
229 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
230 map (current-global-map))
231 (substitute-key-definition 'forward-sentence 'sh-end-of-command
232 map (current-global-map))
233 (define-key map [menu-bar insert] (cons "Insert" menu-map))
234 (define-key menu-map [sh-while] '("While Loop" . sh-while))
235 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
236 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
237 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
238 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
239 (define-key menu-map [sh-while-getopts]
240 '("Options Loop" . sh-while-getopts))
241 (define-key menu-map [sh-indexed-loop]
242 '("Indexed Loop" . sh-indexed-loop))
243 (define-key menu-map [sh-if] '("If Statement" . sh-if))
244 (define-key menu-map [sh-for] '("For Loop" . sh-for))
245 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
247 "Keymap used in Shell-Script mode.")
251 (defvar sh-dynamic-complete-functions
252 '(shell-dynamic-complete-environment-variable
253 shell-dynamic-complete-command
254 comint-dynamic-complete-filename)
255 "*Functions for doing TAB dynamic completion.")
258 (defvar sh-require-final-newline
261 (rc eval . require-final-newline)
262 (sh eval . require-final-newline))
263 "*Value of `require-final-newline' in Shell-Script mode buffers.
267 (defvar sh-comment-prefix
268 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
269 (rc eval identity csh)
270 (sh . "\\(^\\|[ \t|&;()]\\)"))
271 "*Regexp matching what may come before a comment `#'.
272 This must contain one \\(grouping\\) since it is the basis for fontifying
273 comments as well as for `comment-start-skip'.
277 (defvar sh-assignment-regexp
278 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
279 ;; actually spaces are only supported in let/(( ... ))
280 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
281 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
282 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
283 "*Regexp for the variable name and what may follow in an assignment.
284 First grouping matches the variable name. This is upto and including the `='
285 sign. See `sh-feature'.")
288 (defvar sh-indentation 4
289 "The width for further indentation in Shell-Script mode.")
292 (defvar sh-remember-variable-min 3
293 "*Don't remember variables less than this length for completing reads.")
296 (defvar sh-header-marker nil
297 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
298 That command is also used for setting this variable.")
301 (defvar sh-beginning-of-command
302 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
303 "*Regexp to determine the beginning of a shell command.
304 The actual command starts at the beginning of the second \\(grouping\\).")
307 (defvar sh-end-of-command
308 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
309 "*Regexp to determine the end of a shell command.
310 The actual command ends at the end of the first \\(grouping\\).")
314 (defvar sh-here-document-word "EOF"
315 "Word to delimit here documents.")
320 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
324 '((bash eval sh-append posix
325 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
326 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
327 "suspend" "typeset" "unalias")
329 ;; The next entry is only used for defining the others
330 (bourne eval sh-append shell
331 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
334 (csh eval sh-append shell
335 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
336 "setenv" "source" "time" "unalias" "unhash")
338 (dtksh eval identity wksh)
340 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
341 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
343 (jsh eval sh-append sh
344 "bg" "fg" "jobs" "kill" "stop" "suspend")
346 (jcsh eval sh-append csh
347 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
349 (ksh88 eval sh-append bourne
350 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
351 "typeset" "unalias" "whence")
353 (oash eval sh-append sh
354 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
355 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
356 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
357 "wmtitle" "wrefresh")
359 (pdksh eval sh-append ksh88
362 (posix eval sh-append sh
365 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
368 (sh eval sh-append bourne
369 "hash" "test" "type")
371 ;; The next entry is only used for defining the others
372 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
374 (wksh eval sh-append ksh88
377 (zsh eval sh-append ksh88
378 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
379 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
380 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
381 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
382 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
384 "*List of all shell builtins for completing read and fontification.
385 Note that on some systems not all builtins are available or some are
386 implemented as aliases. See `sh-feature'.")
390 (defvar sh-leading-keywords
393 (es "true" "unwind-protect" "whatis")
397 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
398 "*List of keywords that may be immediately followed by a builtin or keyword.
399 Given some confusion between keywords and builtins depending on shell and
400 system, the distinction here has been based on whether they influence the
401 flow of control or syntax. See `sh-feature'.")
404 (defvar sh-other-keywords
405 '((bash eval sh-append bourne
408 ;; The next entry is only used for defining the others
409 (bourne eval sh-append shell
410 "done" "esac" "fi" "for" "function" "in" "return")
412 (csh eval sh-append shell
413 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
414 "if" "logout" "onintr" "repeat" "switch" "then" "while")
416 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
417 "return" "throw" "while")
419 (ksh88 eval sh-append bourne
422 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
425 ;; The next entry is only used for defining the others
426 (shell "break" "case" "continue" "exec" "exit")
428 (zsh eval sh-append bash
430 "*List of keywords not in `sh-leading-keywords'.
436 '((bash eval sh-append sh
437 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
438 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
439 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
440 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
441 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
442 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
443 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
444 "SECONDS" "SHLVL" "TMOUT" "UID")
446 (csh eval sh-append shell
447 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
448 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
449 "shell" "status" "time" "verbose")
451 (es eval sh-append shell
452 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
453 "pid" "prompt" "signals")
455 (jcsh eval sh-append csh
458 (ksh88 eval sh-append sh
459 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
460 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
463 (oash eval sh-append sh
464 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
466 (rc eval sh-append shell
467 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
470 (sh eval sh-append shell
471 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
473 ;; The next entry is only used for defining the others
474 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
475 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
476 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
477 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
479 (tcsh eval sh-append csh
480 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
481 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
482 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
483 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
484 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
485 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
486 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
487 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
490 (zsh eval sh-append ksh88
491 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
492 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
493 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
494 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
495 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
496 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
497 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
498 "List of all shell variables available for completing read.
503 (defvar sh-font-lock-keywords
504 '((csh eval sh-append shell
505 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
506 font-lock-variable-name-face))
508 (es eval sh-append executable-font-lock-keywords
509 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
510 font-lock-variable-name-face))
512 (rc eval identity es)
514 (sh eval sh-append shell
515 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
516 font-lock-variable-name-face))
518 ;; The next entry is only used for defining the others
519 (shell eval sh-append executable-font-lock-keywords
520 '("\\\\." 0 font-lock-string-face)
521 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
522 font-lock-variable-name-face)))
523 "*Rules for highlighting shell scripts. See `sh-feature'.")
525 (defvar sh-font-lock-keywords-1
527 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
529 (defvar sh-font-lock-keywords-2 ()
530 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
532 (defvar sh-font-lock-keywords-only t
533 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
534 Default value is `t' because Emacs' syntax is not expressive enough to
535 detect that $# does not start a comment. Thus comments are fontified by
536 regexp which means that a single apostrophe in a comment turns everything
537 upto the next one or end of buffer into a string.")
539 ;; mode-command and utility functions
543 "Major mode for editing shell scripts.
544 This mode works for many shells, since they all have roughly the same syntax,
545 as far as commands, arguments, variables, pipes, comments etc. are concerned.
546 Unless the file's magic number indicates the shell, your usual shell is
547 assumed. Since filenames rarely give a clue, they are not further analyzed.
549 This mode adapts to the variations between shells (see `sh-set-shell') by
550 means of an inheritance based feature lookup (see `sh-feature'). This
551 mechanism applies to all variables (including skeletons) that pertain to
552 shell-specific features.
554 The default style of this mode is that of Rosenblatt's Korn shell book.
555 The syntax of the statements varies with the shell being used. The
556 following commands are available, based on the current shell's syntax:
558 \\[sh-case] case statement
560 \\[sh-function] function definition
561 \\[sh-if] if statement
562 \\[sh-indexed-loop] indexed loop from 1 to n
563 \\[sh-while-getopts] while getopts loop
564 \\[sh-repeat] repeat loop
565 \\[sh-select] select loop
566 \\[sh-until] until loop
567 \\[sh-while] while loop
569 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
570 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
571 \\[sh-end-of-command] Go to end of successive commands.
572 \\[sh-beginning-of-command] Go to beginning of successive commands.
573 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
574 \\[sh-execute-region] Have optional header and region be executed in a subshell.
576 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
578 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
580 If you generally program a shell different from your login shell you can
581 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
582 indicate what shell it is use `sh-alias-alist' to translate.
584 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
585 with your script for an edit-interpret-debug cycle."
587 (kill-all-local-variables)
588 (use-local-map sh-mode-map)
589 (make-local-variable 'indent-line-function)
590 (make-local-variable 'indent-region-function)
591 (make-local-variable 'skeleton-end-hook)
592 (make-local-variable 'paragraph-start)
593 (make-local-variable 'paragraph-separate)
594 (make-local-variable 'comment-start)
595 (make-local-variable 'comment-start-skip)
596 (make-local-variable 'require-final-newline)
597 (make-local-variable 'sh-header-marker)
598 (make-local-variable 'sh-shell-file)
599 (make-local-variable 'sh-shell)
600 (make-local-variable 'skeleton-pair-alist)
601 (make-local-variable 'skeleton-pair-filter)
602 (make-local-variable 'comint-dynamic-complete-functions)
603 (make-local-variable 'comint-prompt-regexp)
604 (make-local-variable 'font-lock-keywords)
605 (make-local-variable 'font-lock-defaults)
606 (make-local-variable 'skeleton-filter)
607 (make-local-variable 'skeleton-newline-indent-rigidly)
608 (make-local-variable 'process-environment)
609 (setq major-mode 'sh-mode
610 mode-name "Shell-script"
611 indent-line-function 'sh-indent-line
612 ;; not very clever, but enables wrapping skeletons around regions
613 indent-region-function (lambda (b e)
616 (skip-syntax-backward "-")
619 (skip-syntax-backward "-")
620 (indent-rigidly b (point) sh-indentation)))
621 skeleton-end-hook (lambda ()
622 (or (eolp) (newline) (indent-relative)))
623 paragraph-start (concat page-delimiter "\\|$")
624 paragraph-separate paragraph-start
626 comint-dynamic-complete-functions sh-dynamic-complete-functions
627 ;; we can't look if previous line ended with `\'
628 comint-prompt-regexp "^[ \t]*"
630 `((sh-font-lock-keywords
631 sh-font-lock-keywords-1
632 sh-font-lock-keywords-2)
633 ,sh-font-lock-keywords-only
635 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
636 skeleton-pair-alist '((?` _ ?`))
637 skeleton-pair-filter 'sh-quoted-p
638 skeleton-further-elements '((< '(- (min sh-indentation
640 skeleton-filter 'sh-feature
641 skeleton-newline-indent-rigidly t)
642 ;; parse or insert magic number for exec() and set all variables depending
643 ;; on the shell thus determined
644 (goto-char (point-min))
646 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
649 (run-hooks 'sh-mode-hook))
651 (defalias 'shell-script-mode 'sh-mode)
654 (defun sh-font-lock-keywords (&optional keywords)
655 "Function to get simple fontification based on `sh-font-lock-keywords'.
656 This adds rules for comments and assignments."
657 (sh-feature sh-font-lock-keywords
659 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
660 2 font-lock-comment-face t)
661 (,(sh-feature sh-assignment-regexp)
662 1 font-lock-variable-name-face)
666 (defun sh-font-lock-keywords-1 (&optional builtins)
667 "Function to get better fontification including keywords."
668 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
670 (sh-feature sh-leading-keywords)
674 (append (sh-feature sh-leading-keywords)
675 (sh-feature sh-other-keywords))
678 (sh-font-lock-keywords
680 `((,(concat keywords "[ \t]+\\)?\\("
681 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
683 (2 font-lock-keyword-face nil t)
684 (6 font-lock-function-name-face))
685 ,@(sh-feature sh-font-lock-keywords-2)))
686 (,(concat keywords "\\)\\>")
687 2 font-lock-keyword-face)
688 ,@(sh-feature sh-font-lock-keywords-1)))))
690 (defun sh-font-lock-keywords-2 ()
691 "Function to get better fontification including keywords and builtins."
692 (sh-font-lock-keywords-1 t))
695 (defun sh-set-shell (shell)
696 "Set this buffer's shell to SHELL (a string).
697 Makes this script executable via `executable-set-magic'.
698 Calls the value of `sh-set-shell-hook' if set."
699 (interactive (list (completing-read "Name or path of shell: "
700 interpreter-mode-alist
701 (lambda (x) (eq (cdr x) 'sh-mode)))))
702 (if (eq this-command 'sh-set-shell)
704 (setq this-command 'executable-set-magic))
705 (setq sh-shell (intern (file-name-nondirectory shell))
706 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
708 sh-shell-file (executable-set-magic shell (sh-feature sh-shell-arg))
709 ;;; local-abbrev-table (sh-feature sh-abbrevs)
710 require-final-newline (sh-feature sh-require-final-newline)
711 font-lock-keywords nil ; force resetting
712 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
713 mode-line-process (format "[%s]" sh-shell)
714 process-environment (default-value 'process-environment)
715 shell (sh-feature sh-variables))
716 (set-syntax-table (sh-feature sh-mode-syntax-table))
717 (setq font-lock-syntax-table)
719 (while (search-forward "=" nil t)
722 (sh-remember-variable (car shell))
723 (setq shell (cdr shell)))
724 (and (boundp 'font-lock-mode)
726 (font-lock-mode (font-lock-mode 0)))
727 (run-hooks 'sh-set-shell-hook))
731 (defun sh-feature (list &optional function)
732 "Index ALIST by the current shell.
733 If ALIST isn't a list where every element is a cons, it is returned as is.
734 Else indexing follows an inheritance logic which works in two ways:
736 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
737 the alist contains no value for the current shell.
739 - If the value thus looked up is a list starting with `eval' its `cdr' is
740 first evaluated. If that is also a list and the first argument is a
741 symbol in ALIST it is not evaluated, but rather recursively looked up in
742 ALIST to allow the function called to define the value for one shell to be
743 derived from another shell. While calling the function, is the car of the
744 alist element is the current shell.
745 The value thus determined is physically replaced into the alist.
747 Optional FUNCTION is applied to the determined value and the result is cached
751 (while (and l (consp (car l)))
755 (cdr (assoc (setq function (cons sh-shell function)) list)))
756 (let ((sh-shell sh-shell)
759 (not (setq elt (assq sh-shell list))))
760 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
761 (if (and (consp (setq val (cdr elt)))
762 (eq (car val) 'eval))
765 (eval (if (consp (setq val (cdr val)))
766 (let ((sh-shell (car (cdr val)))
768 (if (assq sh-shell list)
777 (setq sh-shell (car function)
778 val (funcall (cdr function) val))))))
783 ;;; I commented this out because nobody calls it -- rms.
784 ;;;(defun sh-abbrevs (ancestor &rest list)
785 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
786 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
787 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
788 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
789 ;;;EXPANSION may be either a string or a skeleton command."
790 ;;; (or (if (boundp sh-shell)
791 ;;; (symbol-value sh-shell))
793 ;;; (if (listp ancestor)
794 ;;; (nconc list ancestor))
795 ;;; (define-abbrev-table sh-shell ())
796 ;;; (if (vectorp ancestor)
797 ;;; (mapatoms (lambda (atom)
799 ;;; (define-abbrev (symbol-value sh-shell)
800 ;;; (symbol-name atom)
801 ;;; (symbol-value atom)
802 ;;; (symbol-function atom))))
805 ;;; (define-abbrev (symbol-value sh-shell)
807 ;;; (if (stringp (car (cdr list)))
810 ;;; (if (symbolp (car (cdr list)))
811 ;;; (car (cdr list))))
812 ;;; (setq list (cdr (cdr list)))))
813 ;;; (symbol-value sh-shell)))
816 (defun sh-mode-syntax-table (table &rest list)
817 "Copy TABLE and set syntax for successive CHARs according to strings S."
818 (setq table (copy-syntax-table table))
820 (modify-syntax-entry (car list) (car (cdr list)) table)
821 (setq list (cdr (cdr list))))
825 (defun sh-append (ancestor &rest list)
826 "Return list composed of first argument (a list) physically appended to rest."
827 (nconc list ancestor))
830 (defun sh-modify (skeleton &rest list)
831 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
832 (setq skeleton (copy-sequence skeleton))
834 (setcar (or (nthcdr (car list) skeleton)
835 (error "Index %d out of bounds" (car list)))
837 (setq list (nthcdr 2 list)))
841 (defun sh-indent-line ()
842 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
843 Lines containing only comments are considered empty."
845 (let ((previous (save-excursion
848 (back-to-indentation)
850 (eq (following-char) ?#))))
854 (indent-to (if (eq this-command 'newline-and-indent)
856 (if (< (current-column)
857 (setq current (progn (back-to-indentation)
859 (if (eolp) previous 0)
860 (delete-region (point)
861 (progn (beginning-of-line) (point)))
863 (max previous (* (1+ (/ current sh-indentation))
865 (* (1+ (/ current sh-indentation)) sh-indentation))))))
866 (if (< (current-column) (current-indentation))
867 (skip-chars-forward " \t"))))
870 (defun sh-execute-region (start end &optional flag)
871 "Pass optional header and region to a subshell for noninteractive execution.
872 The working directory is that of the buffer, and only environment variables
873 are already set which is why you can mark a header within the script.
875 With a positive prefix ARG, instead of sending region, define header from
876 beginning of buffer to point. With a negative prefix ARG, instead of sending
877 region, clear header."
880 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
884 (let (buffer-undo-list)
885 (goto-char sh-header-marker)
886 (append-to-buffer (current-buffer) start end)
887 (shell-command-on-region (point-min)
888 (setq end (+ sh-header-marker
891 (delete-region sh-header-marker end)))
892 (shell-command-on-region start end (concat sh-shell-file " -")))))
895 (defun sh-remember-variable (var)
896 "Make VARIABLE available for future completing reads in this buffer."
897 (or (< (length var) sh-remember-variable-min)
899 (setq process-environment (cons (concat var "=") process-environment)))
904 (defun sh-quoted-p ()
905 "Is point preceded by an odd number of backslashes?"
906 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
908 ;; statement syntax-commands for various shells
910 ;; You are welcome to add the syntax or even completely new statements as
911 ;; appropriate for your favorite shell.
913 (define-skeleton sh-case
914 "Insert a case/switch statement. See `sh-feature'."
916 "switch( " str " )" \n
917 > "case " (read-string "pattern: ") ?: \n
920 ( "other pattern, %s: "
930 "switch( " str " ) {" \n
931 > "case " (read-string "pattern: ") \n
933 ( "other pattern, %s: "
942 > (read-string "pattern: ") ?\) \n
945 ( "other pattern, %s: "
953 (put 'sh-case 'menu-enable '(sh-feature sh-case))
957 (define-skeleton sh-for
958 "Insert a for loop. See `sh-feature'."
959 (csh eval sh-modify sh
964 (es eval sh-modify rc
966 (rc eval sh-modify sh
970 (sh "Index variable: "
971 "for " str " in " _ "; do" \n
972 > _ | ?$ & (sh-remember-variable str) \n
977 (define-skeleton sh-indexed-loop
978 "Insert an indexed loop from 1 to n. See `sh-feature'."
979 (bash eval identity posix)
980 (csh "Index variable: "
982 "while( $" str " <= " (read-string "upper limit: ") " )" \n
986 (es eval sh-modify rc
988 (ksh88 "Index variable: "
989 "integer " str "=0" \n
990 "while (( ( " str " += 1 ) <= "
991 (read-string "upper limit: ")
993 > _ ?$ (sh-remember-variable str) \n
995 (posix "Index variable: "
997 "while [ $" str " -le "
998 (read-string "upper limit: ")
1001 str ?= (sh-add (sh-remember-variable str) 1) \n
1003 (rc "Index variable: "
1004 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
1005 (read-string "upper limit: ")
1006 "; i++ ) print i }'}) {" \n
1007 > _ ?$ (sh-remember-variable str) \n
1009 (sh "Index variable: "
1010 "for " str " in `awk 'BEGIN { for( i=1; i<="
1011 (read-string "upper limit: ")
1012 "; i++ ) print i }'`; do" \n
1013 > _ ?$ (sh-remember-variable str) \n
1017 (defun sh-add (var delta)
1018 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1020 (list (completing-read "Variable: "
1021 (mapcar (lambda (var)
1022 (substring var 0 (string-match "=" var)))
1023 process-environment))
1024 (prefix-numeric-value current-prefix-arg)))
1025 (insert (sh-feature '((bash . "$[ ")
1031 (sh-remember-variable var)
1032 (if (< delta 0) " - " " + ")
1033 (number-to-string (abs delta))
1034 (sh-feature '((bash . " ]")
1043 (define-skeleton sh-function
1044 "Insert a function definition. See `sh-feature'."
1045 (bash eval sh-modify ksh88
1048 "function " str " {" \n
1051 (rc eval sh-modify ksh88
1060 (define-skeleton sh-if
1061 "Insert an if statement. See `sh-feature'."
1063 "if( " str " ) then" \n
1065 ( "other condition, %s: "
1066 < "else if( " str " ) then" \n
1073 "if { " str " } {" \n
1075 ( "other condition, %s: "
1076 < "} { " str " } {" \n
1082 (rc eval sh-modify csh
1084 8 '( "other condition, %s: "
1085 < "} else if( " str " ) {" \n
1090 '(setq input (sh-feature sh-test))
1091 "if " str "; then" \n
1093 ( "other condition, %s: "
1094 < "elif " str "; then" \n
1103 (define-skeleton sh-repeat
1104 "Insert a repeat loop definition. See `sh-feature'."
1110 "repeat " str "; do"\n
1113 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1117 (define-skeleton sh-select
1118 "Insert a select statement. See `sh-feature'."
1119 (ksh88 "Index variable: "
1120 "select " str " in " _ "; do" \n
1123 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1127 (define-skeleton sh-tmp-file
1128 "Insert code to setup temporary file handling. See `sh-feature'."
1129 (bash eval identity ksh88)
1130 (csh (file-name-nondirectory (buffer-file-name))
1131 "set tmp = /tmp/" str ".$$" \n
1133 (and (goto-char (point-max))
1137 "rm $tmp* >&/dev/null" >)
1138 (es (file-name-nondirectory (buffer-file-name))
1139 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1141 > "rm $tmp^* >[2]/dev/null" \n
1147 (ksh88 eval sh-modify sh
1149 (rc (file-name-nondirectory (buffer-file-name))
1150 "tmp = /tmp/" str ".$pid" \n
1151 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1152 (sh (file-name-nondirectory (buffer-file-name))
1153 "TMP=/tmp/" str ".$$" \n
1154 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1158 (define-skeleton sh-until
1159 "Insert an until loop. See `sh-feature'."
1161 '(setq input (sh-feature sh-test))
1162 "until " str "; do" \n
1165 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1169 (define-skeleton sh-while
1170 "Insert a while loop. See `sh-feature'."
1171 (csh eval sh-modify sh
1175 (es eval sh-modify rc
1178 (rc eval sh-modify csh
1182 '(setq input (sh-feature sh-test))
1183 "while " str "; do" \n
1189 (define-skeleton sh-while-getopts
1190 "Insert a while getopts loop. See `sh-feature'.
1191 Prompts for an options string which consists of letters for each recognized
1192 option followed by a colon `:' if the option accepts an argument."
1193 (bash eval sh-modify sh
1197 > "switch( \"$1\" )" \n
1198 '(setq input '("- x" . 2))
1201 < "case " '(eval str)
1202 '(if (string-match " +" str)
1203 (setq v1 (substring str (match-end 0))
1204 str (substring str 0 (match-beginning 0)))
1207 > "set " v1 & " = $2" | -4 & _ \n
1208 (if v1 "shift") & \n
1218 (ksh88 eval sh-modify sh
1222 (posix eval sh-modify sh
1223 18 "$(basename $0)")
1225 "while getopts :" str " OPT; do" \n
1228 '(setq v1 (append (vconcat str) nil))
1229 ( (prog1 (if v1 (char-to-string (car v1)))
1230 (if (eq (nth 1 v1) ?:)
1231 (setq v1 (nthcdr 2 v1)
1235 < str "|+" str ?\) \n
1239 > "echo" " \"usage: " "`basename $0`"
1240 "[ +-" '(setq v1 (point)) str
1242 (while (search-backward ":" v1 t)
1243 (replace-match " arg][ +-" t t)))
1244 (if (eq (preceding-char) ?-) -5)
1249 "shift " (sh-add "OPTIND" -1)))
1250 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1254 (defun sh-assignment (arg)
1255 "Remember preceding identifier for future completion and do self-insert."
1257 (self-insert-command arg)
1259 (sh-remember-variable
1261 (if (re-search-forward (sh-feature sh-assignment-regexp)
1263 (beginning-of-line 1))
1265 (match-string 1))))))
1269 (defun sh-maybe-here-document (arg)
1270 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1271 The document is bounded by `sh-here-document-word'."
1273 (self-insert-command (prefix-numeric-value arg))
1275 (not (eq (char-after (- (point) 2)) last-command-char))
1280 (insert sh-here-document-word)
1281 (or (eolp) (looking-at "[ \t]") (insert ? ))
1287 (save-excursion (insert ?\n sh-here-document-word)))))
1290 ;; various other commands
1292 (autoload 'comint-dynamic-complete "comint"
1293 "Dynamically perform completion at point." t)
1295 (autoload 'shell-dynamic-complete-command "shell"
1296 "Dynamically complete the command at point." t)
1298 (autoload 'comint-dynamic-complete-filename "comint"
1299 "Dynamically complete the filename at point." t)
1301 (autoload 'shell-dynamic-complete-environment-variable "shell"
1302 "Dynamically complete the environment variable at point." t)
1306 (defun sh-newline-and-indent ()
1307 "Strip unquoted whitespace, insert newline, and indent like current line."
1309 (indent-to (prog1 (current-indentation)
1310 (delete-region (point)
1312 (or (zerop (skip-chars-backward " \t"))
1320 (defun sh-beginning-of-command ()
1321 "Move point to successive beginnings of commands."
1323 (if (re-search-backward sh-beginning-of-command nil t)
1324 (goto-char (match-beginning 2))))
1327 (defun sh-end-of-command ()
1328 "Move point to successive ends of commands."
1330 (if (re-search-forward sh-end-of-command nil t)
1331 (goto-char (match-end 1))))
1333 (provide 'sh-script)
1334 ;; sh-script.el ends here