1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 1994, 1995, 1996 by Free Software Foundation, Inc.
5 ;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
8 ;; Keywords: languages, unix
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30 ;; as various derivatives are supported and easily derived from. Structured
31 ;; statements can be inserted with one command or abbrev. Completion is
32 ;; available for filenames, variables known from the script, the shell and
33 ;; the environment as well as commands.
37 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 ;; - Variables in `"' strings aren't fontified because there's no way of
39 ;; syntactically distinguishing those from `'' strings.
43 ;; page 1: variables and settings
44 ;; page 2: mode-command and utility functions
45 ;; page 3: statement syntax-commands for various shells
46 ;; page 4: various other commands
50 (defvar sh-ancestor-alist
67 "*Alist showing the direct ancestor of various shells.
68 This is the basis for `sh-feature'. See also `sh-alias-alist'.
69 By default we have the following three hierarchies:
72 jcsh C Shell with Job Control
74 itcsh ? Toronto C Shell
79 jsh Bourne Shell with Job Control
80 bash GNU Bourne Again Shell
83 dtksh CDE Desktop Korn Shell
84 pdksh Public Domain Korn Shell
85 wksh Window Korn Shell
87 oash SCO OA (curses) Shell
88 posix IEEE 1003.2 Shell Standard
92 (defvar sh-alias-alist
93 (nconc (if (eq system-type 'linux)
99 "*Alist for transforming shell names to what they really are.
100 Use this where the name of the executable doesn't correspond to the type of
101 shell it really is.")
104 (defvar sh-shell-file (or (getenv "SHELL") "/bin/sh")
105 "*The executable file name for the shell being programmed.")
108 ;; bash and ksh do not need any options when run in a shell script,
109 ;; and Bill_Mann@praxisint.com says -p with ksh can do harm.
115 ;; Bill_Mann@praxisint.com says -p may be wrong for this too.
119 "*Single argument string for the magic number. See `sh-feature'.")
121 (defvar sh-shell-variables nil
122 "Alist of shell variable names that should be included in completion.
123 These are used for completion in addition to all the variables named
124 in `process-environment'. Each element looks like (VAR . VAR), where
125 the car and cdr are the same symbol.")
127 (defvar sh-shell-variables-initialized nil
128 "Non-nil if `sh-shell-variables' is initialized.")
130 (defun sh-canonicalize-shell (shell)
131 "Convert a shell name SHELL to the one we should handle it as."
133 (setq shell (intern shell)))
134 (or (cdr (assq shell sh-alias-alist))
137 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
138 "The shell being programmed. This is set by \\[sh-set-shell].")
140 ;;; I turned off this feature because it doesn't permit typing commands
141 ;;; in the usual way without help.
142 ;;;(defvar sh-abbrevs
143 ;;; '((csh eval sh-abbrevs shell
144 ;;; "switch" 'sh-case
145 ;;; "getopts" 'sh-while-getopts)
147 ;;; (es eval sh-abbrevs shell
148 ;;; "function" 'sh-function)
150 ;;; (ksh88 eval sh-abbrevs sh
151 ;;; "select" 'sh-select)
153 ;;; (rc eval sh-abbrevs shell
155 ;;; "function" 'sh-function)
157 ;;; (sh eval sh-abbrevs shell
159 ;;; "function" 'sh-function
160 ;;; "until" 'sh-until
161 ;;; "getopts" 'sh-while-getopts)
163 ;;; ;; The next entry is only used for defining the others
164 ;;; (shell "for" sh-for
165 ;;; "loop" sh-indexed-loop
167 ;;; "tmpfile" sh-tmp-file
168 ;;; "while" sh-while)
170 ;;; (zsh eval sh-abbrevs ksh88
171 ;;; "repeat" 'sh-repeat))
172 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
173 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
174 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
178 (defvar sh-mode-syntax-table
179 '((csh eval identity sh)
180 (sh eval sh-mode-syntax-table ()
181 ;; #'s meanings depend on context which can't be expressed here
195 (rc eval sh-mode-syntax-table sh
198 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
203 (let ((map (make-sparse-keymap))
204 (menu-map (make-sparse-keymap "Insert")))
205 (define-key map "\C-c(" 'sh-function)
206 (define-key map "\C-c\C-w" 'sh-while)
207 (define-key map "\C-c\C-u" 'sh-until)
208 (define-key map "\C-c\C-t" 'sh-tmp-file)
209 (define-key map "\C-c\C-s" 'sh-select)
210 (define-key map "\C-c\C-r" 'sh-repeat)
211 (define-key map "\C-c\C-o" 'sh-while-getopts)
212 (define-key map "\C-c\C-l" 'sh-indexed-loop)
213 (define-key map "\C-c\C-i" 'sh-if)
214 (define-key map "\C-c\C-f" 'sh-for)
215 (define-key map "\C-c\C-c" 'sh-case)
217 (define-key map "=" 'sh-assignment)
218 (define-key map "\C-c+" 'sh-add)
219 (define-key map "\C-\M-x" 'sh-execute-region)
220 (define-key map "\C-c\C-x" 'executable-interpret)
221 (define-key map "<" 'sh-maybe-here-document)
222 (define-key map "(" 'skeleton-pair-insert-maybe)
223 (define-key map "{" 'skeleton-pair-insert-maybe)
224 (define-key map "[" 'skeleton-pair-insert-maybe)
225 (define-key map "'" 'skeleton-pair-insert-maybe)
226 (define-key map "`" 'skeleton-pair-insert-maybe)
227 (define-key map "\"" 'skeleton-pair-insert-maybe)
229 (define-key map "\t" 'sh-indent-line)
230 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
231 map (current-global-map))
232 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
233 map (current-global-map))
234 (substitute-key-definition 'delete-backward-char
235 'backward-delete-char-untabify
236 map (current-global-map))
237 (define-key map "\C-c:" 'sh-set-shell)
238 (substitute-key-definition 'beginning-of-defun
239 'sh-beginning-of-compound-command
240 map (current-global-map))
241 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
242 map (current-global-map))
243 (substitute-key-definition 'forward-sentence 'sh-end-of-command
244 map (current-global-map))
245 (define-key map [menu-bar insert] (cons "Insert" menu-map))
246 (define-key menu-map [sh-while] '("While Loop" . sh-while))
247 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
248 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
249 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
250 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
251 (define-key menu-map [sh-while-getopts]
252 '("Options Loop" . sh-while-getopts))
253 (define-key menu-map [sh-indexed-loop]
254 '("Indexed Loop" . sh-indexed-loop))
255 (define-key menu-map [sh-if] '("If Statement" . sh-if))
256 (define-key menu-map [sh-for] '("For Loop" . sh-for))
257 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
259 "Keymap used in Shell-Script mode.")
263 (defvar sh-dynamic-complete-functions
264 '(shell-dynamic-complete-environment-variable
265 shell-dynamic-complete-command
266 comint-dynamic-complete-filename)
267 "*Functions for doing TAB dynamic completion.")
270 (defvar sh-require-final-newline
273 (rc eval . require-final-newline)
274 (sh eval . require-final-newline))
275 "*Value of `require-final-newline' in Shell-Script mode buffers.
279 (defvar sh-comment-prefix
280 '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
281 (rc eval identity csh)
282 (sh . "\\(^\\|[ \t|&;()]\\)"))
283 "*Regexp matching what may come before a comment `#'.
284 This must contain one \\(grouping\\) since it is the basis for fontifying
285 comments as well as for `comment-start-skip'.
289 (defvar sh-assignment-regexp
290 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
291 ;; actually spaces are only supported in let/(( ... ))
292 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
293 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
294 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
295 "*Regexp for the variable name and what may follow in an assignment.
296 First grouping matches the variable name. This is upto and including the `='
297 sign. See `sh-feature'.")
300 (defvar sh-indentation 4
301 "The width for further indentation in Shell-Script mode.")
304 (defvar sh-remember-variable-min 3
305 "*Don't remember variables less than this length for completing reads.")
308 (defvar sh-header-marker nil
309 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
310 That command is also used for setting this variable.")
313 (defvar sh-beginning-of-command
314 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
315 "*Regexp to determine the beginning of a shell command.
316 The actual command starts at the beginning of the second \\(grouping\\).")
319 (defvar sh-end-of-command
320 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
321 "*Regexp to determine the end of a shell command.
322 The actual command ends at the end of the first \\(grouping\\).")
326 (defvar sh-here-document-word "EOF"
327 "Word to delimit here documents.")
332 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
336 '((bash eval sh-append posix
337 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
338 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
339 "suspend" "typeset" "unalias")
341 ;; The next entry is only used for defining the others
342 (bourne eval sh-append shell
343 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
346 (csh eval sh-append shell
347 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
348 "setenv" "source" "time" "unalias" "unhash")
350 (dtksh eval identity wksh)
352 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
353 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
355 (jsh eval sh-append sh
356 "bg" "fg" "jobs" "kill" "stop" "suspend")
358 (jcsh eval sh-append csh
359 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
361 (ksh88 eval sh-append bourne
362 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
363 "typeset" "unalias" "whence")
365 (oash eval sh-append sh
366 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
367 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
368 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
369 "wmtitle" "wrefresh")
371 (pdksh eval sh-append ksh88
374 (posix eval sh-append sh
377 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
380 (sh eval sh-append bourne
381 "hash" "test" "type")
383 ;; The next entry is only used for defining the others
384 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
386 (wksh eval sh-append ksh88
389 (zsh eval sh-append ksh88
390 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
391 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
392 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
393 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
394 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
396 "*List of all shell builtins for completing read and fontification.
397 Note that on some systems not all builtins are available or some are
398 implemented as aliases. See `sh-feature'.")
402 (defvar sh-leading-keywords
405 (es "true" "unwind-protect" "whatis")
409 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
410 "*List of keywords that may be immediately followed by a builtin or keyword.
411 Given some confusion between keywords and builtins depending on shell and
412 system, the distinction here has been based on whether they influence the
413 flow of control or syntax. See `sh-feature'.")
416 (defvar sh-other-keywords
417 '((bash eval sh-append bourne
420 ;; The next entry is only used for defining the others
421 (bourne eval sh-append shell
422 "done" "esac" "fi" "for" "function" "in" "return")
424 (csh eval sh-append shell
425 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
426 "if" "logout" "onintr" "repeat" "switch" "then" "while")
428 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
429 "return" "throw" "while")
431 (ksh88 eval sh-append bourne
434 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
437 ;; The next entry is only used for defining the others
438 (shell "break" "case" "continue" "exec" "exit")
440 (zsh eval sh-append bash
442 "*List of keywords not in `sh-leading-keywords'.
448 '((bash eval sh-append sh
449 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
450 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
451 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
452 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
453 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
454 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
455 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
456 "SECONDS" "SHLVL" "TMOUT" "UID")
458 (csh eval sh-append shell
459 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
460 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
461 "shell" "status" "time" "verbose")
463 (es eval sh-append shell
464 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
465 "pid" "prompt" "signals")
467 (jcsh eval sh-append csh
470 (ksh88 eval sh-append sh
471 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
472 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
475 (oash eval sh-append sh
476 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
478 (rc eval sh-append shell
479 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
482 (sh eval sh-append shell
483 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
485 ;; The next entry is only used for defining the others
486 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
487 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
488 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
489 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
491 (tcsh eval sh-append csh
492 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
493 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
494 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
495 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
496 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
497 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
498 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
499 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
502 (zsh eval sh-append ksh88
503 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
504 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
505 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
506 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
507 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
508 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
509 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
510 "List of all shell variables available for completing read.
515 (defvar sh-font-lock-keywords
516 '((csh eval sh-append shell
517 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
518 font-lock-variable-name-face))
520 (es eval sh-append executable-font-lock-keywords
521 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
522 font-lock-variable-name-face))
524 (rc eval identity es)
526 (sh eval sh-append shell
527 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
528 font-lock-variable-name-face))
530 ;; The next entry is only used for defining the others
531 (shell eval sh-append executable-font-lock-keywords
532 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
533 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
534 font-lock-variable-name-face)))
535 "*Rules for highlighting shell scripts. See `sh-feature'.")
537 (defvar sh-font-lock-keywords-1
539 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
541 (defvar sh-font-lock-keywords-2 ()
542 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
544 (defvar sh-font-lock-keywords-only t
545 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
546 Default value is `t' because Emacs' syntax is not expressive enough to
547 detect that $# does not start a comment. Thus comments are fontified by
548 regexp which means that a single apostrophe in a comment turns everything
549 upto the next one or end of buffer into a string.")
551 ;; mode-command and utility functions
554 (put 'sh-mode 'mode-class 'special)
558 "Major mode for editing shell scripts.
559 This mode works for many shells, since they all have roughly the same syntax,
560 as far as commands, arguments, variables, pipes, comments etc. are concerned.
561 Unless the file's magic number indicates the shell, your usual shell is
562 assumed. Since filenames rarely give a clue, they are not further analyzed.
564 This mode adapts to the variations between shells (see `sh-set-shell') by
565 means of an inheritance based feature lookup (see `sh-feature'). This
566 mechanism applies to all variables (including skeletons) that pertain to
567 shell-specific features.
569 The default style of this mode is that of Rosenblatt's Korn shell book.
570 The syntax of the statements varies with the shell being used. The
571 following commands are available, based on the current shell's syntax:
573 \\[sh-case] case statement
575 \\[sh-function] function definition
576 \\[sh-if] if statement
577 \\[sh-indexed-loop] indexed loop from 1 to n
578 \\[sh-while-getopts] while getopts loop
579 \\[sh-repeat] repeat loop
580 \\[sh-select] select loop
581 \\[sh-until] until loop
582 \\[sh-while] while loop
584 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
585 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
586 \\[sh-end-of-command] Go to end of successive commands.
587 \\[sh-beginning-of-command] Go to beginning of successive commands.
588 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
589 \\[sh-execute-region] Have optional header and region be executed in a subshell.
591 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
593 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
595 If you generally program a shell different from your login shell you can
596 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
597 indicate what shell it is use `sh-alias-alist' to translate.
599 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
600 with your script for an edit-interpret-debug cycle."
602 (kill-all-local-variables)
603 (use-local-map sh-mode-map)
604 (make-local-variable 'indent-line-function)
605 (make-local-variable 'indent-region-function)
606 (make-local-variable 'skeleton-end-hook)
607 (make-local-variable 'paragraph-start)
608 (make-local-variable 'paragraph-separate)
609 (make-local-variable 'comment-start)
610 (make-local-variable 'comment-start-skip)
611 (make-local-variable 'require-final-newline)
612 (make-local-variable 'sh-header-marker)
613 (make-local-variable 'sh-shell-file)
614 (make-local-variable 'sh-shell)
615 (make-local-variable 'skeleton-pair-alist)
616 (make-local-variable 'skeleton-pair-filter)
617 (make-local-variable 'comint-dynamic-complete-functions)
618 (make-local-variable 'comint-prompt-regexp)
619 (make-local-variable 'font-lock-keywords)
620 (make-local-variable 'font-lock-defaults)
621 (make-local-variable 'skeleton-filter)
622 (make-local-variable 'skeleton-newline-indent-rigidly)
623 (make-local-variable 'sh-shell-variables)
624 (make-local-variable 'sh-shell-variables-initialized)
625 (setq major-mode 'sh-mode
626 mode-name "Shell-script"
627 indent-line-function 'sh-indent-line
628 ;; not very clever, but enables wrapping skeletons around regions
629 indent-region-function (lambda (b e)
632 (skip-syntax-backward "-")
635 (skip-syntax-backward "-")
636 (indent-rigidly b (point) sh-indentation)))
637 skeleton-end-hook (lambda ()
638 (or (eolp) (newline) (indent-relative)))
639 paragraph-start (concat page-delimiter "\\|$")
640 paragraph-separate paragraph-start
642 comint-dynamic-complete-functions sh-dynamic-complete-functions
643 ;; we can't look if previous line ended with `\'
644 comint-prompt-regexp "^[ \t]*"
646 `((sh-font-lock-keywords
647 sh-font-lock-keywords-1
648 sh-font-lock-keywords-2)
649 ,sh-font-lock-keywords-only
651 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")))
652 skeleton-pair-alist '((?` _ ?`))
653 skeleton-pair-filter 'sh-quoted-p
654 skeleton-further-elements '((< '(- (min sh-indentation
656 skeleton-filter 'sh-feature
657 skeleton-newline-indent-rigidly t)
659 ;; parse or insert magic number for exec() and set all variables depending
660 ;; on the shell thus determined
661 (goto-char (point-min))
663 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
666 (run-hooks 'sh-mode-hook))
668 (defalias 'shell-script-mode 'sh-mode)
671 (defun sh-font-lock-keywords (&optional keywords)
672 "Function to get simple fontification based on `sh-font-lock-keywords'.
673 This adds rules for comments and assignments."
674 (sh-feature sh-font-lock-keywords
676 `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
677 2 font-lock-comment-face t)
678 (,(sh-feature sh-assignment-regexp)
679 1 font-lock-variable-name-face)
683 (defun sh-font-lock-keywords-1 (&optional builtins)
684 "Function to get better fontification including keywords."
685 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
687 (sh-feature sh-leading-keywords)
691 (append (sh-feature sh-leading-keywords)
692 (sh-feature sh-other-keywords))
695 (sh-font-lock-keywords
697 `((,(concat keywords "[ \t]+\\)?\\("
698 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
700 (2 font-lock-keyword-face nil t)
701 (6 font-lock-function-name-face))
702 ,@(sh-feature sh-font-lock-keywords-2)))
703 (,(concat keywords "\\)\\>")
704 2 font-lock-keyword-face)
705 ,@(sh-feature sh-font-lock-keywords-1)))))
707 (defun sh-font-lock-keywords-2 ()
708 "Function to get better fontification including keywords and builtins."
709 (sh-font-lock-keywords-1 t))
712 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
713 "Set this buffer's shell to SHELL (a string).
714 Makes this script executable via `executable-set-magic'.
715 Calls the value of `sh-set-shell-hook' if set."
716 (interactive (list (completing-read "Name or path of shell: "
717 interpreter-mode-alist
718 (lambda (x) (eq (cdr x) 'sh-mode)))
719 (eq executable-query 'function)
721 (setq sh-shell (intern (file-name-nondirectory shell))
722 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
724 (setq sh-shell-file (executable-set-magic shell (sh-feature sh-shell-arg)))
725 (setq require-final-newline (sh-feature sh-require-final-newline)
726 ;;; local-abbrev-table (sh-feature sh-abbrevs)
727 font-lock-keywords nil ; force resetting
728 font-lock-syntax-table nil
729 comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
730 mode-line-process (format "[%s]" sh-shell)
731 sh-shell-variables nil
732 sh-shell-variables-initialized nil
733 shell (sh-feature sh-variables))
734 (set-syntax-table (sh-feature sh-mode-syntax-table))
736 (sh-remember-variable (car shell))
737 (setq shell (cdr shell)))
738 (and (boundp 'font-lock-mode)
740 (font-lock-mode (font-lock-mode 0)))
741 (run-hooks 'sh-set-shell-hook))
745 (defun sh-feature (list &optional function)
746 "Index ALIST by the current shell.
747 If ALIST isn't a list where every element is a cons, it is returned as is.
748 Else indexing follows an inheritance logic which works in two ways:
750 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
751 the alist contains no value for the current shell.
753 - If the value thus looked up is a list starting with `eval' its `cdr' is
754 first evaluated. If that is also a list and the first argument is a
755 symbol in ALIST it is not evaluated, but rather recursively looked up in
756 ALIST to allow the function called to define the value for one shell to be
757 derived from another shell. While calling the function, is the car of the
758 alist element is the current shell.
759 The value thus determined is physically replaced into the alist.
761 Optional FUNCTION is applied to the determined value and the result is cached
765 (while (and l (consp (car l)))
769 (cdr (assoc (setq function (cons sh-shell function)) list)))
770 (let ((sh-shell sh-shell)
773 (not (setq elt (assq sh-shell list))))
774 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
775 (if (and (consp (setq val (cdr elt)))
776 (eq (car val) 'eval))
779 (eval (if (consp (setq val (cdr val)))
780 (let ((sh-shell (car (cdr val)))
782 (if (assq sh-shell list)
791 (setq sh-shell (car function)
792 val (funcall (cdr function) val))))))
797 ;;; I commented this out because nobody calls it -- rms.
798 ;;;(defun sh-abbrevs (ancestor &rest list)
799 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
800 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
801 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
802 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
803 ;;;EXPANSION may be either a string or a skeleton command."
804 ;;; (or (if (boundp sh-shell)
805 ;;; (symbol-value sh-shell))
807 ;;; (if (listp ancestor)
808 ;;; (nconc list ancestor))
809 ;;; (define-abbrev-table sh-shell ())
810 ;;; (if (vectorp ancestor)
811 ;;; (mapatoms (lambda (atom)
813 ;;; (define-abbrev (symbol-value sh-shell)
814 ;;; (symbol-name atom)
815 ;;; (symbol-value atom)
816 ;;; (symbol-function atom))))
819 ;;; (define-abbrev (symbol-value sh-shell)
821 ;;; (if (stringp (car (cdr list)))
824 ;;; (if (symbolp (car (cdr list)))
825 ;;; (car (cdr list))))
826 ;;; (setq list (cdr (cdr list)))))
827 ;;; (symbol-value sh-shell)))
830 (defun sh-mode-syntax-table (table &rest list)
831 "Copy TABLE and set syntax for successive CHARs according to strings S."
832 (setq table (copy-syntax-table table))
834 (modify-syntax-entry (car list) (car (cdr list)) table)
835 (setq list (cdr (cdr list))))
839 (defun sh-append (ancestor &rest list)
840 "Return list composed of first argument (a list) physically appended to rest."
841 (nconc list ancestor))
844 (defun sh-modify (skeleton &rest list)
845 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
846 (setq skeleton (copy-sequence skeleton))
848 (setcar (or (nthcdr (car list) skeleton)
849 (error "Index %d out of bounds" (car list)))
851 (setq list (nthcdr 2 list)))
855 (defun sh-indent-line ()
856 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
857 Lines containing only comments are considered empty."
859 (let ((previous (save-excursion
860 (while (and (not (bobp))
863 (back-to-indentation)
865 (eq (following-char) ?#)))))
869 (indent-to (if (eq this-command 'newline-and-indent)
871 (if (< (current-column)
872 (setq current (progn (back-to-indentation)
874 (if (eolp) previous 0)
875 (delete-region (point)
876 (progn (beginning-of-line) (point)))
878 (max previous (* (1+ (/ current sh-indentation))
880 (* (1+ (/ current sh-indentation)) sh-indentation))))))
881 (if (< (current-column) (current-indentation))
882 (skip-chars-forward " \t"))))
885 (defun sh-execute-region (start end &optional flag)
886 "Pass optional header and region to a subshell for noninteractive execution.
887 The working directory is that of the buffer, and only environment variables
888 are already set which is why you can mark a header within the script.
890 With a positive prefix ARG, instead of sending region, define header from
891 beginning of buffer to point. With a negative prefix ARG, instead of sending
892 region, clear header."
895 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
899 (let (buffer-undo-list)
900 (goto-char sh-header-marker)
901 (append-to-buffer (current-buffer) start end)
902 (shell-command-on-region (point-min)
903 (setq end (+ sh-header-marker
906 (delete-region sh-header-marker end)))
907 (shell-command-on-region start end (concat sh-shell-file " -")))))
910 (defun sh-remember-variable (var)
911 "Make VARIABLE available for future completing reads in this buffer."
912 (or (< (length var) sh-remember-variable-min)
914 (assoc var sh-shell-variables)
915 (setq sh-shell-variables (cons (cons var var) sh-shell-variables)))
920 (defun sh-quoted-p ()
921 "Is point preceded by an odd number of backslashes?"
922 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
924 ;; statement syntax-commands for various shells
926 ;; You are welcome to add the syntax or even completely new statements as
927 ;; appropriate for your favorite shell.
929 (define-skeleton sh-case
930 "Insert a case/switch statement. See `sh-feature'."
932 "switch( " str " )" \n
933 > "case " (read-string "pattern: ") ?: \n
936 ( "other pattern, %s: "
946 "switch( " str " ) {" \n
947 > "case " (read-string "pattern: ") \n
949 ( "other pattern, %s: "
958 > (read-string "pattern: ") ?\) \n
961 ( "other pattern, %s: "
969 (put 'sh-case 'menu-enable '(sh-feature sh-case))
973 (define-skeleton sh-for
974 "Insert a for loop. See `sh-feature'."
975 (csh eval sh-modify sh
980 (es eval sh-modify rc
982 (rc eval sh-modify sh
986 (sh "Index variable: "
987 "for " str " in " _ "; do" \n
988 > _ | ?$ & (sh-remember-variable str) \n
993 (define-skeleton sh-indexed-loop
994 "Insert an indexed loop from 1 to n. See `sh-feature'."
995 (bash eval identity posix)
996 (csh "Index variable: "
998 "while( $" str " <= " (read-string "upper limit: ") " )" \n
1002 (es eval sh-modify rc
1004 (ksh88 "Index variable: "
1005 "integer " str "=0" \n
1006 "while (( ( " str " += 1 ) <= "
1007 (read-string "upper limit: ")
1009 > _ ?$ (sh-remember-variable str) \n
1011 (posix "Index variable: "
1013 "while [ $" str " -le "
1014 (read-string "upper limit: ")
1017 str ?= (sh-add (sh-remember-variable str) 1) \n
1019 (rc "Index variable: "
1020 "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
1021 (read-string "upper limit: ")
1022 "; i++ ) print i }'}) {" \n
1023 > _ ?$ (sh-remember-variable str) \n
1025 (sh "Index variable: "
1026 "for " str " in `awk 'BEGIN { for( i=1; i<="
1027 (read-string "upper limit: ")
1028 "; i++ ) print i }'`; do" \n
1029 > _ ?$ (sh-remember-variable str) \n
1033 (defun sh-shell-initialize-variables ()
1034 "Scan the buffer for variable assignments.
1035 Add these variables to `sh-shell-variables'."
1036 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
1038 (goto-char (point-min))
1039 (setq sh-shell-variables-initialized t)
1040 (while (search-forward "=" nil t)
1042 (message "Scanning buffer `%s' for variable assignments...done"
1045 (defvar sh-add-buffer)
1047 (defun sh-add-completer (string predicate code)
1048 "Do completion using `sh-shell-variables', but initialize it first.
1049 This function is designed for use as the \"completion table\",
1050 so it takes three arguments:
1051 STRING, the current buffer contents;
1052 PREDICATE, the predicate for filtering possible matches;
1053 CODE, which says what kind of things to do.
1054 CODE can be nil, t or `lambda'.
1055 nil means to return the best completion of STRING, or nil if there is none.
1056 t means to return a list of all possible completions of STRING.
1057 `lambda' means to return t if STRING is a valid completion as it stands."
1058 (let ((sh-shell-variables
1060 (set-buffer sh-add-buffer)
1061 (or sh-shell-variables-initialized
1062 (sh-shell-initialize-variables))
1063 (nconc (mapcar (lambda (var)
1065 (substring var 0 (string-match "=" var))))
1067 process-environment)
1068 sh-shell-variables))))
1070 (try-completion string sh-shell-variables predicate))
1072 (all-completions string sh-shell-variables predicate))
1074 (assoc string sh-shell-variables)))))
1076 (defun sh-add (var delta)
1077 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1079 (let ((sh-add-buffer (current-buffer)))
1080 (list (completing-read "Variable: " 'sh-add-completer)
1081 (prefix-numeric-value current-prefix-arg))))
1082 (insert (sh-feature '((bash . "$[ ")
1088 (sh-remember-variable var)
1089 (if (< delta 0) " - " " + ")
1090 (number-to-string (abs delta))
1091 (sh-feature '((bash . " ]")
1100 (define-skeleton sh-function
1101 "Insert a function definition. See `sh-feature'."
1102 (bash eval sh-modify ksh88
1105 "function " str " {" \n
1108 (rc eval sh-modify ksh88
1117 (define-skeleton sh-if
1118 "Insert an if statement. See `sh-feature'."
1120 "if( " str " ) then" \n
1122 ( "other condition, %s: "
1123 < "else if( " str " ) then" \n
1130 "if { " str " } {" \n
1132 ( "other condition, %s: "
1133 < "} { " str " } {" \n
1139 (rc eval sh-modify csh
1141 8 '( "other condition, %s: "
1142 < "} else if( " str " ) {" \n
1147 '(setq input (sh-feature sh-test))
1148 "if " str "; then" \n
1150 ( "other condition, %s: "
1151 < "elif " str "; then" \n
1160 (define-skeleton sh-repeat
1161 "Insert a repeat loop definition. See `sh-feature'."
1167 "repeat " str "; do"\n
1170 (put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
1174 (define-skeleton sh-select
1175 "Insert a select statement. See `sh-feature'."
1176 (ksh88 "Index variable: "
1177 "select " str " in " _ "; do" \n
1180 (put 'sh-select 'menu-enable '(sh-feature sh-select))
1184 (define-skeleton sh-tmp-file
1185 "Insert code to setup temporary file handling. See `sh-feature'."
1186 (bash eval identity ksh88)
1187 (csh (file-name-nondirectory (buffer-file-name))
1188 "set tmp = /tmp/" str ".$$" \n
1190 (and (goto-char (point-max))
1194 "rm $tmp* >&/dev/null" >)
1195 (es (file-name-nondirectory (buffer-file-name))
1196 "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
1198 > "rm $tmp^* >[2]/dev/null" \n
1204 (ksh88 eval sh-modify sh
1206 (rc (file-name-nondirectory (buffer-file-name))
1207 "tmp = /tmp/" str ".$pid" \n
1208 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1209 (sh (file-name-nondirectory (buffer-file-name))
1210 "TMP=/tmp/" str ".$$" \n
1211 "trap \"rm $TMP* 2>/dev/null\" " ?0))
1215 (define-skeleton sh-until
1216 "Insert an until loop. See `sh-feature'."
1218 '(setq input (sh-feature sh-test))
1219 "until " str "; do" \n
1222 (put 'sh-until 'menu-enable '(sh-feature sh-until))
1226 (define-skeleton sh-while
1227 "Insert a while loop. See `sh-feature'."
1228 (csh eval sh-modify sh
1232 (es eval sh-modify rc
1235 (rc eval sh-modify csh
1239 '(setq input (sh-feature sh-test))
1240 "while " str "; do" \n
1246 (define-skeleton sh-while-getopts
1247 "Insert a while getopts loop. See `sh-feature'.
1248 Prompts for an options string which consists of letters for each recognized
1249 option followed by a colon `:' if the option accepts an argument."
1250 (bash eval sh-modify sh
1254 > "switch( \"$1\" )" \n
1255 '(setq input '("- x" . 2))
1258 < "case " '(eval str)
1259 '(if (string-match " +" str)
1260 (setq v1 (substring str (match-end 0))
1261 str (substring str 0 (match-beginning 0)))
1264 > "set " v1 & " = $2" | -4 & _ \n
1265 (if v1 "shift") & \n
1275 (ksh88 eval sh-modify sh
1279 (posix eval sh-modify sh
1280 18 "$(basename $0)")
1282 "while getopts :" str " OPT; do" \n
1285 '(setq v1 (append (vconcat str) nil))
1286 ( (prog1 (if v1 (char-to-string (car v1)))
1287 (if (eq (nth 1 v1) ?:)
1288 (setq v1 (nthcdr 2 v1)
1292 < str "|+" str ?\) \n
1296 > "echo" " \"usage: " "`basename $0`"
1297 "[ +-" '(setq v1 (point)) str
1299 (while (search-backward ":" v1 t)
1300 (replace-match " arg][ +-" t t)))
1301 (if (eq (preceding-char) ?-) -5)
1306 "shift " (sh-add "OPTIND" -1)))
1307 (put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
1311 (defun sh-assignment (arg)
1312 "Remember preceding identifier for future completion and do self-insert."
1314 (self-insert-command arg)
1316 (sh-remember-variable
1318 (if (re-search-forward (sh-feature sh-assignment-regexp)
1320 (beginning-of-line 1))
1322 (match-string 1))))))
1326 (defun sh-maybe-here-document (arg)
1327 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1328 The document is bounded by `sh-here-document-word'."
1330 (self-insert-command (prefix-numeric-value arg))
1332 (not (eq (char-after (- (point) 2)) last-command-char))
1337 (insert sh-here-document-word)
1338 (or (eolp) (looking-at "[ \t]") (insert ? ))
1344 (save-excursion (insert ?\n sh-here-document-word)))))
1347 ;; various other commands
1349 (autoload 'comint-dynamic-complete "comint"
1350 "Dynamically perform completion at point." t)
1352 (autoload 'shell-dynamic-complete-command "shell"
1353 "Dynamically complete the command at point." t)
1355 (autoload 'comint-dynamic-complete-filename "comint"
1356 "Dynamically complete the filename at point." t)
1358 (autoload 'shell-dynamic-complete-environment-variable "shell"
1359 "Dynamically complete the environment variable at point." t)
1363 (defun sh-newline-and-indent ()
1364 "Strip unquoted whitespace, insert newline, and indent like current line."
1366 (indent-to (prog1 (current-indentation)
1367 (delete-region (point)
1369 (or (zerop (skip-chars-backward " \t"))
1377 (defun sh-beginning-of-command ()
1378 "Move point to successive beginnings of commands."
1380 (if (re-search-backward sh-beginning-of-command nil t)
1381 (goto-char (match-beginning 2))))
1384 (defun sh-end-of-command ()
1385 "Move point to successive ends of commands."
1387 (if (re-search-forward sh-end-of-command nil t)
1388 (goto-char (match-end 1))))
1390 (provide 'sh-script)
1391 ;; sh-script.el ends here