1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 1994, 1995, 1996 by Free Software Foundation, Inc.
5 ;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
8 ;; Keywords: languages, unix
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30 ;; as various derivatives are supported and easily derived from. Structured
31 ;; statements can be inserted with one command or abbrev. Completion is
32 ;; available for filenames, variables known from the script, the shell and
33 ;; the environment as well as commands.
37 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 ;; - Variables in `"' strings aren't fontified because there's no way of
39 ;; syntactically distinguishing those from `'' strings.
43 ;; page 1: variables and settings
44 ;; page 2: mode-command and utility functions
45 ;; page 3: statement syntax-commands for various shells
46 ;; page 4: various other commands
50 (defvar sh-ancestor-alist
67 "*Alist showing the direct ancestor of various shells.
68 This is the basis for `sh-feature'. See also `sh-alias-alist'.
69 By default we have the following three hierarchies:
72 jcsh C Shell with Job Control
74 itcsh ? Toronto C Shell
79 jsh Bourne Shell with Job Control
80 bash GNU Bourne Again Shell
83 dtksh CDE Desktop Korn Shell
84 pdksh Public Domain Korn Shell
85 wksh Window Korn Shell
87 oash SCO OA (curses) Shell
88 posix IEEE 1003.2 Shell Standard
92 (defvar sh-alias-alist
93 (nconc (if (eq system-type 'lignux)
99 "*Alist for transforming shell names to what they really are.
100 Use this where the name of the executable doesn't correspond to the type of
101 shell it really is.")
104 (defvar sh-shell-file (or (getenv "SHELL") "/bin/sh")
105 "*The executable file name for the shell being programmed.")
109 ;; bash does not need any options when run in a shell script,
113 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
115 ;; -p means don't initialize functions from the environment.
117 ;; Someone proposed -motif, but we don't want to encourage
118 ;; use of a non-free widget set.
120 ;; -f means don't run .zshrc.
122 "*Single argument string for the magic number. See `sh-feature'.")
124 (defvar sh-shell-variables nil
125 "Alist of shell variable names that should be included in completion.
126 These are used for completion in addition to all the variables named
127 in `process-environment'. Each element looks like (VAR . VAR), where
128 the car and cdr are the same symbol.")
130 (defvar sh-shell-variables-initialized nil
131 "Non-nil if `sh-shell-variables' is initialized.")
133 (defun sh-canonicalize-shell (shell)
134 "Convert a shell name SHELL to the one we should handle it as."
136 (setq shell (intern shell)))
137 (or (cdr (assq shell sh-alias-alist))
140 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
141 "The shell being programmed. This is set by \\[sh-set-shell].")
143 ;;; I turned off this feature because it doesn't permit typing commands
144 ;;; in the usual way without help.
145 ;;;(defvar sh-abbrevs
146 ;;; '((csh eval sh-abbrevs shell
147 ;;; "switch" 'sh-case
148 ;;; "getopts" 'sh-while-getopts)
150 ;;; (es eval sh-abbrevs shell
151 ;;; "function" 'sh-function)
153 ;;; (ksh88 eval sh-abbrevs sh
154 ;;; "select" 'sh-select)
156 ;;; (rc eval sh-abbrevs shell
158 ;;; "function" 'sh-function)
160 ;;; (sh eval sh-abbrevs shell
162 ;;; "function" 'sh-function
163 ;;; "until" 'sh-until
164 ;;; "getopts" 'sh-while-getopts)
166 ;;; ;; The next entry is only used for defining the others
167 ;;; (shell "for" sh-for
168 ;;; "loop" sh-indexed-loop
170 ;;; "tmpfile" sh-tmp-file
171 ;;; "while" sh-while)
173 ;;; (zsh eval sh-abbrevs ksh88
174 ;;; "repeat" 'sh-repeat))
175 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
176 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
177 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
181 (defvar sh-mode-syntax-table
182 '((csh eval identity sh)
183 (sh eval sh-mode-syntax-table ()
184 ;; #'s meanings depend on context which can't be expressed here
198 (rc eval sh-mode-syntax-table sh
201 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
206 (let ((map (make-sparse-keymap))
207 (menu-map (make-sparse-keymap "Insert")))
208 (define-key map "\C-c(" 'sh-function)
209 (define-key map "\C-c\C-w" 'sh-while)
210 (define-key map "\C-c\C-u" 'sh-until)
211 (define-key map "\C-c\C-t" 'sh-tmp-file)
212 (define-key map "\C-c\C-s" 'sh-select)
213 (define-key map "\C-c\C-r" 'sh-repeat)
214 (define-key map "\C-c\C-o" 'sh-while-getopts)
215 (define-key map "\C-c\C-l" 'sh-indexed-loop)
216 (define-key map "\C-c\C-i" 'sh-if)
217 (define-key map "\C-c\C-f" 'sh-for)
218 (define-key map "\C-c\C-c" 'sh-case)
220 (define-key map "=" 'sh-assignment)
221 (define-key map "\C-c+" 'sh-add)
222 (define-key map "\C-\M-x" 'sh-execute-region)
223 (define-key map "\C-c\C-x" 'executable-interpret)
224 (define-key map "<" 'sh-maybe-here-document)
225 (define-key map "(" 'skeleton-pair-insert-maybe)
226 (define-key map "{" 'skeleton-pair-insert-maybe)
227 (define-key map "[" 'skeleton-pair-insert-maybe)
228 (define-key map "'" 'skeleton-pair-insert-maybe)
229 (define-key map "`" 'skeleton-pair-insert-maybe)
230 (define-key map "\"" 'skeleton-pair-insert-maybe)
232 (define-key map "\t" 'sh-indent-line)
233 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
234 map (current-global-map))
235 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
236 map (current-global-map))
237 (substitute-key-definition 'delete-backward-char
238 'backward-delete-char-untabify
239 map (current-global-map))
240 (define-key map "\C-c:" 'sh-set-shell)
241 (substitute-key-definition 'beginning-of-defun
242 'sh-beginning-of-compound-command
243 map (current-global-map))
244 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
245 map (current-global-map))
246 (substitute-key-definition 'forward-sentence 'sh-end-of-command
247 map (current-global-map))
248 (define-key map [menu-bar insert] (cons "Insert" menu-map))
249 (define-key menu-map [sh-while] '("While Loop" . sh-while))
250 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
251 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
252 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
253 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
254 (define-key menu-map [sh-while-getopts]
255 '("Options Loop" . sh-while-getopts))
256 (define-key menu-map [sh-indexed-loop]
257 '("Indexed Loop" . sh-indexed-loop))
258 (define-key menu-map [sh-if] '("If Statement" . sh-if))
259 (define-key menu-map [sh-for] '("For Loop" . sh-for))
260 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
262 "Keymap used in Shell-Script mode.")
266 (defvar sh-dynamic-complete-functions
267 '(shell-dynamic-complete-environment-variable
268 shell-dynamic-complete-command
269 comint-dynamic-complete-filename)
270 "*Functions for doing TAB dynamic completion.")
273 (defvar sh-require-final-newline
276 (rc eval . require-final-newline)
277 (sh eval . require-final-newline))
278 "*Value of `require-final-newline' in Shell-Script mode buffers.
282 (defvar sh-comment-prefix
283 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
284 (rc eval identity csh)
285 (sh . "\\(^\\|[ \t|&;()]\\)"))
286 "*Regexp matching what may come before a comment `#'.
287 This must contain one \\(grouping\\) since it is the basis for fontifying
288 comments as well as for `comment-start-skip'.
292 (defvar sh-assignment-regexp
293 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
294 ;; actually spaces are only supported in let/(( ... ))
295 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
296 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
297 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
298 "*Regexp for the variable name and what may follow in an assignment.
299 First grouping matches the variable name. This is upto and including the `='
300 sign. See `sh-feature'.")
303 (defvar sh-indentation 4
304 "The width for further indentation in Shell-Script mode.")
307 (defvar sh-remember-variable-min 3
308 "*Don't remember variables less than this length for completing reads.")
311 (defvar sh-header-marker nil
312 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
313 That command is also used for setting this variable.")
316 (defvar sh-beginning-of-command
317 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
318 "*Regexp to determine the beginning of a shell command.
319 The actual command starts at the beginning of the second \\(grouping\\).")
322 (defvar sh-end-of-command
323 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
324 "*Regexp to determine the end of a shell command.
325 The actual command ends at the end of the first \\(grouping\\).")
329 (defvar sh-here-document-word "EOF"
330 "Word to delimit here documents.")
335 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
339 '((bash eval sh-append posix
340 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
341 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
342 "suspend" "typeset" "unalias")
344 ;; The next entry is only used for defining the others
345 (bourne eval sh-append shell
346 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
349 (csh eval sh-append shell
350 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
351 "setenv" "source" "time" "unalias" "unhash")
353 (dtksh eval identity wksh)
355 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
356 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
358 (jsh eval sh-append sh
359 "bg" "fg" "jobs" "kill" "stop" "suspend")
361 (jcsh eval sh-append csh
362 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
364 (ksh88 eval sh-append bourne
365 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
366 "typeset" "unalias" "whence")
368 (oash eval sh-append sh
369 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
370 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
371 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
372 "wmtitle" "wrefresh")
374 (pdksh eval sh-append ksh88
377 (posix eval sh-append sh
380 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
383 (sh eval sh-append bourne
384 "hash" "test" "type")
386 ;; The next entry is only used for defining the others
387 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
389 (wksh eval sh-append ksh88
392 (zsh eval sh-append ksh88
393 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
394 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
395 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
396 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
397 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
399 "*List of all shell builtins for completing read and fontification.
400 Note that on some systems not all builtins are available or some are
401 implemented as aliases. See `sh-feature'.")
405 (defvar sh-leading-keywords
408 (es "true" "unwind-protect" "whatis")
412 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
413 "*List of keywords that may be immediately followed by a builtin or keyword.
414 Given some confusion between keywords and builtins depending on shell and
415 system, the distinction here has been based on whether they influence the
416 flow of control or syntax. See `sh-feature'.")
419 (defvar sh-other-keywords
420 '((bash eval sh-append bourne
423 ;; The next entry is only used for defining the others
424 (bourne eval sh-append shell
425 "done" "esac" "fi" "for" "function" "in" "return")
427 (csh eval sh-append shell
428 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
429 "if" "logout" "onintr" "repeat" "switch" "then" "while")
431 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
432 "return" "throw" "while")
434 (ksh88 eval sh-append bourne
437 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
440 ;; The next entry is only used for defining the others
441 (shell "break" "case" "continue" "exec" "exit")
443 (zsh eval sh-append bash
445 "*List of keywords not in `sh-leading-keywords'.
451 '((bash eval sh-append sh
452 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
453 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
454 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
455 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
456 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
457 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
458 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
459 "SECONDS" "SHLVL" "TMOUT" "UID")
461 (csh eval sh-append shell
462 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
463 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
464 "shell" "status" "time" "verbose")
466 (es eval sh-append shell
467 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
468 "pid" "prompt" "signals")
470 (jcsh eval sh-append csh
473 (ksh88 eval sh-append sh
474 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
475 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
478 (oash eval sh-append sh
479 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
481 (rc eval sh-append shell
482 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
485 (sh eval sh-append shell
486 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
488 ;; The next entry is only used for defining the others
489 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
490 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
491 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
492 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
494 (tcsh eval sh-append csh
495 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
496 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
497 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
498 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
499 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
500 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
501 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
502 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
505 (zsh eval sh-append ksh88
506 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
507 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
508 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
509 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
510 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
511 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
512 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
513 "List of all shell variables available for completing read.
518 (defvar sh-font-lock-keywords
519 '((csh eval sh-append shell
520 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
521 font-lock-variable-name-face))
523 (es eval sh-append executable-font-lock-keywords
524 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
525 font-lock-variable-name-face))
527 (rc eval identity es)
529 (sh eval sh-append shell
530 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
531 font-lock-variable-name-face))
533 ;; The next entry is only used for defining the others
534 (shell eval sh-append executable-font-lock-keywords
535 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
536 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
537 font-lock-variable-name-face)))
538 "*Rules for highlighting shell scripts. See `sh-feature'.")
540 (defvar sh-font-lock-keywords-1
542 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
544 (defvar sh-font-lock-keywords-2 ()
545 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
547 (defvar sh-font-lock-keywords-only t
548 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
549 Default value is `t' because Emacs' syntax is not expressive enough to
550 detect that $# does not start a comment. Thus comments are fontified by
551 regexp which means that a single apostrophe in a comment turns everything
552 upto the next one or end of buffer into a string.")
554 ;; mode-command and utility functions
557 (put 'sh-mode 'mode-class 'special)
561 "Major mode for editing shell scripts.
562 This mode works for many shells, since they all have roughly the same syntax,
563 as far as commands, arguments, variables, pipes, comments etc. are concerned.
564 Unless the file's magic number indicates the shell, your usual shell is
565 assumed. Since filenames rarely give a clue, they are not further analyzed.
567 This mode adapts to the variations between shells (see `sh-set-shell') by
568 means of an inheritance based feature lookup (see `sh-feature'). This
569 mechanism applies to all variables (including skeletons) that pertain to
570 shell-specific features.
572 The default style of this mode is that of Rosenblatt's Korn shell book.
573 The syntax of the statements varies with the shell being used. The
574 following commands are available, based on the current shell's syntax:
576 \\[sh-case] case statement
578 \\[sh-function] function definition
579 \\[sh-if] if statement
580 \\[sh-indexed-loop] indexed loop from 1 to n
581 \\[sh-while-getopts] while getopts loop
582 \\[sh-repeat] repeat loop
583 \\[sh-select] select loop
584 \\[sh-until] until loop
585 \\[sh-while] while loop
587 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
588 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
589 \\[sh-end-of-command] Go to end of successive commands.
590 \\[sh-beginning-of-command] Go to beginning of successive commands.
591 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
592 \\[sh-execute-region] Have optional header and region be executed in a subshell.
594 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
596 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
598 If you generally program a shell different from your login shell you can
599 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
600 indicate what shell it is use `sh-alias-alist' to translate.
602 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
603 with your script for an edit-interpret-debug cycle."
605 (kill-all-local-variables)
606 (use-local-map sh-mode-map)
607 (make-local-variable 'indent-line-function)
608 (make-local-variable 'indent-region-function)
609 (make-local-variable 'skeleton-end-hook)
610 (make-local-variable 'paragraph-start)
611 (make-local-variable 'paragraph-separate)
612 (make-local-variable 'comment-start)
613 (make-local-variable 'comment-start-skip)
614 (make-local-variable 'require-final-newline)
615 (make-local-variable 'sh-header-marker)
616 (make-local-variable 'sh-shell-file)
617 (make-local-variable 'sh-shell)
618 (make-local-variable 'skeleton-pair-alist)
619 (make-local-variable 'skeleton-pair-filter)
620 (make-local-variable 'comint-dynamic-complete-functions)
621 (make-local-variable 'comint-prompt-regexp)
622 (make-local-variable 'font-lock-keywords)
623 (make-local-variable 'font-lock-defaults)
624 (make-local-variable 'skeleton-filter)
625 (make-local-variable 'skeleton-newline-indent-rigidly)
626 (make-local-variable 'sh-shell-variables)
627 (make-local-variable 'sh-shell-variables-initialized)
628 (setq major-mode 'sh-mode
629 mode-name "Shell-script"
630 indent-line-function 'sh-indent-line
631 ;; not very clever, but enables wrapping skeletons around regions
632 indent-region-function (lambda (b e)
635 (skip-syntax-backward "-")
638 (skip-syntax-backward "-")
639 (indent-rigidly b (point) sh-indentation)))
640 skeleton-end-hook (lambda ()
641 (or (eolp) (newline) (indent-relative)))
642 paragraph-start (concat page-delimiter "\\|$")
643 paragraph-separate paragraph-start
645 comint-dynamic-complete-functions sh-dynamic-complete-functions
646 ;; we can't look if previous line ended with `\'
647 comint-prompt-regexp "^[ \t]*"
649 `((sh-font-lock-keywords
650 sh-font-lock-keywords-1
651 sh-font-lock-keywords-2)
652 ,sh-font-lock-keywords-only
654 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
655 skeleton-pair-alist '((?` _ ?`))
656 skeleton-pair-filter 'sh-quoted-p
657 skeleton-further-elements '((< '(- (min sh-indentation
659 skeleton-filter 'sh-feature
660 skeleton-newline-indent-rigidly t)
662 ;; parse or insert magic number for exec() and set all variables depending
663 ;; on the shell thus determined
664 (goto-char (point-min))
665 (and (zerop (buffer-size))
666 (not buffer-read-only)
667 (sh-set-shell sh-shell-file)))
668 (run-hooks 'sh-mode-hook))
670 (defalias 'shell-script-mode 'sh-mode)
673 (defun sh-font-lock-keywords (&optional keywords)
674 "Function to get simple fontification based on `sh-font-lock-keywords'.
675 This adds rules for comments and assignments."
676 (sh-feature sh-font-lock-keywords
678 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
679 2 font-lock-comment-face t)
680 (,(sh-feature sh-assignment-regexp)
681 1 font-lock-variable-name-face)
685 (defun sh-font-lock-keywords-1 (&optional builtins)
686 "Function to get better fontification including keywords."
687 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
689 (sh-feature sh-leading-keywords)
693 (append (sh-feature sh-leading-keywords)
694 (sh-feature sh-other-keywords))
697 (sh-font-lock-keywords
699 `((,(concat keywords "[ \t]+\\)?\\("
700 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
702 (2 font-lock-keyword-face nil t)
703 (6 font-lock-function-name-face))
704 ,@(sh-feature sh-font-lock-keywords-2)))
705 (,(concat keywords "\\)\\>")
706 2 font-lock-keyword-face)
707 ,@(sh-feature sh-font-lock-keywords-1)))))
709 (defun sh-font-lock-keywords-2 ()
710 "Function to get better fontification including keywords and builtins."
711 (sh-font-lock-keywords-1 t))
714 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
715 "Set this buffer's shell to SHELL (a string).
716 Makes this script executable via `executable-set-magic'.
717 Calls the value of `sh-set-shell-hook' if set."
718 (interactive (list (completing-read "Name or path of shell: "
719 interpreter-mode-alist
720 (lambda (x) (eq (cdr x) 'sh-mode)))
721 (eq executable-query 'function)
723 (setq sh-shell (intern (file-name-nondirectory shell))
724 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
726 (setq sh-shell-file (executable-set-magic shell (sh-feature sh-shell-arg)))
727 (setq require-final-newline (sh-feature sh-require-final-newline)
728 ;;; local-abbrev-table (sh-feature sh-abbrevs)
729 font-lock-keywords nil ; force resetting
730 font-lock-syntax-table nil
731 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
732 mode-line-process (format "[%s]" sh-shell)
733 sh-shell-variables nil
734 sh-shell-variables-initialized nil
735 shell (sh-feature sh-variables))
736 (set-syntax-table (sh-feature sh-mode-syntax-table))
738 (sh-remember-variable (car shell))
739 (setq shell (cdr shell)))
740 (and (boundp 'font-lock-mode)
742 (font-lock-mode (font-lock-mode 0)))
743 (run-hooks 'sh-set-shell-hook))
747 (defun sh-feature (list &optional function)
748 "Index ALIST by the current shell.
749 If ALIST isn't a list where every element is a cons, it is returned as is.
750 Else indexing follows an inheritance logic which works in two ways:
752 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
753 the alist contains no value for the current shell.
755 - If the value thus looked up is a list starting with `eval' its `cdr' is
756 first evaluated. If that is also a list and the first argument is a
757 symbol in ALIST it is not evaluated, but rather recursively looked up in
758 ALIST to allow the function called to define the value for one shell to be
759 derived from another shell. While calling the function, is the car of the
760 alist element is the current shell.
761 The value thus determined is physically replaced into the alist.
763 Optional FUNCTION is applied to the determined value and the result is cached
767 (while (and l (consp (car l)))
771 (cdr (assoc (setq function (cons sh-shell function)) list)))
772 (let ((sh-shell sh-shell)
775 (not (setq elt (assq sh-shell list))))
776 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
777 (if (and (consp (setq val (cdr elt)))
778 (eq (car val) 'eval))
781 (eval (if (consp (setq val (cdr val)))
782 (let ((sh-shell (car (cdr val)))
784 (if (assq sh-shell list)
793 (setq sh-shell (car function)
794 val (funcall (cdr function) val))))))
799 ;;; I commented this out because nobody calls it -- rms.
800 ;;;(defun sh-abbrevs (ancestor &rest list)
801 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
802 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
803 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
804 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
805 ;;;EXPANSION may be either a string or a skeleton command."
806 ;;; (or (if (boundp sh-shell)
807 ;;; (symbol-value sh-shell))
809 ;;; (if (listp ancestor)
810 ;;; (nconc list ancestor))
811 ;;; (define-abbrev-table sh-shell ())
812 ;;; (if (vectorp ancestor)
813 ;;; (mapatoms (lambda (atom)
815 ;;; (define-abbrev (symbol-value sh-shell)
816 ;;; (symbol-name atom)
817 ;;; (symbol-value atom)
818 ;;; (symbol-function atom))))
821 ;;; (define-abbrev (symbol-value sh-shell)
823 ;;; (if (stringp (car (cdr list)))
826 ;;; (if (symbolp (car (cdr list)))
827 ;;; (car (cdr list))))
828 ;;; (setq list (cdr (cdr list)))))
829 ;;; (symbol-value sh-shell)))
832 (defun sh-mode-syntax-table (table &rest list)
833 "Copy TABLE and set syntax for successive CHARs according to strings S."
834 (setq table (copy-syntax-table table))
836 (modify-syntax-entry (car list) (car (cdr list)) table)
837 (setq list (cdr (cdr list))))
841 (defun sh-append (ancestor &rest list)
842 "Return list composed of first argument (a list) physically appended to rest."
843 (nconc list ancestor))
846 (defun sh-modify (skeleton &rest list)
847 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
848 (setq skeleton (copy-sequence skeleton))
850 (setcar (or (nthcdr (car list) skeleton)
851 (error "Index %d out of bounds" (car list)))
853 (setq list (nthcdr 2 list)))
857 (defun sh-indent-line ()
858 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
859 Lines containing only comments are considered empty."
861 (let ((previous (save-excursion
862 (while (and (not (bobp))
865 (back-to-indentation)
867 (eq (following-char) ?#)))))
871 (indent-to (if (eq this-command 'newline-and-indent)
873 (if (< (current-column)
874 (setq current (progn (back-to-indentation)
876 (if (eolp) previous 0)
877 (delete-region (point)
878 (progn (beginning-of-line) (point)))
880 (max previous (* (1+ (/ current sh-indentation))
882 (* (1+ (/ current sh-indentation)) sh-indentation))))))
883 (if (< (current-column) (current-indentation))
884 (skip-chars-forward " \t"))))
887 (defun sh-execute-region (start end &optional flag)
888 "Pass optional header and region to a subshell for noninteractive execution.
889 The working directory is that of the buffer, and only environment variables
890 are already set which is why you can mark a header within the script.
892 With a positive prefix ARG, instead of sending region, define header from
893 beginning of buffer to point. With a negative prefix ARG, instead of sending
894 region, clear header."
897 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
901 (let (buffer-undo-list)
902 (goto-char sh-header-marker)
903 (append-to-buffer (current-buffer) start end)
904 (shell-command-on-region (point-min)
905 (setq end (+ sh-header-marker
908 (delete-region sh-header-marker end)))
909 (shell-command-on-region start end (concat sh-shell-file " -")))))
912 (defun sh-remember-variable (var)
913 "Make VARIABLE available for future completing reads in this buffer."
914 (or (< (length var) sh-remember-variable-min)
916 (assoc var sh-shell-variables)
917 (setq sh-shell-variables (cons (cons var var) sh-shell-variables)))
922 (defun sh-quoted-p ()
923 "Is point preceded by an odd number of backslashes?"
924 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
926 ;; statement syntax-commands for various shells
928 ;; You are welcome to add the syntax or even completely new statements as
929 ;; appropriate for your favorite shell.
931 (define-skeleton sh-case
932 "Insert a case/switch statement. See `sh-feature'."
934 "switch( " str " )" \n
935 > "case " (read-string "pattern: ") ?: \n
938 ( "other pattern, %s: "
948 "switch( " str " ) {" \n
949 > "case " (read-string "pattern: ") \n
951 ( "other pattern, %s: "
960 > (read-string "pattern: ") ?\) \n
963 ( "other pattern, %s: "
971 (put 'sh-case 'menu-enable '(sh-feature sh-case))
975 (define-skeleton sh-for
976 "Insert a for loop. See `sh-feature'."
977 (csh eval sh-modify sh
982 (es eval sh-modify rc
984 (rc eval sh-modify sh
988 (sh "Index variable: "
989 "for " str " in " _ "; do" \n
990 > _ | ?$ & (sh-remember-variable str) \n
995 (define-skeleton sh-indexed-loop
996 "Insert an indexed loop from 1 to n. See `sh-feature'."
997 (bash eval identity posix)
998 (csh "Index variable: "
1000 "while( $" str " <= " (read-string "upper limit: ") " )" \n
1004 (es eval sh-modify rc
1006 (ksh88 "Index variable: "
1007 "integer " str "=0" \n
1008 "while (( ( " str " += 1 ) <= "
1009 (read-string "upper limit: ")
1011 > _ ?$ (sh-remember-variable str) \n
1013 (posix "Index variable: "
1015 "while [ $" str " -le "
1016 (read-string "upper limit: ")
1019 str ?= (sh-add (sh-remember-variable str) 1) \n
1021 (rc "Index variable: "
1022 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
1023 (read-string "upper limit: ")
1024 "; i++ ) print i }'}) {" \n
1025 > _ ?$ (sh-remember-variable str) \n
1027 (sh "Index variable: "
1028 "for " str " in `awk 'BEGIN { for( i=1; i<="
1029 (read-string "upper limit: ")
1030 "; i++ ) print i }'`; do" \n
1031 > _ ?$ (sh-remember-variable str) \n
1035 (defun sh-shell-initialize-variables ()
1036 "Scan the buffer for variable assignments.
1037 Add these variables to `sh-shell-variables'."
1038 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
1040 (goto-char (point-min))
1041 (setq sh-shell-variables-initialized t)
1042 (while (search-forward "=" nil t)
1044 (message "Scanning buffer `%s' for variable assignments...done"
1047 (defvar sh-add-buffer)
1049 (defun sh-add-completer (string predicate code)
1050 "Do completion using `sh-shell-variables', but initialize it first.
1051 This function is designed for use as the \"completion table\",
1052 so it takes three arguments:
1053 STRING, the current buffer contents;
1054 PREDICATE, the predicate for filtering possible matches;
1055 CODE, which says what kind of things to do.
1056 CODE can be nil, t or `lambda'.
1057 nil means to return the best completion of STRING, or nil if there is none.
1058 t means to return a list of all possible completions of STRING.
1059 `lambda' means to return t if STRING is a valid completion as it stands."
1060 (let ((sh-shell-variables
1062 (set-buffer sh-add-buffer)
1063 (or sh-shell-variables-initialized
1064 (sh-shell-initialize-variables))
1065 (nconc (mapcar (lambda (var)
1067 (substring var 0 (string-match "=" var))))
1069 process-environment)
1070 sh-shell-variables))))
1072 (try-completion string sh-shell-variables predicate))
1074 (all-completions string sh-shell-variables predicate))
1076 (assoc string sh-shell-variables)))))
1078 (defun sh-add (var delta)
1079 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1081 (let ((sh-add-buffer (current-buffer)))
1082 (list (completing-read "Variable: " 'sh-add-completer)
1083 (prefix-numeric-value current-prefix-arg))))
1084 (insert (sh-feature '((bash . "$[ ")
1090 (sh-remember-variable var)
1091 (if (< delta 0) " - " " + ")
1092 (number-to-string (abs delta))
1093 (sh-feature '((bash . " ]")
1102 (define-skeleton sh-function
1103 "Insert a function definition. See `sh-feature'."
1104 (bash eval sh-modify ksh88
1107 "function " str " {" \n
1110 (rc eval sh-modify ksh88
1119 (define-skeleton sh-if
1120 "Insert an if statement. See `sh-feature'."
1122 "if( " str " ) then" \n
1124 ( "other condition, %s: "
1125 < "else if( " str " ) then" \n
1132 "if { " str " } {" \n
1134 ( "other condition, %s: "
1135 < "} { " str " } {" \n
1141 (rc eval sh-modify csh
1143 8 '( "other condition, %s: "
1144 < "} else if( " str " ) {" \n
1149 '(setq input (sh-feature sh-test))
1150 "if " str "; then" \n
1152 ( "other condition, %s: "
1153 < "elif " str "; then" \n
1162 (define-skeleton sh-repeat
1163 "Insert a repeat loop definition. See `sh-feature'."
1169 "repeat " str "; do"\n
1172 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1176 (define-skeleton sh-select
1177 "Insert a select statement. See `sh-feature'."
1178 (ksh88 "Index variable: "
1179 "select " str " in " _ "; do" \n
1182 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1186 (define-skeleton sh-tmp-file
1187 "Insert code to setup temporary file handling. See `sh-feature'."
1188 (bash eval identity ksh88)
1189 (csh (file-name-nondirectory (buffer-file-name))
1190 "set tmp = /tmp/" str ".$$" \n
1192 (and (goto-char (point-max))
1196 "rm $tmp* >&/dev/null" >)
1197 (es (file-name-nondirectory (buffer-file-name))
1198 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1200 > "rm $tmp^* >[2]/dev/null" \n
1206 (ksh88 eval sh-modify sh
1208 (rc (file-name-nondirectory (buffer-file-name))
1209 "tmp = /tmp/" str ".$pid" \n
1210 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1211 (sh (file-name-nondirectory (buffer-file-name))
1212 "TMP=/tmp/" str ".$$" \n
1213 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1217 (define-skeleton sh-until
1218 "Insert an until loop. See `sh-feature'."
1220 '(setq input (sh-feature sh-test))
1221 "until " str "; do" \n
1224 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1228 (define-skeleton sh-while
1229 "Insert a while loop. See `sh-feature'."
1230 (csh eval sh-modify sh
1234 (es eval sh-modify rc
1237 (rc eval sh-modify csh
1241 '(setq input (sh-feature sh-test))
1242 "while " str "; do" \n
1248 (define-skeleton sh-while-getopts
1249 "Insert a while getopts loop. See `sh-feature'.
1250 Prompts for an options string which consists of letters for each recognized
1251 option followed by a colon `:' if the option accepts an argument."
1252 (bash eval sh-modify sh
1256 > "switch( \"$1\" )" \n
1257 '(setq input '("- x" . 2))
1260 < "case " '(eval str)
1261 '(if (string-match " +" str)
1262 (setq v1 (substring str (match-end 0))
1263 str (substring str 0 (match-beginning 0)))
1266 > "set " v1 & " = $2" | -4 & _ \n
1267 (if v1 "shift") & \n
1277 (ksh88 eval sh-modify sh
1281 (posix eval sh-modify sh
1282 18 "$(basename $0)")
1284 "while getopts :" str " OPT; do" \n
1287 '(setq v1 (append (vconcat str) nil))
1288 ( (prog1 (if v1 (char-to-string (car v1)))
1289 (if (eq (nth 1 v1) ?:)
1290 (setq v1 (nthcdr 2 v1)
1294 < str "|+" str ?\) \n
1298 > "echo" " \"usage: " "`basename $0`"
1299 " [+-" '(setq v1 (point)) str
1301 (while (search-backward ":" v1 t)
1302 (replace-match " ARG] [+-" t t)))
1303 (if (eq (preceding-char) ?-) -5)
1304 "] [--] ARGS...\"" \n
1308 "shift " (sh-add "OPTIND" -1)))
1309 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1313 (defun sh-assignment (arg)
1314 "Remember preceding identifier for future completion and do self-insert."
1316 (self-insert-command arg)
1318 (sh-remember-variable
1320 (if (re-search-forward (sh-feature sh-assignment-regexp)
1322 (beginning-of-line 1))
1324 (match-string 1))))))
1328 (defun sh-maybe-here-document (arg)
1329 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1330 The document is bounded by `sh-here-document-word'."
1332 (self-insert-command (prefix-numeric-value arg))
1334 (not (eq (char-after (- (point) 2)) last-command-char))
1339 (insert sh-here-document-word)
1340 (or (eolp) (looking-at "[ \t]") (insert ? ))
1346 (save-excursion (insert ?\n sh-here-document-word)))))
1349 ;; various other commands
1351 (autoload 'comint-dynamic-complete "comint"
1352 "Dynamically perform completion at point." t)
1354 (autoload 'shell-dynamic-complete-command "shell"
1355 "Dynamically complete the command at point." t)
1357 (autoload 'comint-dynamic-complete-filename "comint"
1358 "Dynamically complete the filename at point." t)
1360 (autoload 'shell-dynamic-complete-environment-variable "shell"
1361 "Dynamically complete the environment variable at point." t)
1365 (defun sh-newline-and-indent ()
1366 "Strip unquoted whitespace, insert newline, and indent like current line."
1368 (indent-to (prog1 (current-indentation)
1369 (delete-region (point)
1371 (or (zerop (skip-chars-backward " \t"))
1379 (defun sh-beginning-of-command ()
1380 "Move point to successive beginnings of commands."
1382 (if (re-search-backward sh-beginning-of-command nil t)
1383 (goto-char (match-beginning 2))))
1386 (defun sh-end-of-command ()
1387 "Move point to successive ends of commands."
1389 (if (re-search-forward sh-end-of-command nil t)
1390 (goto-char (match-end 1))))
1392 (provide 'sh-script)
1393 ;; sh-script.el ends here