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-mode-hook nil
51 "*Hook run by `sh-mode'.")
53 (defvar sh-set-shell-hook nil
54 "*Hook run by `sh-set-shell'.")
56 (defvar sh-ancestor-alist
73 "*Alist showing the direct ancestor of various shells.
74 This is the basis for `sh-feature'. See also `sh-alias-alist'.
75 By default we have the following three hierarchies:
78 jcsh C Shell with Job Control
80 itcsh ? Toronto C Shell
85 jsh Bourne Shell with Job Control
86 bash GNU Bourne Again Shell
89 dtksh CDE Desktop Korn Shell
90 pdksh Public Domain Korn Shell
91 wksh Window Korn Shell
93 oash SCO OA (curses) Shell
94 posix IEEE 1003.2 Shell Standard
98 (defvar sh-alias-alist
99 (nconc (if (eq system-type
'gnu
/linux
)
102 ;; for the time being
105 "*Alist for transforming shell names to what they really are.
106 Use this where the name of the executable doesn't correspond to the type of
107 shell it really is.")
110 (defvar sh-shell-file
112 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
113 ;; the executable extension, so comparisons with the list of
114 ;; known shells work.
115 (and (memq system-type
'(ms-dos windows-nt
))
116 (file-name-sans-extension (downcase (getenv "SHELL"))))
119 "*The executable file name for the shell being programmed.")
123 ;; bash does not need any options when run in a shell script,
127 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
129 ;; -p means don't initialize functions from the environment.
131 ;; Someone proposed -motif, but we don't want to encourage
132 ;; use of a non-free widget set.
134 ;; -f means don't run .zshrc.
136 "*Single argument string for the magic number. See `sh-feature'.")
138 (defvar sh-shell-variables nil
139 "Alist of shell variable names that should be included in completion.
140 These are used for completion in addition to all the variables named
141 in `process-environment'. Each element looks like (VAR . VAR), where
142 the car and cdr are the same symbol.")
144 (defvar sh-shell-variables-initialized nil
145 "Non-nil if `sh-shell-variables' is initialized.")
147 (defun sh-canonicalize-shell (shell)
148 "Convert a shell name SHELL to the one we should handle it as."
150 (setq shell
(intern shell
)))
151 (or (cdr (assq shell sh-alias-alist
))
154 (defvar sh-shell
(sh-canonicalize-shell (file-name-nondirectory sh-shell-file
))
155 "The shell being programmed. This is set by \\[sh-set-shell].")
157 ;;; I turned off this feature because it doesn't permit typing commands
158 ;;; in the usual way without help.
159 ;;;(defvar sh-abbrevs
160 ;;; '((csh eval sh-abbrevs shell
161 ;;; "switch" 'sh-case
162 ;;; "getopts" 'sh-while-getopts)
164 ;;; (es eval sh-abbrevs shell
165 ;;; "function" 'sh-function)
167 ;;; (ksh88 eval sh-abbrevs sh
168 ;;; "select" 'sh-select)
170 ;;; (rc eval sh-abbrevs shell
172 ;;; "function" 'sh-function)
174 ;;; (sh eval sh-abbrevs shell
176 ;;; "function" 'sh-function
177 ;;; "until" 'sh-until
178 ;;; "getopts" 'sh-while-getopts)
180 ;;; ;; The next entry is only used for defining the others
181 ;;; (shell "for" sh-for
182 ;;; "loop" sh-indexed-loop
184 ;;; "tmpfile" sh-tmp-file
185 ;;; "while" sh-while)
187 ;;; (zsh eval sh-abbrevs ksh88
188 ;;; "repeat" 'sh-repeat))
189 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
190 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
191 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
195 (defvar sh-mode-syntax-table
196 '((sh eval sh-mode-syntax-table
()
203 ?$
"\\" ; `escape' so $# doesn't start a comment
210 (csh eval identity sh
)
211 (rc eval identity sh
))
212 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
217 (let ((map (make-sparse-keymap))
218 (menu-map (make-sparse-keymap "Insert")))
219 (define-key map
"\C-c(" 'sh-function
)
220 (define-key map
"\C-c\C-w" 'sh-while
)
221 (define-key map
"\C-c\C-u" 'sh-until
)
222 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
223 (define-key map
"\C-c\C-s" 'sh-select
)
224 (define-key map
"\C-c\C-r" 'sh-repeat
)
225 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
226 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
227 (define-key map
"\C-c\C-i" 'sh-if
)
228 (define-key map
"\C-c\C-f" 'sh-for
)
229 (define-key map
"\C-c\C-c" 'sh-case
)
231 (define-key map
"=" 'sh-assignment
)
232 (define-key map
"\C-c+" 'sh-add
)
233 (define-key map
"\C-\M-x" 'sh-execute-region
)
234 (define-key map
"\C-c\C-x" 'executable-interpret
)
235 (define-key map
"<" 'sh-maybe-here-document
)
236 (define-key map
"(" 'skeleton-pair-insert-maybe
)
237 (define-key map
"{" 'skeleton-pair-insert-maybe
)
238 (define-key map
"[" 'skeleton-pair-insert-maybe
)
239 (define-key map
"'" 'skeleton-pair-insert-maybe
)
240 (define-key map
"`" 'skeleton-pair-insert-maybe
)
241 (define-key map
"\"" 'skeleton-pair-insert-maybe
)
243 (define-key map
"\t" 'sh-indent-line
)
244 (substitute-key-definition 'complete-tag
'comint-dynamic-complete
245 map
(current-global-map))
246 (substitute-key-definition 'newline-and-indent
'sh-newline-and-indent
247 map
(current-global-map))
248 (substitute-key-definition 'delete-backward-char
249 'backward-delete-char-untabify
250 map
(current-global-map))
251 (define-key map
"\C-c:" 'sh-set-shell
)
252 (substitute-key-definition 'beginning-of-defun
253 'sh-beginning-of-compound-command
254 map
(current-global-map))
255 (substitute-key-definition 'backward-sentence
'sh-beginning-of-command
256 map
(current-global-map))
257 (substitute-key-definition 'forward-sentence
'sh-end-of-command
258 map
(current-global-map))
259 (define-key map
[menu-bar insert
] (cons "Insert" menu-map
))
260 (define-key menu-map
[sh-while
] '("While Loop" . sh-while
))
261 (define-key menu-map
[sh-until
] '("Until Loop" . sh-until
))
262 (define-key menu-map
[sh-tmp-file
] '("Temporary File" . sh-tmp-file
))
263 (define-key menu-map
[sh-select
] '("Select Statement" . sh-select
))
264 (define-key menu-map
[sh-repeat
] '("Repeat Loop" . sh-repeat
))
265 (define-key menu-map
[sh-while-getopts
]
266 '("Options Loop" . sh-while-getopts
))
267 (define-key menu-map
[sh-indexed-loop
]
268 '("Indexed Loop" . sh-indexed-loop
))
269 (define-key menu-map
[sh-if
] '("If Statement" . sh-if
))
270 (define-key menu-map
[sh-for
] '("For Loop" . sh-for
))
271 (define-key menu-map
[sh-case
] '("Case Statement" . sh-case
))
273 "Keymap used in Shell-Script mode.")
277 (defvar sh-dynamic-complete-functions
278 '(shell-dynamic-complete-environment-variable
279 shell-dynamic-complete-command
280 comint-dynamic-complete-filename
)
281 "*Functions for doing TAB dynamic completion.")
284 (defvar sh-require-final-newline
287 (rc eval . require-final-newline
)
288 (sh eval . require-final-newline
))
289 "*Value of `require-final-newline' in Shell-Script mode buffers.
293 (defvar sh-assignment-regexp
294 '((csh .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
295 ;; actually spaces are only supported in let/(( ... ))
296 (ksh88 .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
297 (rc .
"\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
298 (sh .
"\\<\\([a-zA-Z0-9_]+\\)="))
299 "*Regexp for the variable name and what may follow in an assignment.
300 First grouping matches the variable name. This is upto and including the `='
301 sign. See `sh-feature'.")
304 (defvar sh-indentation
4
305 "The width for further indentation in Shell-Script mode.")
308 (defvar sh-remember-variable-min
3
309 "*Don't remember variables less than this length for completing reads.")
312 (defvar sh-header-marker nil
313 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
314 That command is also used for setting this variable.")
317 (defvar sh-beginning-of-command
318 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
319 "*Regexp to determine the beginning of a shell command.
320 The actual command starts at the beginning of the second \\(grouping\\).")
323 (defvar sh-end-of-command
324 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
325 "*Regexp to determine the end of a shell command.
326 The actual command ends at the end of the first \\(grouping\\).")
330 (defvar sh-here-document-word
"EOF"
331 "Word to delimit here documents.")
336 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
340 '((bash eval sh-append posix
341 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
342 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
343 "suspend" "typeset" "unalias")
345 ;; The next entry is only used for defining the others
346 (bourne eval sh-append shell
347 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
350 (csh eval sh-append shell
351 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
352 "setenv" "source" "time" "unalias" "unhash")
354 (dtksh eval identity wksh
)
356 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
357 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
359 (jsh eval sh-append sh
360 "bg" "fg" "jobs" "kill" "stop" "suspend")
362 (jcsh eval sh-append csh
363 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
365 (ksh88 eval sh-append bourne
366 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
367 "typeset" "unalias" "whence")
369 (oash eval sh-append sh
370 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
371 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
372 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
373 "wmtitle" "wrefresh")
375 (pdksh eval sh-append ksh88
378 (posix eval sh-append sh
381 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
384 (sh eval sh-append bourne
385 "hash" "test" "type")
387 ;; The next entry is only used for defining the others
388 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
390 (wksh eval sh-append ksh88
393 (zsh eval sh-append ksh88
394 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
395 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
396 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
397 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
398 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
400 "*List of all shell builtins for completing read and fontification.
401 Note that on some systems not all builtins are available or some are
402 implemented as aliases. See `sh-feature'.")
406 (defvar sh-leading-keywords
409 (es "true" "unwind-protect" "whatis")
413 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
414 "*List of keywords that may be immediately followed by a builtin or keyword.
415 Given some confusion between keywords and builtins depending on shell and
416 system, the distinction here has been based on whether they influence the
417 flow of control or syntax. See `sh-feature'.")
420 (defvar sh-other-keywords
421 '((bash eval sh-append bourne
424 ;; The next entry is only used for defining the others
425 (bourne eval sh-append sh
428 (csh eval sh-append shell
429 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
430 "if" "logout" "onintr" "repeat" "switch" "then" "while")
432 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
433 "return" "throw" "while")
435 (ksh88 eval sh-append bourne
438 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
441 (sh eval sh-append shell
442 "done" "esac" "fi" "for" "in" "return")
444 ;; The next entry is only used for defining the others
445 (shell "break" "case" "continue" "exec" "exit")
447 (zsh eval sh-append bash
449 "*List of keywords not in `sh-leading-keywords'.
455 '((bash eval sh-append sh
456 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
457 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
458 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
459 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
460 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
461 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
462 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
463 "SECONDS" "SHLVL" "TMOUT" "UID")
465 (csh eval sh-append shell
466 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
467 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
468 "shell" "status" "time" "verbose")
470 (es eval sh-append shell
471 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
472 "pid" "prompt" "signals")
474 (jcsh eval sh-append csh
477 (ksh88 eval sh-append sh
478 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
479 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
482 (oash eval sh-append sh
483 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
485 (rc eval sh-append shell
486 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
489 (sh eval sh-append shell
490 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
492 ;; The next entry is only used for defining the others
493 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
494 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
495 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
496 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
498 (tcsh eval sh-append csh
499 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
500 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
501 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
502 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
503 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
504 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
505 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
506 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
509 (zsh eval sh-append ksh88
510 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
511 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
512 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
513 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
514 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
515 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
516 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
517 "List of all shell variables available for completing read.
522 (defvar sh-font-lock-keywords
523 '((csh eval sh-append shell
524 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
525 font-lock-variable-name-face
))
527 (es eval sh-append executable-font-lock-keywords
528 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
529 font-lock-variable-name-face
))
531 (rc eval identity es
)
533 (sh eval sh-append shell
534 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
535 font-lock-variable-name-face
))
537 ;; The next entry is only used for defining the others
538 (shell eval sh-append executable-font-lock-keywords
539 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face
)
540 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
541 font-lock-variable-name-face
)))
542 "*Rules for highlighting shell scripts. See `sh-feature'.")
544 (defvar sh-font-lock-keywords-1
546 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
548 (defvar sh-font-lock-keywords-2
()
549 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
552 ;; mode-command and utility functions
555 (put 'sh-mode
'mode-class
'special
)
559 "Major mode for editing shell scripts.
560 This mode works for many shells, since they all have roughly the same syntax,
561 as far as commands, arguments, variables, pipes, comments etc. are concerned.
562 Unless the file's magic number indicates the shell, your usual shell is
563 assumed. Since filenames rarely give a clue, they are not further analyzed.
565 This mode adapts to the variations between shells (see `sh-set-shell') by
566 means of an inheritance based feature lookup (see `sh-feature'). This
567 mechanism applies to all variables (including skeletons) that pertain to
568 shell-specific features.
570 The default style of this mode is that of Rosenblatt's Korn shell book.
571 The syntax of the statements varies with the shell being used. The
572 following commands are available, based on the current shell's syntax:
574 \\[sh-case] case statement
576 \\[sh-function] function definition
577 \\[sh-if] if statement
578 \\[sh-indexed-loop] indexed loop from 1 to n
579 \\[sh-while-getopts] while getopts loop
580 \\[sh-repeat] repeat loop
581 \\[sh-select] select loop
582 \\[sh-until] until loop
583 \\[sh-while] while loop
585 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
586 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
587 \\[sh-end-of-command] Go to end of successive commands.
588 \\[sh-beginning-of-command] Go to beginning of successive commands.
589 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
590 \\[sh-execute-region] Have optional header and region be executed in a subshell.
592 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
594 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
596 If you generally program a shell different from your login shell you can
597 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
598 indicate what shell it is use `sh-alias-alist' to translate.
600 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
601 with your script for an edit-interpret-debug cycle."
603 (kill-all-local-variables)
604 (use-local-map sh-mode-map
)
605 (make-local-variable 'indent-line-function
)
606 (make-local-variable 'indent-region-function
)
607 (make-local-variable 'skeleton-end-hook
)
608 (make-local-variable 'paragraph-start
)
609 (make-local-variable 'paragraph-separate
)
610 (make-local-variable 'comment-start
)
611 (make-local-variable 'comment-start-skip
)
612 (make-local-variable 'require-final-newline
)
613 (make-local-variable 'sh-header-marker
)
614 (make-local-variable 'sh-shell-file
)
615 (make-local-variable 'sh-shell
)
616 (make-local-variable 'skeleton-pair-alist
)
617 (make-local-variable 'skeleton-pair-filter
)
618 (make-local-variable 'comint-dynamic-complete-functions
)
619 (make-local-variable 'comint-prompt-regexp
)
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
)
650 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")))
651 skeleton-pair-alist
'((?
` _ ?
`))
652 skeleton-pair-filter
'sh-quoted-p
653 skeleton-further-elements
'((< '(- (min sh-indentation
655 skeleton-filter
'sh-feature
656 skeleton-newline-indent-rigidly t
)
657 ;; Parse or insert magic number for exec, and set all variables depending
658 ;; on the shell thus determined.
661 (goto-char (point-min))
662 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
663 (buffer-substring (match-beginning 2)
666 (sh-set-shell interpreter nil nil
)))
667 (run-hooks 'sh-mode-hook
))
669 (defalias 'shell-script-mode
'sh-mode
)
672 (defun sh-font-lock-keywords (&optional keywords
)
673 "Function to get simple fontification based on `sh-font-lock-keywords'.
674 This adds rules for comments and assignments."
675 (sh-feature sh-font-lock-keywords
677 `((,(sh-feature sh-assignment-regexp
)
678 1 font-lock-variable-name-face
)
682 (defun sh-font-lock-keywords-1 (&optional builtins
)
683 "Function to get better fontification including keywords."
684 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
686 (sh-feature sh-leading-keywords
)
690 (append (sh-feature sh-leading-keywords
)
691 (sh-feature sh-other-keywords
))
694 (sh-font-lock-keywords
696 `((,(concat keywords
"[ \t]+\\)?\\("
697 (mapconcat 'identity
(sh-feature sh-builtins
) "\\|")
699 (2 font-lock-keyword-face nil t
)
700 (6 font-lock-builtin-face
))
701 ,@(sh-feature sh-font-lock-keywords-2
)))
702 (,(concat keywords
"\\)\\>")
703 2 font-lock-keyword-face
)
704 ,@(sh-feature sh-font-lock-keywords-1
)))))
706 (defun sh-font-lock-keywords-2 ()
707 "Function to get better fontification including keywords and builtins."
708 (sh-font-lock-keywords-1 t
))
711 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
712 "Set this buffer's shell to SHELL (a string).
713 Makes this script executable via `executable-set-magic', and sets up the
714 proper starting #!-line, if INSERT-FLAG is non-nil.
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
))
726 (executable-set-magic shell
(sh-feature sh-shell-arg
)
727 no-query-flag insert-flag
)))
728 (setq require-final-newline
(sh-feature sh-require-final-newline
)
729 ;;; local-abbrev-table (sh-feature sh-abbrevs)
730 font-lock-keywords nil
; force resetting
731 font-lock-syntax-table nil
732 comment-start-skip
"#+[\t ]*"
733 mode-line-process
(format "[%s]" sh-shell
)
734 sh-shell-variables nil
735 sh-shell-variables-initialized nil
736 shell
(sh-feature sh-variables
))
737 (set-syntax-table (sh-feature sh-mode-syntax-table
))
739 (sh-remember-variable (car shell
))
740 (setq shell
(cdr shell
)))
741 (and (boundp 'font-lock-mode
)
743 (font-lock-mode (font-lock-mode 0)))
744 (run-hooks 'sh-set-shell-hook
))
748 (defun sh-feature (list &optional function
)
749 "Index ALIST by the current shell.
750 If ALIST isn't a list where every element is a cons, it is returned as is.
751 Else indexing follows an inheritance logic which works in two ways:
753 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
754 the alist contains no value for the current shell.
756 - If the value thus looked up is a list starting with `eval' its `cdr' is
757 first evaluated. If that is also a list and the first argument is a
758 symbol in ALIST it is not evaluated, but rather recursively looked up in
759 ALIST to allow the function called to define the value for one shell to be
760 derived from another shell. While calling the function, is the car of the
761 alist element is the current shell.
762 The value thus determined is physically replaced into the alist.
764 Optional FUNCTION is applied to the determined value and the result is cached
768 (while (and l
(consp (car l
)))
772 (cdr (assoc (setq function
(cons sh-shell function
)) list
)))
773 (let ((sh-shell sh-shell
)
776 (not (setq elt
(assq sh-shell list
))))
777 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
778 (if (and (consp (setq val
(cdr elt
)))
779 (eq (car val
) 'eval
))
782 (eval (if (consp (setq val
(cdr val
)))
783 (let ((sh-shell (car (cdr val
)))
785 (if (assq sh-shell list
)
794 (setq sh-shell
(car function
)
795 val
(funcall (cdr function
) val
))))))
800 ;;; I commented this out because nobody calls it -- rms.
801 ;;;(defun sh-abbrevs (ancestor &rest list)
802 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
803 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
804 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
805 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
806 ;;;EXPANSION may be either a string or a skeleton command."
807 ;;; (or (if (boundp sh-shell)
808 ;;; (symbol-value sh-shell))
810 ;;; (if (listp ancestor)
811 ;;; (nconc list ancestor))
812 ;;; (define-abbrev-table sh-shell ())
813 ;;; (if (vectorp ancestor)
814 ;;; (mapatoms (lambda (atom)
816 ;;; (define-abbrev (symbol-value sh-shell)
817 ;;; (symbol-name atom)
818 ;;; (symbol-value atom)
819 ;;; (symbol-function atom))))
822 ;;; (define-abbrev (symbol-value sh-shell)
824 ;;; (if (stringp (car (cdr list)))
827 ;;; (if (symbolp (car (cdr list)))
828 ;;; (car (cdr list))))
829 ;;; (setq list (cdr (cdr list)))))
830 ;;; (symbol-value sh-shell)))
833 (defun sh-mode-syntax-table (table &rest list
)
834 "Copy TABLE and set syntax for successive CHARs according to strings S."
835 (setq table
(copy-syntax-table table
))
837 (modify-syntax-entry (car list
) (car (cdr list
)) table
)
838 (setq list
(cdr (cdr list
))))
842 (defun sh-append (ancestor &rest list
)
843 "Return list composed of first argument (a list) physically appended to rest."
844 (nconc list ancestor
))
847 (defun sh-modify (skeleton &rest list
)
848 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
849 (setq skeleton
(copy-sequence skeleton
))
851 (setcar (or (nthcdr (car list
) skeleton
)
852 (error "Index %d out of bounds" (car list
)))
854 (setq list
(nthcdr 2 list
)))
858 (defun sh-indent-line ()
859 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
860 Lines containing only comments are considered empty."
862 (let ((previous (save-excursion
863 (while (and (not (bobp))
866 (back-to-indentation)
868 (eq (following-char) ?
#)))))
872 (indent-to (if (eq this-command
'newline-and-indent
)
874 (if (< (current-column)
875 (setq current
(progn (back-to-indentation)
877 (if (eolp) previous
0)
878 (delete-region (point)
879 (progn (beginning-of-line) (point)))
881 (max previous
(* (1+ (/ current sh-indentation
))
883 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
884 (if (< (current-column) (current-indentation))
885 (skip-chars-forward " \t"))))
888 (defun sh-execute-region (start end
&optional flag
)
889 "Pass optional header and region to a subshell for noninteractive execution.
890 The working directory is that of the buffer, and only environment variables
891 are already set which is why you can mark a header within the script.
893 With a positive prefix ARG, instead of sending region, define header from
894 beginning of buffer to point. With a negative prefix ARG, instead of sending
895 region, clear header."
898 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
902 (let (buffer-undo-list)
903 (goto-char sh-header-marker
)
904 (append-to-buffer (current-buffer) start end
)
905 (shell-command-on-region (point-min)
906 (setq end
(+ sh-header-marker
909 (delete-region sh-header-marker end
)))
910 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
913 (defun sh-remember-variable (var)
914 "Make VARIABLE available for future completing reads in this buffer."
915 (or (< (length var
) sh-remember-variable-min
)
917 (assoc var sh-shell-variables
)
918 (setq sh-shell-variables
(cons (cons var var
) sh-shell-variables
)))
923 (defun sh-quoted-p ()
924 "Is point preceded by an odd number of backslashes?"
925 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
927 ;; statement syntax-commands for various shells
929 ;; You are welcome to add the syntax or even completely new statements as
930 ;; appropriate for your favorite shell.
932 (define-skeleton sh-case
933 "Insert a case/switch statement. See `sh-feature'."
935 "switch( " str
" )" \n
936 > "case " (read-string "pattern: ") ?
: \n
939 ( "other pattern, %s: "
949 "switch( " str
" ) {" \n
950 > "case " (read-string "pattern: ") \n
952 ( "other pattern, %s: "
961 > (read-string "pattern: ") ?\
) \n
964 ( "other pattern, %s: "
972 (put 'sh-case
'menu-enable
'(sh-feature sh-case
))
976 (define-skeleton sh-for
977 "Insert a for loop. See `sh-feature'."
978 (csh eval sh-modify sh
983 (es eval sh-modify rc
985 (rc eval sh-modify sh
989 (sh "Index variable: "
990 "for " str
" in " _
"; do" \n
991 > _ | ?$
& (sh-remember-variable str
) \n
996 (define-skeleton sh-indexed-loop
997 "Insert an indexed loop from 1 to n. See `sh-feature'."
998 (bash eval identity posix
)
999 (csh "Index variable: "
1001 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
1005 (es eval sh-modify rc
1007 (ksh88 "Index variable: "
1008 "integer " str
"=0" \n
1009 "while (( ( " str
" += 1 ) <= "
1010 (read-string "upper limit: ")
1012 > _ ?$
(sh-remember-variable str
) \n
1014 (posix "Index variable: "
1016 "while [ $" str
" -le "
1017 (read-string "upper limit: ")
1020 str ?
= (sh-add (sh-remember-variable str
) 1) \n
1022 (rc "Index variable: "
1023 "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
1024 (read-string "upper limit: ")
1025 "; i++ ) print i }'}) {" \n
1026 > _ ?$
(sh-remember-variable str
) \n
1028 (sh "Index variable: "
1029 "for " str
" in `awk 'BEGIN { for( i=1; i<="
1030 (read-string "upper limit: ")
1031 "; i++ ) print i }'`; do" \n
1032 > _ ?$
(sh-remember-variable str
) \n
1036 (defun sh-shell-initialize-variables ()
1037 "Scan the buffer for variable assignments.
1038 Add these variables to `sh-shell-variables'."
1039 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
1041 (goto-char (point-min))
1042 (setq sh-shell-variables-initialized t
)
1043 (while (search-forward "=" nil t
)
1045 (message "Scanning buffer `%s' for variable assignments...done"
1048 (defvar sh-add-buffer
)
1050 (defun sh-add-completer (string predicate code
)
1051 "Do completion using `sh-shell-variables', but initialize it first.
1052 This function is designed for use as the \"completion table\",
1053 so it takes three arguments:
1054 STRING, the current buffer contents;
1055 PREDICATE, the predicate for filtering possible matches;
1056 CODE, which says what kind of things to do.
1057 CODE can be nil, t or `lambda'.
1058 nil means to return the best completion of STRING, or nil if there is none.
1059 t means to return a list of all possible completions of STRING.
1060 `lambda' means to return t if STRING is a valid completion as it stands."
1061 (let ((sh-shell-variables
1063 (set-buffer sh-add-buffer
)
1064 (or sh-shell-variables-initialized
1065 (sh-shell-initialize-variables))
1066 (nconc (mapcar (lambda (var)
1068 (substring var
0 (string-match "=" var
))))
1070 process-environment
)
1071 sh-shell-variables
))))
1073 (try-completion string sh-shell-variables predicate
))
1075 (all-completions string sh-shell-variables predicate
))
1077 (assoc string sh-shell-variables
)))))
1079 (defun sh-add (var delta
)
1080 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1082 (let ((sh-add-buffer (current-buffer)))
1083 (list (completing-read "Variable: " 'sh-add-completer
)
1084 (prefix-numeric-value current-prefix-arg
))))
1085 (insert (sh-feature '((bash .
"$[ ")
1091 (sh-remember-variable var
)
1092 (if (< delta
0) " - " " + ")
1093 (number-to-string (abs delta
))
1094 (sh-feature '((bash .
" ]")
1103 (define-skeleton sh-function
1104 "Insert a function definition. See `sh-feature'."
1105 (bash eval sh-modify ksh88
1108 "function " str
" {" \n
1111 (rc eval sh-modify ksh88
1120 (define-skeleton sh-if
1121 "Insert an if statement. See `sh-feature'."
1123 "if( " str
" ) then" \n
1125 ( "other condition, %s: "
1126 < "else if( " str
" ) then" \n
1133 "if { " str
" } {" \n
1135 ( "other condition, %s: "
1136 < "} { " str
" } {" \n
1142 (rc eval sh-modify csh
1144 8 '( "other condition, %s: "
1145 < "} else if( " str
" ) {" \n
1150 '(setq input
(sh-feature sh-test
))
1151 "if " str
"; then" \n
1153 ( "other condition, %s: "
1154 < "elif " str
"; then" \n
1163 (define-skeleton sh-repeat
1164 "Insert a repeat loop definition. See `sh-feature'."
1170 "repeat " str
"; do"\n
1173 (put 'sh-repeat
'menu-enable
'(sh-feature sh-repeat
))
1177 (define-skeleton sh-select
1178 "Insert a select statement. See `sh-feature'."
1179 (ksh88 "Index variable: "
1180 "select " str
" in " _
"; do" \n
1183 (put 'sh-select
'menu-enable
'(sh-feature sh-select
))
1187 (define-skeleton sh-tmp-file
1188 "Insert code to setup temporary file handling. See `sh-feature'."
1189 (bash eval identity ksh88
)
1190 (csh (file-name-nondirectory (buffer-file-name))
1191 "set tmp = /tmp/" str
".$$" \n
1193 (and (goto-char (point-max))
1197 "rm $tmp* >&/dev/null" >)
1198 (es (file-name-nondirectory (buffer-file-name))
1199 "local( signals = $signals sighup sigint; tmp = /tmp/" str
".$pid ) {" \n
1201 > "rm $tmp^* >[2]/dev/null" \n
1207 (ksh88 eval sh-modify sh
1209 (rc (file-name-nondirectory (buffer-file-name))
1210 "tmp = /tmp/" str
".$pid" \n
1211 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1212 (sh (file-name-nondirectory (buffer-file-name))
1213 "TMP=/tmp/" str
".$$" \n
1214 "trap \"rm $TMP* 2>/dev/null\" " ?
0))
1218 (define-skeleton sh-until
1219 "Insert an until loop. See `sh-feature'."
1221 '(setq input
(sh-feature sh-test
))
1222 "until " str
"; do" \n
1225 (put 'sh-until
'menu-enable
'(sh-feature sh-until
))
1229 (define-skeleton sh-while
1230 "Insert a while loop. See `sh-feature'."
1231 (csh eval sh-modify sh
1235 (es eval sh-modify rc
1238 (rc eval sh-modify csh
1242 '(setq input
(sh-feature sh-test
))
1243 "while " str
"; do" \n
1249 (define-skeleton sh-while-getopts
1250 "Insert a while getopts loop. See `sh-feature'.
1251 Prompts for an options string which consists of letters for each recognized
1252 option followed by a colon `:' if the option accepts an argument."
1253 (bash eval sh-modify sh
1257 > "switch( \"$1\" )" \n
1258 '(setq input
'("- x" .
2))
1261 < "case " '(eval str
)
1262 '(if (string-match " +" str
)
1263 (setq v1
(substring str
(match-end 0))
1264 str
(substring str
0 (match-beginning 0)))
1267 > "set " v1
& " = $2" | -
4 & _
\n
1268 (if v1
"shift") & \n
1278 (ksh88 eval sh-modify sh
1282 (posix eval sh-modify sh
1283 18 "$(basename $0)")
1285 "while getopts :" str
" OPT; do" \n
1288 '(setq v1
(append (vconcat str
) nil
))
1289 ( (prog1 (if v1
(char-to-string (car v1
)))
1290 (if (eq (nth 1 v1
) ?
:)
1291 (setq v1
(nthcdr 2 v1
)
1295 < str
"|+" str ?\
) \n
1299 > "echo" " \"usage: " "`basename $0`"
1300 " [+-" '(setq v1
(point)) str
1302 (while (search-backward ":" v1 t
)
1303 (replace-match " ARG] [+-" t t
)))
1304 (if (eq (preceding-char) ?-
) -
5)
1305 "] [--] ARGS...\"" \n
1309 "shift " (sh-add "OPTIND" -
1)))
1310 (put 'sh-while-getopts
'menu-enable
'(sh-feature sh-while-getopts
))
1314 (defun sh-assignment (arg)
1315 "Remember preceding identifier for future completion and do self-insert."
1317 (self-insert-command arg
)
1319 (sh-remember-variable
1321 (if (re-search-forward (sh-feature sh-assignment-regexp
)
1323 (beginning-of-line 1))
1325 (match-string 1))))))
1329 (defun sh-maybe-here-document (arg)
1330 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1331 The document is bounded by `sh-here-document-word'."
1333 (self-insert-command (prefix-numeric-value arg
))
1335 (not (eq (char-after (- (point) 2)) last-command-char
))
1340 (insert sh-here-document-word
)
1341 (or (eolp) (looking-at "[ \t]") (insert ?
))
1347 (save-excursion (insert ?
\n sh-here-document-word
)))))
1350 ;; various other commands
1352 (autoload 'comint-dynamic-complete
"comint"
1353 "Dynamically perform completion at point." t
)
1355 (autoload 'shell-dynamic-complete-command
"shell"
1356 "Dynamically complete the command at point." t
)
1358 (autoload 'comint-dynamic-complete-filename
"comint"
1359 "Dynamically complete the filename at point." t
)
1361 (autoload 'shell-dynamic-complete-environment-variable
"shell"
1362 "Dynamically complete the environment variable at point." t
)
1366 (defun sh-newline-and-indent ()
1367 "Strip unquoted whitespace, insert newline, and indent like current line."
1369 (indent-to (prog1 (current-indentation)
1370 (delete-region (point)
1372 (or (zerop (skip-chars-backward " \t"))
1380 (defun sh-beginning-of-command ()
1381 "Move point to successive beginnings of commands."
1383 (if (re-search-backward sh-beginning-of-command nil t
)
1384 (goto-char (match-beginning 2))))
1387 (defun sh-end-of-command ()
1388 "Move point to successive ends of commands."
1390 (if (re-search-forward sh-end-of-command nil t
)
1391 (goto-char (match-end 1))))
1393 (provide 'sh-script
)
1394 ;; sh-script.el ends here