sh-script.el 40.1 KB
Newer Older
Richard M. Stallman's avatar
Richard M. Stallman committed
1
;;; sh-script.el --- shell-script editing commands for Emacs
2
;; Copyright (C) 1993, 1994, 1995 by Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
3

4 5
;; Author: Daniel.Pfeiffer@Informatik.START.dbp.de, fax (+49 69) 7588-2389
;; Version: 2.0d
Richard M. Stallman's avatar
Richard M. Stallman committed
6
;; Maintainer: FSF
7
;; Keywords: languages, unix
Richard M. Stallman's avatar
Richard M. Stallman committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to
;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

;;; Commentary:

27 28 29 30 31
;; Major mode for editing shell scripts.  Bourne, C and rc shells as well
;; as various derivatives are supported and easily derived from.  Structured
;; statements can be inserted with one command or abbrev.  Completion is
;; available for filenames, variables known from the script, the shell and
;; the environment as well as commands.
Richard M. Stallman's avatar
Richard M. Stallman committed
32

33 34 35 36 37 38 39 40 41 42
;;; Known Bugs:

;; - Since GNU Emacs' syntax can't handle the context-sensitive meanings of
;;   the variable/number base/comment symbol `#', that has to be fontified by
;;   regexp.  This alas means that a quote `'' or `"' in a comment will
;;   fontify VERY badly.  The alternative is to have these frequent constructs
;;   with `#' fontify as comments.  Or maybe we intoduce a 'syntax text-
;;   property?
;; - Variables in `"' strings aren't fontified because there's no way of
;;   syntactically distinguishing those from `'' strings.
43

Richard M. Stallman's avatar
Richard M. Stallman committed
44 45 46 47 48 49 50
;;; Code:

;; page 1:	variables and settings
;; page 2:	mode-command and utility functions
;; page 3:	statement syntax-commands for various shells
;; page 4:	various other commands

51 52 53
(require 'executable)


54 55 56

;; Autoload cookie deleted here because it made loaddefs.el fail to load.
;; -rms
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
(or (assoc "sh" interpreter-mode-alist)
    (setq auto-mode-alist
	  ;; matches files
	  ;;	- that have a suffix .sh, .csh or .shar (shell archive)
	  ;;	- that contain ressources for the various shells
	  ;;	- startup files for X11
	  (cons '("\\.c?sh\\'\\|\\.shar\\'\\|/\\.\\(z?profile\\|bash_profile\\|z?login\\|bash_login\\|z?logout\\|bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\|rcrc\\|[kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
		auto-mode-alist)
	  interpreter-mode-alist
	  (nconc '(("ash" . sh-mode)
		   ("bash" . sh-mode)
		   ("csh" . sh-mode)
		   ("dtksh" . sh-mode)
		   ("es" . sh-mode)
		   ("itcsh" . sh-mode)
		   ("jsh" . sh-mode)
		   ("ksh" . sh-mode)
		   ("oash" . sh-mode)
		   ("pdksh" . sh-mode)
		   ("rc" . sh-mode)
		   ("sh" . sh-mode)
		   ("sh5" . sh-mode)
		   ("tcsh" . sh-mode)
		   ("wksh" . sh-mode)
		   ("wsh" . sh-mode)
		   ("zsh" . sh-mode))
		 interpreter-mode-alist)))


(defvar sh-ancestor-alist
  '((ash . sh)
    (bash . jsh)
    (dtksh . ksh)
    (es . rc)
    (itcsh . tcsh)
    (jcsh . csh)
    (jsh . sh)
    (ksh . ksh88)
    (ksh88 . jsh)
    (oash . sh)
    (pdksh . ksh88)
    (posix . sh)
    (tcsh . csh)
    (wksh . ksh88)
    (wsh . sh)
    (zsh . ksh88))
  "*Alist showing the direct ancestor of various shells.
This is the basis for `sh-feature'.  See also `sh-alias-alist'.
By default we have the following three hierarchies:

csh		C Shell
  jcsh		C Shell with Job Control
  tcsh		Toronto C Shell
    itcsh	? Toronto C Shell
rc		Plan 9 Shell
  es		Extensible Shell
sh		Bourne Shell
  ash		? Shell
  jsh		Bourne Shell with Job Control
    bash	GNU Bourne Again Shell
    ksh88	Korn Shell '88
      ksh	Korn Shell '93
	dtksh	CDE Desktop Korn Shell
      pdksh	Public Domain Korn Shell
      wksh	Window Korn Shell
      zsh	Z Shell
  oash		SCO OA (curses) Shell
  posix		IEEE 1003.2 Shell Standard
  wsh		? Shell")


(defvar sh-alias-alist
  (nconc (if (eq system-type 'linux)
	     '((csh . tcsh)
	       (ksh . pdksh)
	       (sh . bash)))
	 ;; for the time being
	 '((ksh . ksh88)
	   (sh5 . sh)))
  "*Alist for transforming shell names to what they really are.
Use this where the name of the executable doesn't correspond to the type of
shell it really is.")


(defvar sh-shells
  '(("ash") ("bash") ("csh") ("dtksh") ("es") ("itcsh") ("jsh") ("ksh")
    ("oash") ("pdksh") ("rc") ("sh") ("tcsh") ("wksh") ("wsh") ("zsh"))
  "*Alist of shells available for completing read in `sh-set-shell'.")


(defvar sh-shell-path (or (getenv "SHELL") "/bin/sh")
  "*The executable of the shell being programmed.")


(defvar sh-shell-arg
  '((bash . "-norc")
    (csh . "-f")
    (ksh88 eval progn nil (if (file-exists-p "/etc/suid_profile") nil "-p"))
    (pdksh)
    (rc . "-p")
    (wksh . "-motif")
    (zsh . "-f"))
  "*Single argument string for the magic number.  See `sh-feature'.")



(defvar sh-shell (or (cdr (assq (intern (file-name-nondirectory sh-shell-path))
				sh-alias-alist))
		     (intern (file-name-nondirectory sh-shell-path)))
  "The shell being programmed.  This is set by \\[sh-set-shell].")



