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.")
111 (ksh88 eval progn nil
(if (file-exists-p "/etc/suid_profile") nil
"-p"))
116 "*Single argument string for the magic number. See `sh-feature'.")
120 (defun sh-canonicalize-shell (shell)
121 "Convert a shell name SHELL to the one we should handle it as."
123 (setq shell
(intern shell
)))
124 (or (cdr (assq shell sh-alias-alist
))
127 (defvar sh-shell
(sh-canonicalize-shell (file-name-nondirectory sh-shell-file
))
128 "The shell being programmed. This is set by \\[sh-set-shell].")
130 ;;; I turned off this feature because it doesn't permit typing commands
131 ;;; in the usual way without help.
132 ;;;(defvar sh-abbrevs
133 ;;; '((csh eval sh-abbrevs shell
134 ;;; "switch" 'sh-case
135 ;;; "getopts" 'sh-while-getopts)
137 ;;; (es eval sh-abbrevs shell
138 ;;; "function" 'sh-function)
140 ;;; (ksh88 eval sh-abbrevs sh
141 ;;; "select" 'sh-select)
143 ;;; (rc eval sh-abbrevs shell
145 ;;; "function" 'sh-function)
147 ;;; (sh eval sh-abbrevs shell
149 ;;; "function" 'sh-function
150 ;;; "until" 'sh-until
151 ;;; "getopts" 'sh-while-getopts)
153 ;;; ;; The next entry is only used for defining the others
154 ;;; (shell "for" sh-for
155 ;;; "loop" sh-indexed-loop
157 ;;; "tmpfile" sh-tmp-file
158 ;;; "while" sh-while)
160 ;;; (zsh eval sh-abbrevs ksh88
161 ;;; "repeat" 'sh-repeat))
162 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
163 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
164 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
168 (defvar sh-mode-syntax-table
169 '((csh eval identity sh
)
170 (sh eval sh-mode-syntax-table
()
171 ;; #'s meanings depend on context which can't be expressed here
185 (rc eval sh-mode-syntax-table sh
188 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
193 (let ((map (make-sparse-keymap))
194 (menu-map (make-sparse-keymap "Insert")))
195 (define-key map
"\C-c(" 'sh-function
)
196 (define-key map
"\C-c\C-w" 'sh-while
)
197 (define-key map
"\C-c\C-u" 'sh-until
)
198 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
199 (define-key map
"\C-c\C-s" 'sh-select
)
200 (define-key map
"\C-c\C-r" 'sh-repeat
)
201 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
202 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
203 (define-key map
"\C-c\C-i" 'sh-if
)
204 (define-key map
"\C-c\C-f" 'sh-for
)
205 (define-key map
"\C-c\C-c" 'sh-case
)
207 (define-key map
"=" 'sh-assignment
)
208 (define-key map
"\C-c+" 'sh-add
)
209 (define-key map
"\C-\M-x" 'sh-execute-region
)
210 (define-key map
"\C-c\C-x" 'executable-interpret
)
211 (define-key map
"<" 'sh-maybe-here-document
)
212 (define-key map
"(" 'skeleton-pair-insert-maybe
)
213 (define-key map
"{" 'skeleton-pair-insert-maybe
)
214 (define-key map
"[" 'skeleton-pair-insert-maybe
)
215 (define-key map
"'" 'skeleton-pair-insert-maybe
)
216 (define-key map
"`" 'skeleton-pair-insert-maybe
)
217 (define-key map
"\"" 'skeleton-pair-insert-maybe
)
219 (define-key map
"\t" 'sh-indent-line
)
220 (substitute-key-definition 'complete-tag
'comint-dynamic-complete
221 map
(current-global-map))
222 (substitute-key-definition 'newline-and-indent
'sh-newline-and-indent
223 map
(current-global-map))
224 (substitute-key-definition 'delete-backward-char
225 'backward-delete-char-untabify
226 map
(current-global-map))
227 (define-key map
"\C-c:" 'sh-set-shell
)
228 (substitute-key-definition 'beginning-of-defun
229 'sh-beginning-of-compound-command
230 map
(current-global-map))
231 (substitute-key-definition 'backward-sentence
'sh-beginning-of-command
232 map
(current-global-map))
233 (substitute-key-definition 'forward-sentence
'sh-end-of-command
234 map
(current-global-map))
235 (define-key map
[menu-bar insert
] (cons "Insert" menu-map
))
236 (define-key menu-map
[sh-while
] '("While Loop" . sh-while
))
237 (define-key menu-map
[sh-until
] '("Until Loop" . sh-until
))
238 (define-key menu-map
[sh-tmp-file
] '("Temporary File" . sh-tmp-file
))
239 (define-key menu-map
[sh-select
] '("Select Statement" . sh-select
))
240 (define-key menu-map
[sh-repeat
] '("Repeat Loop" . sh-repeat
))
241 (define-key menu-map
[sh-while-getopts
]
242 '("Options Loop" . sh-while-getopts
))
243 (define-key menu-map
[sh-indexed-loop
]
244 '("Indexed Loop" . sh-indexed-loop
))
245 (define-key menu-map
[sh-if
] '("If Statement" . sh-if
))
246 (define-key menu-map
[sh-for
] '("For Loop" . sh-for
))
247 (define-key menu-map
[sh-case
] '("Case Statement" . sh-case
))
249 "Keymap used in Shell-Script mode.")
253 (defvar sh-dynamic-complete-functions
254 '(shell-dynamic-complete-environment-variable
255 shell-dynamic-complete-command
256 comint-dynamic-complete-filename
)
257 "*Functions for doing TAB dynamic completion.")
260 (defvar sh-require-final-newline
263 (rc eval . require-final-newline
)
264 (sh eval . require-final-newline
))
265 "*Value of `require-final-newline' in Shell-Script mode buffers.
269 (defvar sh-comment-prefix
270 '((csh .
"\\(^\\|[^$]\\|\\$[^{]\\)")
271 (rc eval identity csh
)
272 (sh .
"\\(^\\|[ \t|&;()]\\)"))
273 "*Regexp matching what may come before a comment `#'.
274 This must contain one \\(grouping\\) since it is the basis for fontifying
275 comments as well as for `comment-start-skip'.
279 (defvar sh-assignment-regexp
280 '((csh .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
281 ;; actually spaces are only supported in let/(( ... ))
282 (ksh88 .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
283 (rc .
"\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
284 (sh .
"\\<\\([a-zA-Z0-9_]+\\)="))
285 "*Regexp for the variable name and what may follow in an assignment.
286 First grouping matches the variable name. This is upto and including the `='
287 sign. See `sh-feature'.")
290 (defvar sh-indentation
4
291 "The width for further indentation in Shell-Script mode.")
294 (defvar sh-remember-variable-min
3
295 "*Don't remember variables less than this length for completing reads.")
298 (defvar sh-header-marker nil
299 "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
300 That command is also used for setting this variable.")
303 (defvar sh-beginning-of-command
304 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
305 "*Regexp to determine the beginning of a shell command.
306 The actual command starts at the beginning of the second \\(grouping\\).")
309 (defvar sh-end-of-command
310 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
311 "*Regexp to determine the end of a shell command.
312 The actual command ends at the end of the first \\(grouping\\).")
316 (defvar sh-here-document-word
"EOF"
317 "Word to delimit here documents.")
322 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
326 '((bash eval sh-append posix
327 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
328 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
329 "suspend" "typeset" "unalias")
331 ;; The next entry is only used for defining the others
332 (bourne eval sh-append shell
333 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
336 (csh eval sh-append shell
337 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
338 "setenv" "source" "time" "unalias" "unhash")
340 (dtksh eval identity wksh
)
342 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
343 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
345 (jsh eval sh-append sh
346 "bg" "fg" "jobs" "kill" "stop" "suspend")
348 (jcsh eval sh-append csh
349 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
351 (ksh88 eval sh-append bourne
352 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
353 "typeset" "unalias" "whence")
355 (oash eval sh-append sh
356 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
357 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
358 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
359 "wmtitle" "wrefresh")
361 (pdksh eval sh-append ksh88
364 (posix eval sh-append sh
367 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
370 (sh eval sh-append bourne
371 "hash" "test" "type")
373 ;; The next entry is only used for defining the others
374 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
376 (wksh eval sh-append ksh88
379 (zsh eval sh-append ksh88
380 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
381 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
382 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
383 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
384 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
386 "*List of all shell builtins for completing read and fontification.
387 Note that on some systems not all builtins are available or some are
388 implemented as aliases. See `sh-feature'.")
392 (defvar sh-leading-keywords
395 (es "true" "unwind-protect" "whatis")
399 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
400 "*List of keywords that may be immediately followed by a builtin or keyword.
401 Given some confusion between keywords and builtins depending on shell and
402 system, the distinction here has been based on whether they influence the
403 flow of control or syntax. See `sh-feature'.")
406 (defvar sh-other-keywords
407 '((bash eval sh-append bourne
410 ;; The next entry is only used for defining the others
411 (bourne eval sh-append shell
412 "done" "esac" "fi" "for" "function" "in" "return")
414 (csh eval sh-append shell
415 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
416 "if" "logout" "onintr" "repeat" "switch" "then" "while")
418 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
419 "return" "throw" "while")
421 (ksh88 eval sh-append bourne
424 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
427 ;; The next entry is only used for defining the others
428 (shell "break" "case" "continue" "exec" "exit")
430 (zsh eval sh-append bash
432 "*List of keywords not in `sh-leading-keywords'.
438 '((bash eval sh-append sh
439 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
440 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
441 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
442 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
443 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
444 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
445 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
446 "SECONDS" "SHLVL" "TMOUT" "UID")
448 (csh eval sh-append shell
449 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
450 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
451 "shell" "status" "time" "verbose")
453 (es eval sh-append shell
454 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
455 "pid" "prompt" "signals")
457 (jcsh eval sh-append csh
460 (ksh88 eval sh-append sh
461 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
462 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
465 (oash eval sh-append sh
466 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
468 (rc eval sh-append shell
469 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
472 (sh eval sh-append shell
473 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
475 ;; The next entry is only used for defining the others
476 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
477 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
478 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
479 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
481 (tcsh eval sh-append csh
482 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
483 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
484 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
485 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
486 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
487 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
488 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
489 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
492 (zsh eval sh-append ksh88
493 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
494 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
495 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
496 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
497 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
498 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
499 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
500 "List of all shell variables available for completing read.
505 (defvar sh-font-lock-keywords
506 '((csh eval sh-append shell
507 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
508 font-lock-variable-name-face
))
510 (es eval sh-append executable-font-lock-keywords
511 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
512 font-lock-variable-name-face
))
514 (rc eval identity es
)
516 (sh eval sh-append shell
517 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
518 font-lock-variable-name-face
))
520 ;; The next entry is only used for defining the others
521 (shell eval sh-append executable-font-lock-keywords
522 '("\\\\." 0 font-lock-string-face
)
523 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
524 font-lock-variable-name-face
)))
525 "*Rules for highlighting shell scripts. See `sh-feature'.")
527 (defvar sh-font-lock-keywords-1
529 "*Additional rules for highlighting shell scripts. See `sh-feature'.")
531 (defvar sh-font-lock-keywords-2
()
532 "*Yet more rules for highlighting shell scripts. See `sh-feature'.")
534 (defvar sh-font-lock-keywords-only t
535 "*Value of `font-lock-keywords-only' for highlighting shell scripts.
536 Default value is `t' because Emacs' syntax is not expressive enough to
537 detect that $# does not start a comment. Thus comments are fontified by
538 regexp which means that a single apostrophe in a comment turns everything
539 upto the next one or end of buffer into a string.")
541 ;; mode-command and utility functions
545 "Major mode for editing shell scripts.
546 This mode works for many shells, since they all have roughly the same syntax,
547 as far as commands, arguments, variables, pipes, comments etc. are concerned.
548 Unless the file's magic number indicates the shell, your usual shell is
549 assumed. Since filenames rarely give a clue, they are not further analyzed.
551 This mode adapts to the variations between shells (see `sh-set-shell') by
552 means of an inheritance based feature lookup (see `sh-feature'). This
553 mechanism applies to all variables (including skeletons) that pertain to
554 shell-specific features.
556 The default style of this mode is that of Rosenblatt's Korn shell book.
557 The syntax of the statements varies with the shell being used. The
558 following commands are available, based on the current shell's syntax:
560 \\[sh-case] case statement
562 \\[sh-function] function definition
563 \\[sh-if] if statement
564 \\[sh-indexed-loop] indexed loop from 1 to n
565 \\[sh-while-getopts] while getopts loop
566 \\[sh-repeat] repeat loop
567 \\[sh-select] select loop
568 \\[sh-until] until loop
569 \\[sh-while] while loop
571 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
572 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
573 \\[sh-end-of-command] Go to end of successive commands.
574 \\[sh-beginning-of-command] Go to beginning of successive commands.
575 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
576 \\[sh-execute-region] Have optional header and region be executed in a subshell.
578 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
580 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
582 If you generally program a shell different from your login shell you can
583 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
584 indicate what shell it is use `sh-alias-alist' to translate.
586 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
587 with your script for an edit-interpret-debug cycle."
589 (kill-all-local-variables)
590 (use-local-map sh-mode-map
)
591 (make-local-variable 'indent-line-function
)
592 (make-local-variable 'indent-region-function
)
593 (make-local-variable 'skeleton-end-hook
)
594 (make-local-variable 'paragraph-start
)
595 (make-local-variable 'paragraph-separate
)
596 (make-local-variable 'comment-start
)
597 (make-local-variable 'comment-start-skip
)
598 (make-local-variable 'require-final-newline
)
599 (make-local-variable 'sh-header-marker
)
600 (make-local-variable 'sh-shell-file
)
601 (make-local-variable 'sh-shell
)
602 (make-local-variable 'skeleton-pair-alist
)
603 (make-local-variable 'skeleton-pair-filter
)
604 (make-local-variable 'comint-dynamic-complete-functions
)
605 (make-local-variable 'comint-prompt-regexp
)
606 (make-local-variable 'font-lock-keywords
)
607 (make-local-variable 'font-lock-defaults
)
608 (make-local-variable 'skeleton-filter
)
609 (make-local-variable 'skeleton-newline-indent-rigidly
)
610 (make-local-variable 'process-environment
)
611 (setq major-mode
'sh-mode
612 mode-name
"Shell-script"
613 indent-line-function
'sh-indent-line
614 ;; not very clever, but enables wrapping skeletons around regions
615 indent-region-function
(lambda (b e
)
618 (skip-syntax-backward "-")
621 (skip-syntax-backward "-")
622 (indent-rigidly b
(point) sh-indentation
)))
623 skeleton-end-hook
(lambda ()
624 (or (eolp) (newline) (indent-relative)))
625 paragraph-start
(concat page-delimiter
"\\|$")
626 paragraph-separate paragraph-start
628 comint-dynamic-complete-functions sh-dynamic-complete-functions
629 ;; we can't look if previous line ended with `\'
630 comint-prompt-regexp
"^[ \t]*"
632 `((sh-font-lock-keywords
633 sh-font-lock-keywords-1
634 sh-font-lock-keywords-2
)
635 ,sh-font-lock-keywords-only
637 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")))
638 skeleton-pair-alist
'((?
` _ ?
`))
639 skeleton-pair-filter
'sh-quoted-p
640 skeleton-further-elements
'((< '(- (min sh-indentation
642 skeleton-filter
'sh-feature
643 skeleton-newline-indent-rigidly t
)
645 ;; parse or insert magic number for exec() and set all variables depending
646 ;; on the shell thus determined
647 (goto-char (point-min))
649 (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
652 (run-hooks 'sh-mode-hook
))
654 (defalias 'shell-script-mode
'sh-mode
)
657 (defun sh-font-lock-keywords (&optional keywords
)
658 "Function to get simple fontification based on `sh-font-lock-keywords'.
659 This adds rules for comments and assignments."
660 (sh-feature sh-font-lock-keywords
662 `((,(concat (sh-feature sh-comment-prefix
) "\\(#.*\\)")
663 2 font-lock-comment-face t
)
664 (,(sh-feature sh-assignment-regexp
)
665 1 font-lock-variable-name-face
)
669 (defun sh-font-lock-keywords-1 (&optional builtins
)
670 "Function to get better fontification including keywords."
671 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
673 (sh-feature sh-leading-keywords
)
677 (append (sh-feature sh-leading-keywords
)
678 (sh-feature sh-other-keywords
))
681 (sh-font-lock-keywords
683 `((,(concat keywords
"[ \t]+\\)?\\("
684 (mapconcat 'identity
(sh-feature sh-builtins
) "\\|")
686 (2 font-lock-keyword-face nil t
)
687 (6 font-lock-function-name-face
))
688 ,@(sh-feature sh-font-lock-keywords-2
)))
689 (,(concat keywords
"\\)\\>")
690 2 font-lock-keyword-face
)
691 ,@(sh-feature sh-font-lock-keywords-1
)))))
693 (defun sh-font-lock-keywords-2 ()
694 "Function to get better fontification including keywords and builtins."
695 (sh-font-lock-keywords-1 t
))
698 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
699 "Set this buffer's shell to SHELL (a string).
700 Makes this script executable via `executable-set-magic'.
701 Calls the value of `sh-set-shell-hook' if set."
702 (interactive (list (completing-read "Name or path of shell: "
703 interpreter-mode-alist
704 (lambda (x) (eq (cdr x
) 'sh-mode
)))
705 (eq executable-query
'function
)
707 (setq sh-shell
(intern (file-name-nondirectory shell
))
708 sh-shell
(or (cdr (assq sh-shell sh-alias-alist
))
710 (setq sh-shell-file
(executable-set-magic shell
(sh-feature sh-shell-arg
)))
711 (setq require-final-newline
(sh-feature sh-require-final-newline
)
712 ;;; local-abbrev-table (sh-feature sh-abbrevs)
713 font-lock-keywords nil
; force resetting
714 font-lock-syntax-table nil
715 comment-start-skip
(concat (sh-feature sh-comment-prefix
) "#+[\t ]*")
716 mode-line-process
(format "[%s]" sh-shell
)
717 process-environment
(default-value 'process-environment
)
718 shell
(sh-feature sh-variables
))
719 (set-syntax-table (sh-feature sh-mode-syntax-table
))
721 (while (search-forward "=" nil t
)
724 (sh-remember-variable (car shell
))
725 (setq shell
(cdr shell
)))
726 (and (boundp 'font-lock-mode
)
728 (font-lock-mode (font-lock-mode 0)))
729 (run-hooks 'sh-set-shell-hook
))
733 (defun sh-feature (list &optional function
)
734 "Index ALIST by the current shell.
735 If ALIST isn't a list where every element is a cons, it is returned as is.
736 Else indexing follows an inheritance logic which works in two ways:
738 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
739 the alist contains no value for the current shell.
741 - If the value thus looked up is a list starting with `eval' its `cdr' is
742 first evaluated. If that is also a list and the first argument is a
743 symbol in ALIST it is not evaluated, but rather recursively looked up in
744 ALIST to allow the function called to define the value for one shell to be
745 derived from another shell. While calling the function, is the car of the
746 alist element is the current shell.
747 The value thus determined is physically replaced into the alist.
749 Optional FUNCTION is applied to the determined value and the result is cached
753 (while (and l
(consp (car l
)))
757 (cdr (assoc (setq function
(cons sh-shell function
)) list
)))
758 (let ((sh-shell sh-shell
)
761 (not (setq elt
(assq sh-shell list
))))
762 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
763 (if (and (consp (setq val
(cdr elt
)))
764 (eq (car val
) 'eval
))
767 (eval (if (consp (setq val
(cdr val
)))
768 (let ((sh-shell (car (cdr val
)))
770 (if (assq sh-shell list
)
779 (setq sh-shell
(car function
)
780 val
(funcall (cdr function
) val
))))))
785 ;;; I commented this out because nobody calls it -- rms.
786 ;;;(defun sh-abbrevs (ancestor &rest list)
787 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
788 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
789 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
790 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
791 ;;;EXPANSION may be either a string or a skeleton command."
792 ;;; (or (if (boundp sh-shell)
793 ;;; (symbol-value sh-shell))
795 ;;; (if (listp ancestor)
796 ;;; (nconc list ancestor))
797 ;;; (define-abbrev-table sh-shell ())
798 ;;; (if (vectorp ancestor)
799 ;;; (mapatoms (lambda (atom)
801 ;;; (define-abbrev (symbol-value sh-shell)
802 ;;; (symbol-name atom)
803 ;;; (symbol-value atom)
804 ;;; (symbol-function atom))))
807 ;;; (define-abbrev (symbol-value sh-shell)
809 ;;; (if (stringp (car (cdr list)))
812 ;;; (if (symbolp (car (cdr list)))
813 ;;; (car (cdr list))))
814 ;;; (setq list (cdr (cdr list)))))
815 ;;; (symbol-value sh-shell)))
818 (defun sh-mode-syntax-table (table &rest list
)
819 "Copy TABLE and set syntax for successive CHARs according to strings S."
820 (setq table
(copy-syntax-table table
))
822 (modify-syntax-entry (car list
) (car (cdr list
)) table
)
823 (setq list
(cdr (cdr list
))))
827 (defun sh-append (ancestor &rest list
)
828 "Return list composed of first argument (a list) physically appended to rest."
829 (nconc list ancestor
))
832 (defun sh-modify (skeleton &rest list
)
833 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
834 (setq skeleton
(copy-sequence skeleton
))
836 (setcar (or (nthcdr (car list
) skeleton
)
837 (error "Index %d out of bounds" (car list
)))
839 (setq list
(nthcdr 2 list
)))
843 (defun sh-indent-line ()
844 "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
845 Lines containing only comments are considered empty."
847 (let ((previous (save-excursion
850 (back-to-indentation)
852 (eq (following-char) ?
#))))
856 (indent-to (if (eq this-command
'newline-and-indent
)
858 (if (< (current-column)
859 (setq current
(progn (back-to-indentation)
861 (if (eolp) previous
0)
862 (delete-region (point)
863 (progn (beginning-of-line) (point)))
865 (max previous
(* (1+ (/ current sh-indentation
))
867 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
868 (if (< (current-column) (current-indentation))
869 (skip-chars-forward " \t"))))
872 (defun sh-execute-region (start end
&optional flag
)
873 "Pass optional header and region to a subshell for noninteractive execution.
874 The working directory is that of the buffer, and only environment variables
875 are already set which is why you can mark a header within the script.
877 With a positive prefix ARG, instead of sending region, define header from
878 beginning of buffer to point. With a negative prefix ARG, instead of sending
879 region, clear header."
882 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
886 (let (buffer-undo-list)
887 (goto-char sh-header-marker
)
888 (append-to-buffer (current-buffer) start end
)
889 (shell-command-on-region (point-min)
890 (setq end
(+ sh-header-marker
893 (delete-region sh-header-marker end
)))
894 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
897 (defun sh-remember-variable (var)
898 "Make VARIABLE available for future completing reads in this buffer."
899 (or (< (length var
) sh-remember-variable-min
)
901 (setq process-environment
(cons (concat var
"=") process-environment
)))
906 (defun sh-quoted-p ()
907 "Is point preceded by an odd number of backslashes?"
908 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
910 ;; statement syntax-commands for various shells
912 ;; You are welcome to add the syntax or even completely new statements as
913 ;; appropriate for your favorite shell.
915 (define-skeleton sh-case
916 "Insert a case/switch statement. See `sh-feature'."
918 "switch( " str
" )" \n
919 > "case " (read-string "pattern: ") ?
: \n
922 ( "other pattern, %s: "
932 "switch( " str
" ) {" \n
933 > "case " (read-string "pattern: ") \n
935 ( "other pattern, %s: "
944 > (read-string "pattern: ") ?\
) \n
947 ( "other pattern, %s: "
955 (put 'sh-case
'menu-enable
'(sh-feature sh-case
))
959 (define-skeleton sh-for
960 "Insert a for loop. See `sh-feature'."
961 (csh eval sh-modify sh
966 (es eval sh-modify rc
968 (rc eval sh-modify sh
972 (sh "Index variable: "
973 "for " str
" in " _
"; do" \n
974 > _ | ?$
& (sh-remember-variable str
) \n
979 (define-skeleton sh-indexed-loop
980 "Insert an indexed loop from 1 to n. See `sh-feature'."
981 (bash eval identity posix
)
982 (csh "Index variable: "
984 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
988 (es eval sh-modify rc
990 (ksh88 "Index variable: "
991 "integer " str
"=0" \n
992 "while (( ( " str
" += 1 ) <= "
993 (read-string "upper limit: ")
995 > _ ?$
(sh-remember-variable str
) \n
997 (posix "Index variable: "
999 "while [ $" str
" -le "
1000 (read-string "upper limit: ")
1003 str ?
= (sh-add (sh-remember-variable str
) 1) \n
1005 (rc "Index variable: "
1006 "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
1007 (read-string "upper limit: ")
1008 "; i++ ) print i }'}) {" \n
1009 > _ ?$
(sh-remember-variable str
) \n
1011 (sh "Index variable: "
1012 "for " str
" in `awk 'BEGIN { for( i=1; i<="
1013 (read-string "upper limit: ")
1014 "; i++ ) print i }'`; do" \n
1015 > _ ?$
(sh-remember-variable str
) \n
1019 (defun sh-add (var delta
)
1020 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
1022 (list (completing-read "Variable: "
1023 (mapcar (lambda (var)
1024 (substring var
0 (string-match "=" var
)))
1025 process-environment
))
1026 (prefix-numeric-value current-prefix-arg
)))
1027 (insert (sh-feature '((bash .
"$[ ")
1033 (sh-remember-variable var
)
1034 (if (< delta
0) " - " " + ")
1035 (number-to-string (abs delta
))
1036 (sh-feature '((bash .
" ]")
1045 (define-skeleton sh-function
1046 "Insert a function definition. See `sh-feature'."
1047 (bash eval sh-modify ksh88
1050 "function " str
" {" \n
1053 (rc eval sh-modify ksh88
1062 (define-skeleton sh-if
1063 "Insert an if statement. See `sh-feature'."
1065 "if( " str
" ) then" \n
1067 ( "other condition, %s: "
1068 < "else if( " str
" ) then" \n
1075 "if { " str
" } {" \n
1077 ( "other condition, %s: "
1078 < "} { " str
" } {" \n
1084 (rc eval sh-modify csh
1086 8 '( "other condition, %s: "
1087 < "} else if( " str
" ) {" \n
1092 '(setq input
(sh-feature sh-test
))
1093 "if " str
"; then" \n
1095 ( "other condition, %s: "
1096 < "elif " str
"; then" \n
1105 (define-skeleton sh-repeat
1106 "Insert a repeat loop definition. See `sh-feature'."
1112 "repeat " str
"; do"\n
1115 (put 'sh-repeat
'menu-enable
'(sh-feature sh-repeat
))
1119 (define-skeleton sh-select
1120 "Insert a select statement. See `sh-feature'."
1121 (ksh88 "Index variable: "
1122 "select " str
" in " _
"; do" \n
1125 (put 'sh-select
'menu-enable
'(sh-feature sh-select
))
1129 (define-skeleton sh-tmp-file
1130 "Insert code to setup temporary file handling. See `sh-feature'."
1131 (bash eval identity ksh88
)
1132 (csh (file-name-nondirectory (buffer-file-name))
1133 "set tmp = /tmp/" str
".$$" \n
1135 (and (goto-char (point-max))
1139 "rm $tmp* >&/dev/null" >)
1140 (es (file-name-nondirectory (buffer-file-name))
1141 "local( signals = $signals sighup sigint; tmp = /tmp/" str
".$pid ) {" \n
1143 > "rm $tmp^* >[2]/dev/null" \n
1149 (ksh88 eval sh-modify sh
1151 (rc (file-name-nondirectory (buffer-file-name))
1152 "tmp = /tmp/" str
".$pid" \n
1153 "fn sigexit { rm $tmp^* >[2]/dev/null }")
1154 (sh (file-name-nondirectory (buffer-file-name))
1155 "TMP=/tmp/" str
".$$" \n
1156 "trap \"rm $TMP* 2>/dev/null\" " ?
0))
1160 (define-skeleton sh-until
1161 "Insert an until loop. See `sh-feature'."
1163 '(setq input
(sh-feature sh-test
))
1164 "until " str
"; do" \n
1167 (put 'sh-until
'menu-enable
'(sh-feature sh-until
))
1171 (define-skeleton sh-while
1172 "Insert a while loop. See `sh-feature'."
1173 (csh eval sh-modify sh
1177 (es eval sh-modify rc
1180 (rc eval sh-modify csh
1184 '(setq input
(sh-feature sh-test
))
1185 "while " str
"; do" \n
1191 (define-skeleton sh-while-getopts
1192 "Insert a while getopts loop. See `sh-feature'.
1193 Prompts for an options string which consists of letters for each recognized
1194 option followed by a colon `:' if the option accepts an argument."
1195 (bash eval sh-modify sh
1199 > "switch( \"$1\" )" \n
1200 '(setq input
'("- x" .
2))
1203 < "case " '(eval str
)
1204 '(if (string-match " +" str
)
1205 (setq v1
(substring str
(match-end 0))
1206 str
(substring str
0 (match-beginning 0)))
1209 > "set " v1
& " = $2" | -
4 & _
\n
1210 (if v1
"shift") & \n
1220 (ksh88 eval sh-modify sh
1224 (posix eval sh-modify sh
1225 18 "$(basename $0)")
1227 "while getopts :" str
" OPT; do" \n
1230 '(setq v1
(append (vconcat str
) nil
))
1231 ( (prog1 (if v1
(char-to-string (car v1
)))
1232 (if (eq (nth 1 v1
) ?
:)
1233 (setq v1
(nthcdr 2 v1
)
1237 < str
"|+" str ?\
) \n
1241 > "echo" " \"usage: " "`basename $0`"
1242 "[ +-" '(setq v1
(point)) str
1244 (while (search-backward ":" v1 t
)
1245 (replace-match " arg][ +-" t t
)))
1246 (if (eq (preceding-char) ?-
) -
5)
1251 "shift " (sh-add "OPTIND" -
1)))
1252 (put 'sh-while-getopts
'menu-enable
'(sh-feature sh-while-getopts
))
1256 (defun sh-assignment (arg)
1257 "Remember preceding identifier for future completion and do self-insert."
1259 (self-insert-command arg
)
1261 (sh-remember-variable
1263 (if (re-search-forward (sh-feature sh-assignment-regexp
)
1265 (beginning-of-line 1))
1267 (match-string 1))))))
1271 (defun sh-maybe-here-document (arg)
1272 "Inserts self. Without prefix, following unquoted `<' inserts here document.
1273 The document is bounded by `sh-here-document-word'."
1275 (self-insert-command (prefix-numeric-value arg
))
1277 (not (eq (char-after (- (point) 2)) last-command-char
))
1282 (insert sh-here-document-word
)
1283 (or (eolp) (looking-at "[ \t]") (insert ?
))
1289 (save-excursion (insert ?
\n sh-here-document-word
)))))
1292 ;; various other commands
1294 (autoload 'comint-dynamic-complete
"comint"
1295 "Dynamically perform completion at point." t
)
1297 (autoload 'shell-dynamic-complete-command
"shell"
1298 "Dynamically complete the command at point." t
)
1300 (autoload 'comint-dynamic-complete-filename
"comint"
1301 "Dynamically complete the filename at point." t
)
1303 (autoload 'shell-dynamic-complete-environment-variable
"shell"
1304 "Dynamically complete the environment variable at point." t
)
1308 (defun sh-newline-and-indent ()
1309 "Strip unquoted whitespace, insert newline, and indent like current line."
1311 (indent-to (prog1 (current-indentation)
1312 (delete-region (point)
1314 (or (zerop (skip-chars-backward " \t"))
1322 (defun sh-beginning-of-command ()
1323 "Move point to successive beginnings of commands."
1325 (if (re-search-backward sh-beginning-of-command nil t
)
1326 (goto-char (match-beginning 2))))
1329 (defun sh-end-of-command ()
1330 "Move point to successive ends of commands."
1332 (if (re-search-forward sh-end-of-command nil t
)
1333 (goto-char (match-end 1))))
1335 (provide 'sh-script
)
1336 ;; sh-script.el ends here