(defvar sh-abbrevs
  '((csh eval sh-abbrevs shell
Karl Heuer's avatar
Karl Heuer committed
172 173
	 "switch" 'sh-case
	 "getopts" 'sh-while-getopts)
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

    (es eval sh-abbrevs shell
	"function" 'sh-function)

    (ksh88 eval sh-abbrevs sh
	   "select" 'sh-select)

    (rc eval sh-abbrevs shell
	"case" 'sh-case
	"function" 'sh-function)

    (sh eval sh-abbrevs shell
	"case" 'sh-case
	"function" 'sh-function
	"until" 'sh-until
	"getopts" 'sh-while-getopts)

    ;; The next entry is only used for defining the others
    (shell "for" sh-for
	   "loop" sh-indexed-loop
	   "if" sh-if
	   "tmpfile" sh-tmp-file
	   "while" sh-while)

    (zsh eval sh-abbrevs ksh88
	 "repeat" 'sh-repeat))
  "Abbrev-table used in Shell-Script mode.  See `sh-feature'.
Due to the internal workings of abbrev tables, the shell name symbol is
actually defined as the table for the like of \\[edit-abbrevs].")
Richard M. Stallman's avatar
Richard M. Stallman committed
203 204 205 206



(defvar sh-mode-syntax-table
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  '((csh eval identity sh)
    (sh eval sh-mode-syntax-table ()
	;; #'s meanings depend on context which can't be expressed here
	;; ?\# "<"
	;; ?\^l ">#"
	;; ?\n ">#"
	?\" "\"\""
	?\' "\"'"
	?\` ".`"
	?$ "_"
	?! "_"
	?% "_"
	?: "_"
	?. "_"
	?^ "_"
	?~ "_")
    (rc eval sh-mode-syntax-table sh
	?\" "_"
	?\` "."))
  "Syntax-table used in Shell-Script mode.  See `sh-feature'.")


Richard M. Stallman's avatar
Richard M. Stallman committed
229 230 231 232 233 234

(defvar sh-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\C-c(" 'sh-function)
    (define-key map "\C-c\C-w" 'sh-while)
    (define-key map "\C-c\C-u" 'sh-until)
235
    (define-key map "\C-c\C-t" 'sh-tmp-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
236
    (define-key map "\C-c\C-s" 'sh-select)
237 238
    (define-key map "\C-c\C-r" 'sh-repeat)
    (define-key map "\C-c\C-o" 'sh-while-getopts)
Richard M. Stallman's avatar
Richard M. Stallman committed
239 240 241 242
    (define-key map "\C-c\C-l" 'sh-indexed-loop)
    (define-key map "\C-c\C-i" 'sh-if)
    (define-key map "\C-c\C-f" 'sh-for)
    (define-key map "\C-c\C-c" 'sh-case)
243

Richard M. Stallman's avatar
Richard M. Stallman committed
244 245
    (define-key map "=" 'sh-assignment)
    (define-key map "\C-c+" 'sh-add)
246 247 248
    (define-key map "\C-c|" 'sh-execute-region)
    (define-key map "\C-c!" 'executable-interpret)
    (define-key map "<" 'sh-maybe-here-document)
249 250 251 252 253 254
    (define-key map "(" 'skeleton-pair-insert-maybe)
    (define-key map "{" 'skeleton-pair-insert-maybe)
    (define-key map "[" 'skeleton-pair-insert-maybe)
    (define-key map "'" 'skeleton-pair-insert-maybe)
    (define-key map "`" 'skeleton-pair-insert-maybe)
    (define-key map "\"" 'skeleton-pair-insert-maybe)
Richard M. Stallman's avatar
Richard M. Stallman committed
255 256

    (define-key map "\t" 'sh-indent-line)
257
    (substitute-key-definition 'complete-tag 'comint-dynamic-complete
Richard M. Stallman's avatar
Richard M. Stallman committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
			       map (current-global-map))
    (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
			       map (current-global-map))
    (substitute-key-definition 'delete-backward-char
			       'backward-delete-char-untabify
			       map (current-global-map))
    (define-key map "\C-c:" 'sh-set-shell)
    (substitute-key-definition 'beginning-of-defun
			       'sh-beginning-of-compound-command
			       map (current-global-map))
    (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
			       map (current-global-map))
    (substitute-key-definition 'forward-sentence 'sh-end-of-command
			       map (current-global-map))
    (define-key map [menu-bar insert] 
      (cons "Insert" (make-sparse-keymap "Insert")))
    (define-key map [menu-bar insert sh-while] 
275
      '("While loop" . sh-while))
Richard M. Stallman's avatar
Richard M. Stallman committed
276
    (define-key map [menu-bar insert sh-until] 
277 278 279
      '("Until loop" . sh-until))
    (define-key map [menu-bar insert sh-tmp-file] 
      '("Temporary file" . sh-tmp-file))
Richard M. Stallman's avatar
Richard M. Stallman committed
280
    (define-key map [menu-bar insert sh-select] 
281 282 283 284 285
      '("Select statement" . sh-select))
    (define-key map [menu-bar insert sh-repeat] 
      '("Repeat loop" . sh-repeat))
    (define-key map [menu-bar insert sh-while-getopts] 
      '("Options loop" . sh-while-getopts))
Richard M. Stallman's avatar
Richard M. Stallman committed
286
    (define-key map [menu-bar insert sh-indexed-loop] 
287
      '("Indexed loop" . sh-indexed-loop))
Richard M. Stallman's avatar
Richard M. Stallman committed
288
    (define-key map [menu-bar insert sh-if] 
289
      '("If statement" . sh-if))
Richard M. Stallman's avatar
Richard M. Stallman committed
290
    (define-key map [menu-bar insert sh-for] 
291
      '("For loop" . sh-for))
Richard M. Stallman's avatar
Richard M. Stallman committed
292
    (define-key map [menu-bar insert sh-case] 
293
      '("Case statement" . sh-case))
Richard M. Stallman's avatar
Richard M. Stallman committed
294 295 296 297 298
    map)
  "Keymap used in Shell-Script mode.")



299 300 301 302 303
(defvar sh-dynamic-complete-functions
  '(shell-dynamic-complete-environment-variable
    shell-dynamic-complete-command
    comint-dynamic-complete-filename)
  "*Functions for doing TAB dynamic completion.")
Richard M. Stallman's avatar
Richard M. Stallman committed
304 305


306 307 308 309 310 311 312
(defvar sh-require-final-newline
  '((csh . t)
    (pdksh . t)
    (rc eval . require-final-newline)
    (sh eval . require-final-newline))
  "*Value of `require-final-newline' in Shell-Script mode buffers.
See `sh-feature'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
313 314


315 316 317 318 319 320 321 322
(defvar sh-comment-prefix
  '((csh . "\\(^\\|[^$]\\|\\$[^{]\\)")
    (rc eval identity csh)
    (sh . "\\(^\\|[ \t|&;()]\\)"))
  "*Regexp matching what may come before a comment `#'.
This must contain one \\(grouping\\) since it is the basis for fontifying
comments as well as for `comment-start-skip'.
See `sh-feature'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
323 324


325 326 327 328 329 330 331 332 333
(defvar sh-assignment-regexp
  '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
    ;; actually spaces are only supported in let/(( ... ))
    (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
    (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
    (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
  "*Regexp for the variable name and what may follow in an assignment.
First grouping matches the variable name.  This is upto and including the `='
sign.  See `sh-feature'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
334 335


336 337
(defvar sh-indentation 4
  "The width for further indentation in Shell-Script mode.")
Richard M. Stallman's avatar
Richard M. Stallman committed
338 339 340 341 342 343


(defvar sh-remember-variable-min 3
  "*Don't remember variables less than this length for completing reads.")


344 345 346 347 348
(defvar sh-header-marker nil
  "When non-`nil' is the end of header for prepending by \\[sh-execute-region].
That command is also used for setting this variable.")


Richard M. Stallman's avatar
Richard M. Stallman committed
349 350 351 352 353
(defvar sh-beginning-of-command
  "\\([;({`|&]\\|^\\)[ \t]*\\([/~:a-zA-Z0-9]\\)"
  "*Regexp to determine the beginning of a shell command.
The actual command starts at the beginning of the second \\(grouping\\).")

354

Richard M. Stallman's avatar
Richard M. Stallman committed
355 356 357 358 359 360 361
(defvar sh-end-of-command
  "\\([/~:a-zA-Z0-9]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
  "*Regexp to determine the end of a shell command.
The actual command ends at the end of the first \\(grouping\\).")



362
(defvar sh-here-document-word "EOF"
Richard M. Stallman's avatar
Richard M. Stallman committed
363 364
  "Word to delimit here documents.")

Karl Heuer's avatar
Karl Heuer committed
365 366 367 368 369
(defvar sh-test
  '((sh "[  ]" . 3)
    (ksh88 "[[  ]]" . 4))
  "Initial input in Bourne if, while and until skeletons.  See `sh-feature'.")

Richard M. Stallman's avatar
Richard M. Stallman committed
370

371 372 373 374 375 376
(defvar sh-builtins
  '((bash eval sh-append sh
	  "alias" "bg" "bind" "builtin" "bye" "command" "declare" "dirs"
	  "enable" "fc" "fg" "function" "help" "history" "jobs" "kill" "let"
	  "local" "logout" "popd" "pushd" "source" "suspend" "typeset"
	  "unalias")
Richard M. Stallman's avatar
Richard M. Stallman committed
377

378 379 380 381 382
    ;; The next entry is only used for defining the others
    (bourne eval sh-append shell
	    "do" "done" "elif" "esac" "export" "fi" "for" "getopts" "in"
	    "newgrp" "pwd" "read" "readonly" "return" "times" "trap" "ulimit"
	    "until")
Richard M. Stallman's avatar
Richard M. Stallman committed
383

384
    (csh eval sh-append shell
Karl Heuer's avatar
Karl Heuer committed
385
	 "alias" "breaksw" "chdir" "default:" "end" "endif" "endsw" "foreach"
386 387 388
	 "glob" "goto" "history" "limit" "logout" "nice" "nohup" "onintr"
	 "rehash" "repeat" "setenv" "source" "switch" "time" "unalias"
	 "unhash")
Richard M. Stallman's avatar
Richard M. Stallman committed
389

390 391 392 393
    (es "access" "apids" "break" "catch" "cd" "echo" "eval" "exec" "exit"
	"false" "fn" "for" "forever" "fork" "if" "let" "limit" "local"
	"newpgrp" "result" "return" "throw" "time" "true" "umask"
	"unwind-protect" "var" "vars" "wait" "whatis" "while")
Richard M. Stallman's avatar
Richard M. Stallman committed
394

395 396
    (jsh eval sh-append sh
	 "bg" "fg" "jobs" "kill" "stop" "suspend")
Richard M. Stallman's avatar
Richard M. Stallman committed
397

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    (jcsh eval sh-append csh
	 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")

    (ksh88 eval sh-append bourne
	   "alias" "bg" "false" "fc" "fg" "function" "jobs" "kill" "let"
	   "print" "select" "time" "typeset" "unalias" "whence")

    (oash eval sh-append sh
	  "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
	  "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
	  "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
	  "wmtitle" "wrefresh")

    (pdksh eval sh-append ksh88
	   "bind")

    (posix eval sh-append sh
	   "command")

    (rc "break" "builtin" "case" "cd" "echo" "else" "eval" "exec" "exit" "fn"
	"for" "if" "in" "limit" "newpgrp" "return" "shift" "switch" "umask"
	"wait" "whatis" "while")

    (sh eval sh-append bourne
	"hash" "test" "type")

    ;; The next entry is only used for defining the others
    (shell "break" "case" "cd" "continue" "echo" "else" "eval" "exec" "exit"
	   "if" "set" "shift" "then" "umask" "unset" "wait" "while")

    (zsh eval sh-append ksh88
	 "autoload" "bindkey" "builtin" "bye" "chdir" "compctl" "declare"
	 "dirs" "disable" "disown" "echotc" "enable" "functions" "getln"
	 "hash" "history" "integer" "limit" "local" "log" "logout" "popd"
	 "pushd" "r" "readonly" "rehash" "sched" "setopt" "source" "suspend"
	 "true" "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt"
	 "vared" "which"))
  "*List of all shell builtins for completing read and fontification.
Note that on some systems not all builtins are available or some are
implemented as aliases.  See `sh-feature'.")


(defvar sh-leading-keywords
  '((bash eval sh-append sh
	  "builtin" "command" "enable")

    ;; The next entry is only used for defining the others
    (bourne "do" "elif" "else" "eval" "if" "then" "trap" "until" "while")

    (csh "else")

    (es "eval" "time" "true" "umask"
	"unwind-protect" "whatis")

    (ksh88 eval sh-append bourne
	   "time" "whence")

    (posix eval sh-append sh
	   "command")

    (rc "builtin" "else" "eval" "whatis")

    (sh eval sh-append bourne
	"type")

    (zsh eval sh-append ksh88
	 "builtin" "disable" "enable" "type" "unhash" "which"))
  "*List of keywords that may be immediately followed by a command(-name).
See `sh-feature'.")



(defvar sh-variables
  '((bash eval sh-append sh
	  "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
	  "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
	  "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
	  "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
	  "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
	  "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
	  "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
	  "SECONDS" "SHLVL" "TMOUT" "UID")

    (csh eval sh-append shell
	 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
	 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
	 "shell" "status" "time" "verbose")

    (es eval sh-append shell
	"apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
	"pid" "prompt" "signals")

    (jcsh eval sh-append csh
	 "notify")

    (ksh88 eval sh-append sh
	   "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
	   "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
	   "TMOUT")

    (oash eval sh-append sh
	  "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")

    (rc eval sh-append shell
	"apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
	"prompt" "status")

    (sh eval sh-append shell
	"CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")

    ;; The next entry is only used for defining the others
    (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
	   "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
	   "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
	   "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")

    (tcsh eval sh-append csh
	  "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
	  "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
	  "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
	  "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
	  "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
	  "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
	  "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
	  "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
	  "wordchars")

    (zsh eval sh-append ksh88
	 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
	 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
	 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
	 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
	 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
	 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
	 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
  "List of all shell variables available for completing read.
See `sh-feature'.")



(defvar sh-font-lock-keywords
  '((csh eval sh-append shell
	 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
Karl Heuer's avatar
Karl Heuer committed
541
	   font-lock-variable-name-face))
542 543 544 545 546

    (dtksh eval identity wksh)

    (es eval sh-append executable-font-lock-keywords
	'("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
Karl Heuer's avatar
Karl Heuer committed
547
	  font-lock-variable-name-face))
548 549 550 551 552 553 554

    (rc eval sh-append es
	'("\\(^\\|[ \t]\\)\\(else\\( if\\)?\\)\\>" 2
	  font-lock-keyword-face t))

    (sh eval sh-append shell
	'("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
Karl Heuer's avatar
Karl Heuer committed
555
	  font-lock-variable-name-face)
556 557 558 559 560 561
	" in\\([ \t]\\|$\\)")

    ;; The next entry is only used for defining the others
    (shell eval sh-append executable-font-lock-keywords
	   '("\\\\." 0 font-lock-string-face)
	   '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
Karl Heuer's avatar
Karl Heuer committed
562
	     font-lock-variable-name-face))
563 564 565 566 567 568 569 570 571

    (wksh eval sh-append ksh88
	  '("\\(^\\|[^-._A-Za-z0-9]\\)\\(Xt[A-Z][A-Za-z]*\\)\\($\\|[^-._A-Za-z0-9]\\)" 2 font-lock-keyword-face)))
  "*Rules for highlighting shell scripts.  See `sh-feature'.")


;; mode-command and utility functions

;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
572 573 574 575 576 577 578
(defun sh-mode ()
  "Major mode for editing shell scripts.
This mode works for many shells, since they all have roughly the same syntax,
as far as commands, arguments, variables, pipes, comments etc. are concerned.
Unless the file's magic number indicates the shell, your usual shell is
assumed.  Since filenames rarely give a clue, they are not further analyzed.

579 580 581 582
This mode adapts to the variations between shells (see `sh-set-shell') by
means of an inheritance based feature lookup (see `sh-feature').  This
mechanism applies to all variables (including skeletons) that pertain to
shell-specific features.
Richard M. Stallman's avatar
Richard M. Stallman committed
583

584 585 586
The default style of this mode is that of Rosenblatt's Korn shell book.
The syntax of the statements varies with the shell being used.  The
following commands are available, based on the current shell's syntax:
Richard M. Stallman's avatar
Richard M. Stallman committed
587 588 589 590 591 592

\\[sh-case]	 case statement
\\[sh-for]	 for loop
\\[sh-function]	 function definition
\\[sh-if]	 if statement
\\[sh-indexed-loop]	 indexed loop from 1 to n
593 594 595
\\[sh-while-getopts]	 while getopts loop
\\[sh-repeat]	 repeat loop
\\[sh-select]	 select loop
Richard M. Stallman's avatar
Richard M. Stallman committed
596 597 598 599 600 601 602 603
\\[sh-until]	 until loop
\\[sh-while]	 while loop

\\[backward-delete-char-untabify]	 Delete backward one position, even if it was a tab.
\\[sh-newline-and-indent]	 Delete unquoted space and indent new line same as this one.
\\[sh-end-of-command]	 Go to end of successive commands.
\\[sh-beginning-of-command]	 Go to beginning of successive commands.
\\[sh-set-shell]	 Set this buffer's shell, and maybe its magic number.
604
\\[sh-execute-region]	 Have optional header and region be executed in a subshell.
Richard M. Stallman's avatar
Richard M. Stallman committed
605 606 607

\\[sh-maybe-here-document]	 Without prefix, following an unquoted < inserts here document.
{, (, [, ', \", `
608 609 610 611 612 613 614 615
	Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.

If you generally program a shell different from your login shell you can
set `sh-shell-path' accordingly.  If your shell's file name doesn't correctly
indicate what shell it is use `sh-alias-alist' to translate.

If your shell gives error messages with line numbers, you can use \\[executable-interpret]
with your script for an edit-interpret-debug cycle."
Richard M. Stallman's avatar
Richard M. Stallman committed
616 617 618 619
  (interactive)
  (kill-all-local-variables)
  (use-local-map sh-mode-map)
  (make-local-variable 'indent-line-function)
620 621 622
  (make-local-variable 'indent-region-function)
  (make-local-variable 'paragraph-start)
  (make-local-variable 'paragraph-separate)
Richard M. Stallman's avatar
Richard M. Stallman committed
623 624 625
  (make-local-variable 'comment-start)
  (make-local-variable 'comment-start-skip)
  (make-local-variable 'require-final-newline)
626
  (make-local-variable 'sh-header-marker)
Richard M. Stallman's avatar
Richard M. Stallman committed
627 628
  (make-local-variable 'sh-shell-path)
  (make-local-variable 'sh-shell)
629 630
  (make-local-variable 'skeleton-pair-alist)
  (make-local-variable 'skeleton-pair-filter)
631 632 633 634 635 636
  (make-local-variable 'font-lock-keywords)
  (make-local-variable 'comint-dynamic-complete-functions)
  (make-local-variable 'comint-prompt-regexp)
  (make-local-variable 'font-lock-keywords-case-fold-search)
  (make-local-variable 'skeleton-filter)
  (make-local-variable 'process-environment)
Richard M. Stallman's avatar
Richard M. Stallman committed
637 638 639
  (setq major-mode 'sh-mode
	mode-name "Shell-script"
	indent-line-function 'sh-indent-line
640 641 642 643 644
	;; not very clever, but enables wrapping skeletons around regions
	indent-region-function (lambda (b e)
				 (indent-rigidly b e sh-indentation))
	paragraph-start "^$\\|^"
	paragraph-separate paragraph-start
Richard M. Stallman's avatar
Richard M. Stallman committed
645
	comment-start "# "
646 647 648 649
	font-lock-keywords-case-fold-search nil
	comint-dynamic-complete-functions sh-dynamic-complete-functions
	;; we can't look if previous line ended with `\'
	comint-prompt-regexp "^[ \t]*"
650 651
	skeleton-pair-alist '((?` _ ?`))
	skeleton-pair-filter 'sh-quoted-p
652 653 654 655 656 657 658 659 660 661
	skeleton-further-elements '((< '(- (min sh-indentation
						(current-column)))))
	skeleton-filter 'sh-feature)
  ;; parse or insert magic number for exec() and set all variables depending
  ;; on the shell thus determined
  (goto-char (point-min))
  (sh-set-shell
   (if (looking-at "#![\t ]*\\([^\t\n ]+\\)")
       (buffer-substring (match-beginning 1) (match-end 1))
     sh-shell-path))
Richard M. Stallman's avatar
Richard M. Stallman committed
662
  (run-hooks 'sh-mode-hook))
663
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
664 665 666 667
(defalias 'shell-script-mode 'sh-mode)



668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
(defun sh-set-shell (shell)
  "Set this buffer's shell to SHELL (a string).
Makes this script executable via `executable-set-magic'.
Calls the value of `sh-set-shell-hook' if set."
  (interactive (list (completing-read "Name or path of shell: " sh-shells)))
  (if (eq this-command 'sh-set-shell)
      ;; prevent querying
      (setq this-command 'executable-set-magic))
  (setq sh-shell (intern (file-name-nondirectory shell))
	sh-shell (or (cdr (assq sh-shell sh-alias-alist))
		     sh-shell)
	sh-shell-path (executable-set-magic shell (sh-feature sh-shell-arg))
	local-abbrev-table (sh-feature sh-abbrevs)
	require-final-newline (sh-feature sh-require-final-newline)
	font-lock-keywords
	  (sh-feature
	   sh-font-lock-keywords
	   (lambda (list)
Karl Heuer's avatar
Karl Heuer committed
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
	     `((,(concat (sh-feature sh-comment-prefix) "\\(#.*\\)")
		2 font-lock-comment-face t)
	       (,(sh-feature sh-assignment-regexp)
		1 font-lock-variable-name-face)
	       ,@(if font-lock-maximum-decoration
		     `((,(concat "\\(^\\|[|&;()]\\)[ \t]*\\(\\(\\("
				 (mapconcat 'identity
					    (sh-feature sh-leading-keywords)
					    "\\|")
				 "\\)[ \t]+\\)?\\("
				 (mapconcat 'identity
					    (sh-feature sh-builtins)
					    "\\|")
				 "\\)\\)\\($\\|[ \t|&;()]\\)")
			2 font-lock-keyword-face 'keep)
		       ,@list)
		   list))))
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
	comment-start-skip (concat (sh-feature sh-comment-prefix) "#+[\t ]*")
	mode-line-process (format "[%s]" sh-shell)
	process-environment (default-value 'process-environment)
	shell (sh-feature sh-variables))
  (set-syntax-table (sh-feature sh-mode-syntax-table))
  (save-excursion
    (while (search-forward "=" nil t)
      (sh-assignment 0)))
  (while shell
    (sh-remember-variable (car shell))
    (setq shell (cdr shell)))
  (and (boundp 'font-lock-mode)
       font-lock-mode
       (font-lock-mode (font-lock-mode 0)))
  (run-hooks 'sh-set-shell-hook))


Richard M. Stallman's avatar
Richard M. Stallman committed
720

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
(defun sh-feature (list &optional function)
  "Index ALIST by the current shell.
If ALIST isn't a list where every element is a cons, it is returned as is.
Else indexing follows an inheritance logic which works in two ways:

  - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
    the alist contains no value for the current shell.

  - If the value thus looked up is a list starting with `eval' its `cdr' is
    first evaluated.  If that is also a list and the first argument is a
    symbol in ALIST it is not evaluated, but rather recursively looked up in
    ALIST to allow the function called to define the value for one shell to be
    derived from another shell.  While calling the function, is the car of the
    alist element is the current shell.
    The value thus determined is physically replaced into the alist.

Optional FUNCTION is applied to the determined value and the result is cached
in ALIST."
  (or (if (consp list)
	  (let ((l list))
	    (while (and l (consp (car l)))
	      (setq l (cdr l)))
	    (if l list)))
      (if function
	  (cdr (assoc (setq function (cons sh-shell function)) list)))
      (let ((sh-shell sh-shell)
	    elt val)
	(while (and sh-shell
		    (not (setq elt (assq sh-shell list))))
	  (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
	(if (and (consp (setq val (cdr elt)))
		 (eq (car val) 'eval))
	    (setcdr elt
		    (setq val
			  (eval (if (consp (setq val (cdr val)))
				    (let ((sh-shell (car (cdr val)))
					  function)
				      (if (assq sh-shell list)
					  (setcar (cdr val)
						  (list 'quote
							(sh-feature list))))
				      val)
				  val)))))
	(if function
	    (nconc list
		   (list (cons function
			       (setq sh-shell (car function)
				     val (funcall (cdr function) val))))))
	val)))



(defun sh-abbrevs (ancestor &rest list)
  "Iff it isn't, define the current shell as abbrev table and fill that.
Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
table or a list of (NAME1 EXPANSION1 ...).  In addition it will define abbrevs
according to the remaining arguments NAMEi EXPANSIONi ...
EXPANSION may be either a string or a skeleton command."
  (or (if (boundp sh-shell)
	  (symbol-value sh-shell))
      (progn
	(if (listp ancestor)
	    (nconc list ancestor))
	(define-abbrev-table sh-shell ())
	(if (vectorp ancestor)
	    (mapatoms (lambda (atom)
			(or (eq atom 0)
			    (define-abbrev (symbol-value sh-shell)
			      (symbol-name atom)
			      (symbol-value atom)
			      (symbol-function atom))))
		      ancestor))
	(while list
	  (define-abbrev (symbol-value sh-shell)
	    (car list)
	    (if (stringp (car (cdr list)))
		(car (cdr list))
	      "")
	    (if (symbolp (car (cdr list)))
		(car (cdr list))))
	  (setq list (cdr (cdr list)))))
      (symbol-value sh-shell)))


(defun sh-mode-syntax-table (table &rest list)
  "Copy TABLE and set syntax for succesive CHARs according to strings S."
  (setq table (copy-syntax-table table))
  (while list
    (modify-syntax-entry (car list) (car (cdr list)) table)
    (setq list (cdr (cdr list))))
  table)


(defun sh-append (ancestor &rest list)
  "Return list composed of first argument (a list) physically appended to rest."
  (nconc list ancestor))


(defun sh-modify (skeleton &rest list)
  "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
  (setq skeleton (copy-sequence skeleton))
  (while list
    (setcar (or (nthcdr (car list) skeleton)
		(error "Index %d out of bounds" (car list)))
	    (car (cdr list)))
    (setq list (nthcdr 2 list)))
  skeleton)
Richard M. Stallman's avatar
Richard M. Stallman committed
828 829 830


(defun sh-indent-line ()
831 832
  "Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
Lines containing only comments are considered empty."
Richard M. Stallman's avatar
Richard M. Stallman committed
833 834
  (interactive)
  (let ((previous (save-excursion
835 836 837 838 839 840 841
		    (while (progn
			     (line-move -1)
			     (back-to-indentation)
			     (or (eolp)
				 (eq (following-char) ?#))))
		    (current-column)))
	current)
Richard M. Stallman's avatar
Richard M. Stallman committed
842 843 844 845
    (save-excursion
      (indent-to (if (eq this-command 'newline-and-indent)
		     previous
		   (if (< (current-column)
846 847
			  (setq current (progn (back-to-indentation)
					       (current-column))))
Richard M. Stallman's avatar
Richard M. Stallman committed
848
		       (if (eolp) previous 0)
849 850
		     (delete-region (point)
				    (progn (beginning-of-line) (point)))
Richard M. Stallman's avatar
Richard M. Stallman committed
851
		     (if (eolp)
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
			 (max previous (* (1+ (/ current sh-indentation))
					  sh-indentation))
		       (* (1+ (/ current sh-indentation)) sh-indentation))))))
    (if (< (current-column) (current-indentation))
	(skip-chars-forward " \t"))))


(defun sh-execute-region (start end &optional flag)
  "Pass optional header and region to a subshell for noninteractive execution.
The working directory is that of the buffer, and only environment variables
are already set which is why you can mark a header within the script.

With a positive prefix ARG, instead of sending region, define header from
beginning of buffer to point.  With a negative prefix ARG, instead of sending
region, clear header."
  (interactive "r\nP")
  (if flag
      (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
				 (point-marker)))
    (if sh-header-marker
	(save-excursion
	  (let (buffer-undo-list)
	    (goto-char sh-header-marker)
	    (append-to-buffer (current-buffer) start end)
	    (shell-command-on-region (point-min)
				     (setq end (+ sh-header-marker
						  (- end start)))
				     sh-shell-path)
	    (delete-region sh-header-marker end)))
      (shell-command-on-region start end (concat sh-shell-path " -")))))
Richard M. Stallman's avatar
Richard M. Stallman committed
882 883 884 885 886


(defun sh-remember-variable (var)
  "Make VARIABLE available for future completing reads in this buffer."
  (or (< (length var) sh-remember-variable-min)
887 888
      (getenv var)
      (setq process-environment (cons (concat var "=0") process-environment)))
Richard M. Stallman's avatar
Richard M. Stallman committed
889 890 891 892 893 894
  var)



(defun sh-quoted-p ()
  "Is point preceded by an odd number of backslashes?"
895
  (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
Richard M. Stallman's avatar
Richard M. Stallman committed
896 897 898 899 900 901

;; statement syntax-commands for various shells

;; You are welcome to add the syntax or even completely new statements as
;; appropriate for your favorite shell.

902 903
(define-skeleton sh-case
  "Insert a case/switch statement.  See `sh-feature'."
Richard M. Stallman's avatar
Richard M. Stallman committed
904 905 906 907 908 909 910
  (csh "expression: "
       "switch( " str " )" \n
       > "case " (read-string "pattern: ") ?: \n
       > _ \n
       "breaksw" \n
       ( "other pattern, %s: "
	 < "case " str ?: \n
911
	 > _ \n
Richard M. Stallman's avatar
Richard M. Stallman committed
912 913
	 "breaksw" \n)
       < "default:" \n
914
       > _ \n
Richard M. Stallman's avatar
Richard M. Stallman committed
915 916
       resume:
       < < "endsw")
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
  (es)
  (rc "expression: "
      "switch( " str " ) {" \n
      > "case " (read-string "pattern: ") \n
      > _ \n
      ( "other pattern, %s: "
	< "case " str \n
	> _ \n)
      < "case *" \n
      > _ \n
      resume:
      < < ?})
  (sh "expression: "
      "case " str " in" \n
      > (read-string "pattern: ") ?\) \n
      > _ \n
      ";;" \n
      ( "other pattern, %s: "
	< str ?\) \n
	> _ \n
	";;" \n)
      < "*)" \n
      > _ \n
      resume:
      < < "esac"))



(define-skeleton sh-for
  "Insert a for loop.  See `sh-feature'."
  (csh eval sh-modify sh
       1 "foreach "
       3 " ( "
       5 " )"
       15 "end")
  (es eval sh-modify rc
      3 " = ")
  (rc eval sh-modify sh
      1 "for( "
      5 " ) {"
      15 ?})
Richard M. Stallman's avatar
Richard M. Stallman committed
958 959
  (sh "Index variable: "
      "for " str " in " _ "; do" \n
960 961
      > _ | ?$ & (sh-remember-variable str) \n
      < "done"))
Richard M. Stallman's avatar
Richard M. Stallman committed
962 963 964



965 966 967
(define-skeleton sh-indexed-loop
  "Insert an indexed loop from 1 to n.  See `sh-feature'."
  (bash eval identity posix)
Richard M. Stallman's avatar
Richard M. Stallman committed
968 969
  (csh "Index variable: "
       "@ " str " = 1" \n
970 971
       "while( $" str " <= " (read-string "upper limit: ") " )" \n
       > _ ?$ str \n
Richard M. Stallman's avatar
Richard M. Stallman committed
972 973
       "@ " str "++" \n
       < "end")
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
  (es eval sh-modify rc
      3 " =")
  (ksh88 "Index variable: "
	 "integer " str "=0" \n
	 "while (( ( " str " += 1 ) <= "
	 (read-string "upper limit: ")
	 " )); do" \n
	 > _ ?$ (sh-remember-variable str) \n
	 < "done")
  (posix "Index variable: "
	 str "=1" \n
	 "while [ $" str " -le "
	 (read-string "upper limit: ")
	 " ]; do" \n
	 > _ ?$ str \n
	 str ?= (sh-add (sh-remember-variable str) 1) \n
	 < "done")
  (rc "Index variable: "
      "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
      (read-string "upper limit: ")
      "; i++ ) print i }'}) {" \n
      > _ ?$ (sh-remember-variable str) \n
      < ?})
  (sh "Index variable: "
      "for " str " in `awk 'BEGIN { for( i=1; i<="
      (read-string "upper limit: ")
      "; i++ ) print i }'`; do" \n
      > _ ?$ (sh-remember-variable str) \n
      < "done"))
Richard M. Stallman's avatar
Richard M. Stallman committed
1003 1004 1005


(defun sh-add (var delta)
1006
  "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
Richard M. Stallman's avatar
Richard M. Stallman committed
1007
  (interactive
1008 1009 1010 1011
   (list (completing-read "Variable: "
			  (mapcar (lambda (var)
				    (substring var 0 (string-match "=" var)))
				  process-environment))
Richard M. Stallman's avatar
Richard M. Stallman committed
1012
	 (prefix-numeric-value current-prefix-arg)))
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
  (insert (sh-feature '((bash . "$[ ")
			(ksh88 . "$(( ")
			(posix . "$(( ")
			(rc . "`{expr $")
			(sh . "`expr $")
			(zsh . "$[ ")))
	  (sh-remember-variable var)
	  (if (< delta 0) " - " " + ")
	  (number-to-string (abs delta))
	  (sh-feature '((bash . " ]")
			(ksh88 . " ))")
			(posix . " ))")
			(rc . "}")
			(sh . "`")
			(zsh . " ]")))))



(define-skeleton sh-function
  "Insert a function definition.  See `sh-feature'."
  (bash eval sh-modify ksh88
	3 "() {")
  (ksh88 "name: "
	 "function " str " {" \n
	 > _ \n
	 < "}")
  (rc eval sh-modify ksh88
	1 "fn ")
Richard M. Stallman's avatar
Richard M. Stallman committed
1041 1042 1043
  (sh ()
      "() {" \n
      > _ \n
1044
      < "}"))
Richard M. Stallman's avatar
Richard M. Stallman committed
1045 1046 1047



1048 1049
(define-skeleton sh-if
  "Insert an if statement.  See `sh-feature'."
Richard M. Stallman's avatar
Richard M. Stallman committed
1050 1051 1052 1053
  (csh "condition: "
       "if( " str " ) then" \n
       > _ \n
       ( "other condition, %s: "
1054 1055
	 < "else if( " str " ) then" \n
	 > _ \n)
Richard M. Stallman's avatar
Richard M. Stallman committed
1056
       < "else" \n
1057
       > _ \n
Richard M. Stallman's avatar
Richard M. Stallman committed
1058 1059
       resume:
       < "endif")
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  (es "condition: "
      "if { " str " } {" \n
       > _ \n
       ( "other condition, %s: "
	 < "} { " str " } {" \n
	 > _ \n)
       < "} {" \n
       > _ \n
       resume:
       < ?})
  (rc eval sh-modify csh
      3 " ) {"
      8 '( "other condition, %s: "
	   < "} else if( " str " ) {" \n
	   > _ \n)
      10 "} else {"
      17 ?})
  (sh "condition: "
Karl Heuer's avatar
Karl Heuer committed
1078 1079
      '(setq input (sh-feature sh-test))
      "if " str "; then" \n
1080 1081
      > _ \n
      ( "other condition, %s: "
Karl Heuer's avatar
Karl Heuer committed
1082
	< "elif " str "; then" \n
1083 1084 1085 1086 1087
	> _ \n)
      < "else" \n
      > _ \n
      resume:
      < "fi"))
Richard M. Stallman's avatar
Richard M. Stallman committed
1088 1089 1090



1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
(define-skeleton sh-repeat
  "Insert a repeat loop definition.  See `sh-feature'."
  (es nil
      "forever {" \n
      > _ \n
      < ?})
  (zsh "factor: "
      "repeat " str "; do"\n
      > _ \n
      < "done"))
(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))



(define-skeleton sh-select
  "Insert a select statement.  See `sh-feature'."
  (ksh88 "Index variable: "
	 "select " str " in " _ "; do" \n
	 > ?$ str \n
	 < "done"))
(put 'sh-select 'menu-enable '(sh-feature sh-select))



(define-skeleton sh-tmp-file
  "Insert code to setup temporary file handling.  See `sh-feature'."
  (bash eval identity ksh88)
  (csh (file-name-nondirectory (buffer-file-name))
       "set tmp = /tmp/" str ".$$" \n
       "onintr exit" \n _
       (and (goto-char (point-max))
	    (not (bolp))
	    ?\n)
       "exit:\n"
       "rm $tmp* >&/dev/null" >)
  (es (file-name-nondirectory (buffer-file-name))
      "local( signals = $signals sighup sigint; tmp = /tmp/" str ".$pid ) {" \n
      > "catch @ e {" \n
      > "rm $tmp^* >[2]/dev/null" \n
      "throw $e" \n
      < "} {" \n
      > _ \n
      < ?} \n
      < ?})
  (ksh88 eval sh-modify sh
	 6 "EXIT")
  (rc (file-name-nondirectory (buffer-file-name))
       "tmp = /tmp/" str ".$pid" \n
       "fn sigexit { rm $tmp^* >[2]/dev/null }")
  (sh (file-name-nondirectory (buffer-file-name))
      "TMP=/tmp/" str ".$$" \n
      "trap \"rm $TMP* 2>/dev/null\" " ?0))
Richard M. Stallman's avatar
Richard M. Stallman committed
1143 1144 1145



1146 1147
(define-skeleton sh-until
  "Insert an until loop.  See `sh-feature'."
Richard M. Stallman's avatar
Richard M. Stallman committed
1148
  (sh "condition: "
Karl Heuer's avatar
Karl Heuer committed
1149 1150
      '(setq input (sh-feature sh-test))
      "until " str "; do" \n
Richard M. Stallman's avatar
Richard M. Stallman committed
1151
      > _ \n
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
      < "done"))
(put 'sh-until 'menu-enable '(sh-feature sh-until))



(define-skeleton sh-while
  "Insert a while loop.  See `sh-feature'."
  (csh eval sh-modify sh
       1 "while( "
       3 " )"
       9 "end")
  (es eval sh-modify rc
      1 "while { "
      3 " } {")
  (rc eval sh-modify csh
      3 " ) {"
      9 ?})
Richard M. Stallman's avatar
Richard M. Stallman committed
1169
  (sh "condition: "
Karl Heuer's avatar
Karl Heuer committed
1170 1171
      '(setq input (sh-feature sh-test))
      "while " str "; do" \n
Richard M. Stallman's avatar
Richard M. Stallman committed
1172
      > _ \n
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
      < "done"))



(define-skeleton sh-while-getopts
  "Insert a while getopts loop.  See `sh-feature'.
Prompts for an options string which consists of letters for each recognized
option followed by a colon `:' if the option accepts an argument."
  (bash eval sh-modify sh
	18 "${0##*/}")
Karl Heuer's avatar
Karl Heuer committed
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  (csh nil
       "while( 1 )" \n
       > "switch( \"$1\" )" \n
       '(setq input '("- x" . 2))
       > >
       ( "option, %s: "
	 < "case " '(eval str)
	 '(if (string-match " +" str)
	      (setq v1 (substring str (match-end 0))
		    str (substring str 0 (match-beginning 0)))
	    (setq v1 nil))
	 str ?: \n
	 > "set " v1 & " = $2" | -4 & _ \n
	 (if v1 "shift") & \n
	 "breaksw" \n)
       < "case --:" \n
       > "shift" \n
       < "default:" \n
       > "break" \n
       resume:
       < < "endsw" \n
       "shift" \n
       < "end")
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  (ksh88 eval sh-modify sh
	 16 "print"
	 18 "${0##*/}"
	 36 "OPTIND-1")
  (posix eval sh-modify sh
	 18 "$(basename $0)")
  (sh "optstring: "
      "while getopts :" str " OPT; do" \n
      > "case $OPT in" \n
      > >
      '(setq v1 (append (vconcat str) nil))
      ( (prog1 (if v1 (char-to-string (car v1)))
	  (if (eq (nth 1 v1) ?:)
	      (setq v1 (nthcdr 2 v1)
		    v2 "\"$OPTARG\"")
	    (setq v1 (cdr v1)
		  v2 nil)))
	< str "|+" str ?\) \n
	> _ v2 \n
	";;" \n)
      < "*)" \n
      > "echo" " \"usage: " "`basename $0`"
      "[ +-" '(setq v1 (point)) str
      '(save-excursion
	 (while (search-backward ":" v1 t)
	   (replace-match " arg][ +-" t t)))
      (if (eq (preceding-char) ?-) -5)
      "][ --] args\"" \n
      "exit 2" \n
      < < "esac" \n
      < "done" \n
      "shift " (sh-add "OPTIND" -1)))
(put 'sh-while-getopts 'menu-enable '(sh-feature sh-while-getopts))
Richard M. Stallman's avatar
Richard M. Stallman committed
1239 1240 1241 1242



(defun sh-assignment (arg)
1243
  "Remember preceding identifier for future completion and do self-insert."
Richard M. Stallman's avatar
Richard M. Stallman committed
1244
  (interactive "p")
1245 1246
  (self-insert-command arg)
  (if (<= arg 1)
Richard M. Stallman's avatar
Richard M. Stallman committed
1247 1248
      (sh-remember-variable
       (save-excursion
1249 1250 1251 1252 1253
	 (if (re-search-forward (sh-feature sh-assignment-regexp)
				(prog1 (point)
				  (beginning-of-line 1))
				t)
	     (buffer-substring (match-beginning 1) (match-end 1)))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264



(defun sh-maybe-here-document (arg)
  "Inserts self.  Without prefix, following unquoted `<' inserts here document.
The document is bounded by `sh-here-document-word'."
  (interactive "*P")
  (self-insert-command (prefix-numeric-value arg))
  (or arg
      (not (eq (char-after (- (point) 2)) last-command-char))
      (save-excursion
1265
	(backward-char 2)
Richard M. Stallman's avatar
Richard M. Stallman committed
1266 1267 1268
	(sh-quoted-p))
      (progn
	(insert sh-here-document-word)
1269
	(or (eolp) (looking-at "[ \t]") (insert ? ))
Richard M. Stallman's avatar
Richard M. Stallman committed
1270
	(end-of-line 1)
1271 1272 1273
	(while
	    (sh-quoted-p)
	  (end-of-line 2))
Richard M. Stallman's avatar
Richard M. Stallman committed
1274 1275 1276 1277 1278 1279
	(newline)
	(save-excursion (insert ?\n sh-here-document-word)))))


;; various other commands

1280 1281 1282 1283 1284 1285
(autoload 'comint-dynamic-complete "comint"
  "Dynamically perform completion at point." t)

(autoload 'shell-dynamic-complete-command "shell"
  "Dynamically complete the command at point." t)

Richard M. Stallman's avatar
Richard M. Stallman committed
1286 1287 1288
(autoload 'comint-dynamic-complete-filename "comint"
  "Dynamically complete the filename at point." t)

1289 1290 1291
(autoload 'shell-dynamic-complete-environment-variable "shell"
  "Dynamically complete the environment variable at point." t)

Richard M. Stallman's avatar
Richard M. Stallman committed
1292 1293 1294 1295 1296 1297 1298


(defun sh-newline-and-indent (&optional arg)
  "Strip unquoted whitespace, insert newline, and indent like current line.
Unquoted whitespace is stripped from the current line's end, unless a
prefix ARG is given."
  (interactive "*P")
1299
  (let ((previous (current-indentation)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1300
    (if arg ()
1301 1302 1303 1304 1305
      (just-one-space)
      (backward-char)
      (if (sh-quoted-p)
	  (forward-char)
	(delete-char 1)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    (newline)
    (indent-to previous)))



(defun sh-beginning-of-command ()
  "Move point to successive beginnings of commands."
  (interactive)
  (if (re-search-backward sh-beginning-of-command nil t)
      (goto-char (match-beginning 2))))


(defun sh-end-of-command ()
  "Move point to successive ends of commands."
  (interactive)
  (if (re-search-forward sh-end-of-command nil t)
      (goto-char (match-end 1))))

;; sh-script.el ends here