sh-script.el 47.3 KB
Newer Older
Richard M. Stallman's avatar
Richard M. Stallman committed
1
;;; sh-script.el --- shell-script editing commands for Emacs
Erik Naggum's avatar
Erik Naggum committed
2

3
;; Copyright (C) 1993, 94, 95, 96, 1997 by Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

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

;; 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
Erik Naggum's avatar
Erik Naggum committed
23 24 25
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
Richard M. Stallman's avatar
Richard M. Stallman committed
26 27 28

;;; Commentary:

29 30 31 32 33
;; 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
34

35 36
;;; Known Bugs:

37
;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 39
;; - Variables in `"' strings aren't fontified because there's no way of
;;   syntactically distinguishing those from `'' strings.
40

Richard M. Stallman's avatar
Richard M. Stallman committed
41 42 43 44 45 46 47
;;; 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

48 49
(require 'executable)

50 51 52 53 54 55
(defvar sh-mode-hook nil
  "*Hook run by `sh-mode'.")

(defvar sh-set-shell-hook nil
  "*Hook run by `sh-set-shell'.")

56 57 58 59 60 61 62 63 64 65 66 67
(defgroup sh nil
  "Shell programming utilities"
  :group 'unix
  :group 'languages)

(defgroup sh-script nil
  "Shell script mode"
  :group 'sh
  :prefix "sh-")


(defcustom sh-ancestor-alist
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  '((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)
83 84
    (zsh . ksh88)
    (rpm . sh))
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  "*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
107 108 109
  wsh		? Shell"
  :type '(repeat (cons symbol symbol))
  :group 'sh-script)
110 111


112
(defcustom sh-alias-alist
113
  (nconc (if (eq system-type 'gnu/linux)
114
	     '((csh . tcsh)
115
	       (ksh . pdksh)))
116 117 118 119 120
	 ;; 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
121 122 123
shell it really is."
  :type '(repeat (cons symbol symbol))
  :group 'sh-script)
124 125


126
(defcustom sh-shell-file
127
  (or
128 129
   ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
   ;; the executable extension, so comparisons with the list of
130
   ;; known shells work.
131
   (and (memq system-type '(ms-dos windows-nt))
132 133 134 135 136 137 138
	(let* ((shell (getenv "SHELL"))
	       (shell-base
		(and shell (file-name-nondirectory shell))))
	  ;; shell-script mode doesn't support DOS/Windows shells,
	  ;; so use the default instead.
	  (if (or (null shell)
		  (member (downcase shell-base)
139 140
			  '("command.com" "cmd.exe" "4dos.com" "ndos.com"
			    "cmdproxy.exe")))
141 142
	      "/bin/sh"
	    (file-name-sans-extension (downcase shell)))))
143 144
   (getenv "SHELL")
   "/bin/sh")
145 146 147
  "*The executable file name for the shell being programmed."
  :type 'string
  :group 'sh-script)
148 149


150
(defcustom sh-shell-arg
151
  ;; bash does not need any options when run in a shell script,
152
  '((bash)
153 154
    (csh . "-f")
    (pdksh)
155
    ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
156
    (ksh88)
157
    ;; -p means don't initialize functions from the environment.
158
    (rc . "-p")
159 160 161 162
    ;; Someone proposed -motif, but we don't want to encourage
    ;; use of a non-free widget set.
    (wksh)
    ;; -f means don't run .zshrc.
163
    (zsh . "-f"))
164 165 166 167 168 169 170 171
  "*Single argument string for the magic number.  See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (const :tag "No Arguments" nil)
			       (string :tag "Arguments")
			       (cons :format "Evaluate: %v"
				     (const :format "" eval)
				     sexp))))
  :group 'sh-script)
172

173 174 175 176 177 178 179 180 181 182 183
(defcustom sh-imenu-generic-expression
  (list
   (cons 'sh
	 (concat
	  "\\(^\\s-*function\\s-+[A-Za-z_][A-Za-z_0-9]*\\)"
	  "\\|"
	  "\\(^\\s-*[A-Za-z_][A-Za-z_0-9]*\\s-*()\\)")))
  "*Regular expression for recognizing shell function definitions.
See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       regexp))
Dan Nicolaescu's avatar
Dan Nicolaescu committed
184 185
  :group 'sh-script
  :version "20.3")
186

187 188 189 190 191
(defvar sh-shell-variables nil
  "Alist of shell variable names that should be included in completion.
These are used for completion in addition to all the variables named
in `process-environment'.  Each element looks like (VAR . VAR), where
the car and cdr are the same symbol.")
192

193 194 195
(defvar sh-shell-variables-initialized nil
  "Non-nil if `sh-shell-variables' is initialized.")

196 197
(defun sh-canonicalize-shell (shell)
  "Convert a shell name SHELL to the one we should handle it as."
198 199
  (if (string-match "\.exe\\'" shell)
      (setq shell (substring shell 0 (match-beginning 0))))
200 201 202 203
  (or (symbolp shell)
      (setq shell (intern shell)))
  (or (cdr (assq shell sh-alias-alist))
      shell))
204

205 206
(defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
  "The shell being programmed.  This is set by \\[sh-set-shell].")
207

208 209 210 211 212 213
;;; I turned off this feature because it doesn't permit typing commands
;;; in the usual way without help.
;;;(defvar sh-abbrevs
;;;  '((csh eval sh-abbrevs shell
;;;	 "switch" 'sh-case
;;;	 "getopts" 'sh-while-getopts)
214

215 216
;;;    (es eval sh-abbrevs shell
;;;	"function" 'sh-function)
217

218 219
;;;    (ksh88 eval sh-abbrevs sh
;;;	   "select" 'sh-select)
220

221 222 223
;;;    (rc eval sh-abbrevs shell
;;;	"case" 'sh-case
;;;	"function" 'sh-function)
224

225 226 227 228 229
;;;    (sh eval sh-abbrevs shell
;;;	"case" 'sh-case
;;;	"function" 'sh-function
;;;	"until" 'sh-until
;;;	"getopts" 'sh-while-getopts)
230

231 232 233 234 235 236
;;;    ;; 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)
237

238 239 240 241 242
;;;    (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
243 244 245 246



(defvar sh-mode-syntax-table
247 248 249 250
  '((sh eval sh-mode-syntax-table ()
	?\# "<"
	?\^l ">#"
	?\n ">#"
251 252
	?\" "\"\""
	?\' "\"'"
253
	?\` "\"`"
254 255 256 257 258 259
	?! "_"
	?% "_"
	?: "_"
	?. "_"
	?^ "_"
	?~ "_")
260 261
    (csh eval identity sh)
    (rc eval identity sh))
262 263 264
  "Syntax-table used in Shell-Script mode.  See `sh-feature'.")


Richard M. Stallman's avatar
Richard M. Stallman committed
265 266

(defvar sh-mode-map
267 268
  (let ((map (make-sparse-keymap))
	(menu-map (make-sparse-keymap "Insert")))
Richard M. Stallman's avatar
Richard M. Stallman committed
269 270 271
    (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)
272
    (define-key map "\C-c\C-t" 'sh-tmp-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
273
    (define-key map "\C-c\C-s" 'sh-select)
274 275
    (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
276 277 278 279
    (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)
280

Richard M. Stallman's avatar
Richard M. Stallman committed
281 282
    (define-key map "=" 'sh-assignment)
    (define-key map "\C-c+" 'sh-add)
283 284
    (define-key map "\C-\M-x" 'sh-execute-region)
    (define-key map "\C-c\C-x" 'executable-interpret)
285
    (define-key map "<" 'sh-maybe-here-document)
286 287 288 289 290 291
    (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
292 293

    (define-key map "\t" 'sh-indent-line)
294
    (substitute-key-definition 'complete-tag 'comint-dynamic-complete
Richard M. Stallman's avatar
Richard M. Stallman committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308
			       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))
309 310 311 312 313 314 315 316 317 318 319 320 321
    (define-key map [menu-bar insert] (cons "Insert" menu-map))
    (define-key menu-map [sh-while]	'("While Loop" . sh-while))
    (define-key menu-map [sh-until]	'("Until Loop" . sh-until))
    (define-key menu-map [sh-tmp-file]	'("Temporary File" . sh-tmp-file))
    (define-key menu-map [sh-select]	'("Select Statement" . sh-select))
    (define-key menu-map [sh-repeat]	'("Repeat Loop" . sh-repeat))
    (define-key menu-map [sh-while-getopts]
					'("Options Loop" . sh-while-getopts))
    (define-key menu-map [sh-indexed-loop]
					'("Indexed Loop" . sh-indexed-loop))
    (define-key menu-map [sh-if]	'("If Statement" . sh-if))
    (define-key menu-map [sh-for]	'("For Loop" . sh-for))
    (define-key menu-map [sh-case]	'("Case Statement" . sh-case))
Richard M. Stallman's avatar
Richard M. Stallman committed
322 323 324 325 326
    map)
  "Keymap used in Shell-Script mode.")



327
(defcustom sh-dynamic-complete-functions
328 329 330
  '(shell-dynamic-complete-environment-variable
    shell-dynamic-complete-command
    comint-dynamic-complete-filename)
331 332 333
  "*Functions for doing TAB dynamic completion."
  :type '(repeat function)
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
334 335


336
(defcustom sh-require-final-newline
337 338 339 340 341
  '((csh . t)
    (pdksh . t)
    (rc eval . require-final-newline)
    (sh eval . require-final-newline))
  "*Value of `require-final-newline' in Shell-Script mode buffers.
342 343 344 345 346 347 348
See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (const :tag "require" t)
			       (cons :format "Evaluate: %v"
				     (const :format "" eval)
				     sexp))))
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
349 350


351
(defcustom sh-assignment-regexp
352 353 354 355 356 357 358
  '((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 `='
359 360 361 362 363 364 365
sign.  See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice regexp
			       (cons :format "Evaluate: %v"
				     (const :format "" eval)
				     sexp))))
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
366 367


368 369 370 371
(defcustom sh-indentation 4
  "The width for further indentation in Shell-Script mode."
  :type 'integer
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
372 373


374 375 376 377
(defcustom sh-remember-variable-min 3
  "*Don't remember variables less than this length for completing reads."
  :type 'integer
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
378 379


380 381 382 383 384
(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.")


385
(defcustom sh-beginning-of-command
386
  "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
Richard M. Stallman's avatar
Richard M. Stallman committed
387
  "*Regexp to determine the beginning of a shell command.
388 389 390
The actual command starts at the beginning of the second \\(grouping\\)."
  :type 'regexp
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
391

392

393
(defcustom sh-end-of-command
394
  "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
Richard M. Stallman's avatar
Richard M. Stallman committed
395
  "*Regexp to determine the end of a shell command.
396 397 398
The actual command ends at the end of the first \\(grouping\\)."
  :type 'regexp
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
399 400 401



402
(defvar sh-here-document-word "EOF"
Richard M. Stallman's avatar
Richard M. Stallman committed
403 404
  "Word to delimit here documents.")

Karl Heuer's avatar
Karl Heuer committed
405 406 407 408 409
(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
410

411 412 413
;; customized this out of sheer bravado.  not for the faint of heart.
;; but it *did* have an asterisk in the docstring!
(defcustom sh-builtins
414 415 416 417
  '((bash eval sh-append posix
	  "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
	  "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
	  "suspend" "typeset" "unalias")
Richard M. Stallman's avatar
Richard M. Stallman committed
418

419 420
    ;; The next entry is only used for defining the others
    (bourne eval sh-append shell
421 422
	    "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
	    "times" "ulimit")
Richard M. Stallman's avatar
Richard M. Stallman committed
423

424
    (csh eval sh-append shell
425 426 427 428
	 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
	 "setenv" "source" "time" "unalias" "unhash")

    (dtksh eval identity wksh)
Richard M. Stallman's avatar
Richard M. Stallman committed
429

430 431
    (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
	"newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
Richard M. Stallman's avatar
Richard M. Stallman committed
432

433 434
    (jsh eval sh-append sh
	 "bg" "fg" "jobs" "kill" "stop" "suspend")
Richard M. Stallman's avatar
Richard M. Stallman committed
435

436 437 438 439
    (jcsh eval sh-append csh
	 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")

    (ksh88 eval sh-append bourne
440 441
	   "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
	   "typeset" "unalias" "whence")
442 443 444 445 446 447 448 449 450 451 452 453 454

    (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")

455 456
    (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
	"whatis")
457 458 459 460 461

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

    ;; The next entry is only used for defining the others
462 463 464 465
    (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")

    (wksh eval sh-append ksh88
	  "Xt[A-Z][A-Za-z]*")
466 467

    (zsh eval sh-append ksh88
468 469 470 471 472 473
	 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
	 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
	 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
	 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
	 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
	 "which"))
474 475
  "*List of all shell builtins for completing read and fontification.
Note that on some systems not all builtins are available or some are
476 477 478 479 480 481 482
implemented as aliases.  See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (repeat string)
			       (cons :format "Evaluate: %v"
				     (const :format "" eval)
				     sexp))))
  :group 'sh-script)
483 484


485

486
(defcustom sh-leading-keywords
487 488 489 490 491 492 493 494 495 496
  '((csh "else")

    (es "true" "unwind-protect" "whatis")

    (rc "else")

    (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
  "*List of keywords that may be immediately followed by a builtin or keyword.
Given some confusion between keywords and builtins depending on shell and
system, the distinction here has been based on whether they influence the
497 498 499 500 501 502 503
flow of control or syntax.  See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (repeat string)
			       (cons :format "Evaluate: %v"
				     (const :format "" eval)
				     sexp))))
  :group 'sh-script)
504 505


506
(defcustom sh-other-keywords
507 508
  '((bash eval sh-append bourne
	  "bye" "logout")
509 510

    ;; The next entry is only used for defining the others
511 512
    (bourne eval sh-append sh
	    "function")
513

514 515 516
    (csh eval sh-append shell
	 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
	 "if" "logout" "onintr" "repeat" "switch" "then" "while")
517

518 519
    (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
	"return" "throw" "while")
520 521

    (ksh88 eval sh-append bourne
522
	   "select")
523

524 525
    (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
	"while")
526

527 528 529
    (sh eval sh-append shell
	"done" "esac" "fi" "for" "in" "return")

530 531
    ;; The next entry is only used for defining the others
    (shell "break" "case" "continue" "exec" "exit")
532

533 534 535
    (zsh eval sh-append bash
	 "select"))
  "*List of keywords not in `sh-leading-keywords'.
536 537 538 539 540 541 542
See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (repeat string)
			       (cons :format "Evaluate: %v"
				     (const :format "" eval)
				     sexp))))
  :group 'sh-script)
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616



(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
617
	   font-lock-variable-name-face))
618 619 620

    (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
621
	  font-lock-variable-name-face))
622

623
    (rc eval identity es)
624 625

    (sh eval sh-append shell
626
	;; Variable names.
627
	'("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
628 629 630 631 632
	  font-lock-variable-name-face)
	;; Function names.
	'("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
	'("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
	  (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t)))
633 634 635

    ;; The next entry is only used for defining the others
    (shell eval sh-append executable-font-lock-keywords
636
	   '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
637
	   '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
638 639 640 641 642
	     font-lock-variable-name-face))
    (rpm eval sh-append rpm2
	 '("%{?\\(\\sw+\\)"  1 font-lock-keyword-face))
    (rpm2 eval sh-append shell
	  '("^\\(\\sw+\\):"  1 font-lock-variable-name-face)))
643
  "Default expressions to highlight in Shell Script modes.  See `sh-feature'.")
644

645
(defvar sh-font-lock-keywords-1
646
  '((sh "[ \t]in\\>"))
647
  "Subdued level highlighting for Shell Script modes.")
648 649

(defvar sh-font-lock-keywords-2 ()
650
  "Gaudy level highlighting for Shell Script modes.")
651

652 653
(defconst sh-font-lock-syntactic-keywords
  ;; Mark a `#' character as having punctuation syntax in a variable reference.
654 655 656 657 658 659 660 661
  ;; Really we should do this properly.  From Chet Ramey and Brian Fox:
  ;; "A `#' begins a comment when it is unquoted and at the beginning of a
  ;; word.  In the shell, words are separated by metacharacters."
  ;; To do this in a regexp would be slow as it would be anchored to the right.
  ;; But I can't be bothered to write a function to do it properly and
  ;; efficiently.  So we only do it properly for `#' in variable references and
  ;; do it efficiently by anchoring the regexp to the left.
  '(("\\${?[^}#\n\t ]*\\(##?\\)" 1 (1 . nil))))
662 663 664 665

;; mode-command and utility functions

;;;###autoload
666
(put 'sh-mode 'mode-class 'special)
Erik Naggum's avatar
Erik Naggum committed
667 668

;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
669 670 671 672 673 674 675
(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.

676 677 678 679
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
680

681 682 683
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
684 685 686 687 688 689

\\[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
690 691 692
\\[sh-while-getopts]	 while getopts loop
\\[sh-repeat]	 repeat loop
\\[sh-select]	 select loop
Richard M. Stallman's avatar
Richard M. Stallman committed
693 694 695 696 697 698 699 700
\\[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.
701
\\[sh-execute-region]	 Have optional header and region be executed in a subshell.
Richard M. Stallman's avatar
Richard M. Stallman committed
702 703 704

\\[sh-maybe-here-document]	 Without prefix, following an unquoted < inserts here document.
{, (, [, ', \", `
705 706 707
	Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.

If you generally program a shell different from your login shell you can
708
set `sh-shell-file' accordingly.  If your shell's file name doesn't correctly
709 710 711 712
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
713 714 715 716
  (interactive)
  (kill-all-local-variables)
  (use-local-map sh-mode-map)
  (make-local-variable 'indent-line-function)
717
  (make-local-variable 'indent-region-function)
718
  (make-local-variable 'skeleton-end-hook)
719 720
  (make-local-variable 'paragraph-start)
  (make-local-variable 'paragraph-separate)
Richard M. Stallman's avatar
Richard M. Stallman committed
721 722 723
  (make-local-variable 'comment-start)
  (make-local-variable 'comment-start-skip)
  (make-local-variable 'require-final-newline)
724
  (make-local-variable 'sh-header-marker)
725
  (make-local-variable 'sh-shell-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
726
  (make-local-variable 'sh-shell)
727 728
  (make-local-variable 'skeleton-pair-alist)
  (make-local-variable 'skeleton-pair-filter)
729 730
  (make-local-variable 'comint-dynamic-complete-functions)
  (make-local-variable 'comint-prompt-regexp)
731
  (make-local-variable 'font-lock-defaults)
732
  (make-local-variable 'skeleton-filter)
733
  (make-local-variable 'skeleton-newline-indent-rigidly)
734 735
  (make-local-variable 'sh-shell-variables)
  (make-local-variable 'sh-shell-variables-initialized)
736
  (make-local-variable 'imenu-generic-expression)
Richard M. Stallman's avatar
Richard M. Stallman committed
737 738 739
  (setq major-mode 'sh-mode
	mode-name "Shell-script"
	indent-line-function 'sh-indent-line
740 741
	;; not very clever, but enables wrapping skeletons around regions
	indent-region-function (lambda (b e)
742 743 744 745 746 747 748 749 750
				 (save-excursion
				   (goto-char b)
				   (skip-syntax-backward "-")
				   (setq b (point))
				   (goto-char e)
				   (skip-syntax-backward "-")
				   (indent-rigidly b (point) sh-indentation)))
	skeleton-end-hook (lambda ()
			    (or (eolp) (newline) (indent-relative)))
751
	paragraph-start (concat page-delimiter "\\|$")
752
	paragraph-separate paragraph-start
Richard M. Stallman's avatar
Richard M. Stallman committed
753
	comment-start "# "
754 755 756
	comint-dynamic-complete-functions sh-dynamic-complete-functions
	;; we can't look if previous line ended with `\'
	comint-prompt-regexp "^[ \t]*"
757
	font-lock-defaults
758 759 760 761 762
	'((sh-font-lock-keywords
	   sh-font-lock-keywords-1 sh-font-lock-keywords-2)
	  nil nil
	  ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
	  (font-lock-syntactic-keywords . sh-font-lock-syntactic-keywords))
763 764
	skeleton-pair-alist '((?` _ ?`))
	skeleton-pair-filter 'sh-quoted-p
765 766
	skeleton-further-elements '((< '(- (min sh-indentation
						(current-column)))))
767 768
	skeleton-filter 'sh-feature
	skeleton-newline-indent-rigidly t)
769 770
  (make-local-variable 'parse-sexp-ignore-comments)
  (setq parse-sexp-ignore-comments t)
771 772 773 774 775
  ;; Parse or insert magic number for exec, and set all variables depending
  ;; on the shell thus determined.
  (let ((interpreter
	 (save-excursion
	   (goto-char (point-min))
776 777 778 779
	   (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
		 (match-string 2))
		 ((string-match "\\.m?spec$" buffer-file-name)
		  "rpm")))))
780
    (if interpreter
781
	(sh-set-shell interpreter nil nil)
782 783 784 785 786 787
      (progn
        ;; If we don't know the shell for this file, set the syntax
        ;; table anyway, for the user's normal choice of shell.
        (set-syntax-table (sh-feature sh-mode-syntax-table))
        ;; And avoid indent-new-comment-line (at least) losing.
        (setq comment-start-skip "#+[\t ]*"))))
Richard M. Stallman's avatar
Richard M. Stallman committed
788
  (run-hooks 'sh-mode-hook))
789
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
790 791 792
(defalias 'shell-script-mode 'sh-mode)


793 794 795 796
(defun sh-font-lock-keywords (&optional keywords)
  "Function to get simple fontification based on `sh-font-lock-keywords'.
This adds rules for comments and assignments."
  (sh-feature sh-font-lock-keywords
797 798 799 800 801 802
	      (when (stringp (sh-feature sh-assignment-regexp))
		(lambda (list)
		  `((,(sh-feature sh-assignment-regexp)
		     1 font-lock-variable-name-face)
		    ,@keywords
		    ,@list)))))
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821

(defun sh-font-lock-keywords-1 (&optional builtins)
  "Function to get better fontification including keywords."
  (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
			  (mapconcat 'identity
				     (sh-feature sh-leading-keywords)
				     "\\|")
			  "\\)[ \t]+\\)?\\("
			  (mapconcat 'identity
				     (append (sh-feature sh-leading-keywords)
					     (sh-feature sh-other-keywords))
				     "\\|")
			  "\\)")))
    (sh-font-lock-keywords
     `(,@(if builtins
	     `((,(concat keywords "[ \t]+\\)?\\("
			 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
			 "\\)\\>")
		(2 font-lock-keyword-face nil t)
Simon Marshall's avatar
Simon Marshall committed
822
		(6 font-lock-builtin-face))
823 824 825 826 827 828 829 830 831
	       ,@(sh-feature sh-font-lock-keywords-2)))
	 (,(concat keywords "\\)\\>")
	  2 font-lock-keyword-face)
	 ,@(sh-feature sh-font-lock-keywords-1)))))

(defun sh-font-lock-keywords-2 ()
  "Function to get better fontification including keywords and builtins."
  (sh-font-lock-keywords-1 t))

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

833
(defun sh-set-shell (shell &optional no-query-flag insert-flag)
834
  "Set this buffer's shell to SHELL (a string).
835 836
Makes this script executable via `executable-set-magic', and sets up the
proper starting #!-line, if INSERT-FLAG is non-nil.
837
Calls the value of `sh-set-shell-hook' if set."
838 839
  (interactive (list (completing-read "Name or path of shell: "
				      interpreter-mode-alist
840 841 842
				      (lambda (x) (eq (cdr x) 'sh-mode)))
		     (eq executable-query 'function)
		     t))
843 844
  (if (string-match "\.exe\\'" shell)
      (setq shell (substring shell 0 (match-beginning 0))))
845 846
  (setq sh-shell (intern (file-name-nondirectory shell))
	sh-shell (or (cdr (assq sh-shell sh-alias-alist))
847
		     sh-shell))
848 849 850 851
  (if insert-flag
      (setq sh-shell-file
	    (executable-set-magic shell (sh-feature sh-shell-arg)
				  no-query-flag insert-flag)))
852
  (setq require-final-newline (sh-feature sh-require-final-newline)
853
;;;	local-abbrev-table (sh-feature sh-abbrevs)
854 855 856
;; Packages should not need to set these variables directly.  sm.
;	font-lock-keywords nil		; force resetting
;	font-lock-syntax-table nil
857
	comment-start-skip "#+[\t ]*"
858
	mode-line-process (format "[%s]" sh-shell)
859
	sh-shell-variables nil
860
	sh-shell-variables-initialized nil
861
	imenu-generic-expression (sh-feature sh-imenu-generic-expression)
862
	imenu-case-fold-search nil)
863 864
  (set-syntax-table (or (sh-feature sh-mode-syntax-table)
			(standard-syntax-table)))
865 866 867 868
  (let ((vars (sh-feature sh-variables)))
    (while vars
      (sh-remember-variable (car vars))
      (setq vars (cdr vars))))
869 870 871 872
;; Packages should not need to toggle Font Lock mode.  sm.
;  (and (boundp 'font-lock-mode)
;       font-lock-mode
;       (font-lock-mode (font-lock-mode 0)))
873 874 875
  (run-hooks 'sh-set-shell-hook))


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

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
(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)))



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 958 959
;;; I commented this out because nobody calls it -- rms.
;;;(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)))
960 961 962


(defun sh-mode-syntax-table (table &rest list)
Karl Heuer's avatar
Karl Heuer committed
963
  "Copy TABLE and set syntax for successive CHARs according to strings S."
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
  (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
985 986 987


(defun sh-indent-line ()
988 989
  "Indent a line for Sh mode (shell script mode).
Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
990
Lines containing only comments are considered empty."
Richard M. Stallman's avatar
Richard M. Stallman committed
991 992
  (interactive)
  (let ((previous (save-excursion
993 994
		    (while (and (progn (beginning-of-line)
				       (not (bobp)))
995 996 997 998 999
				(progn
				  (forward-line -1)
				  (back-to-indentation)
				  (or (eolp)
				      (eq (following-char) ?#)))))
1000 1001
		    (current-column)))
	current)
Richard M. Stallman's avatar
Richard M. Stallman committed
1002 1003 1004 1005
    (save-excursion
      (indent-to (if (eq this-command 'newline-and-indent)
		     previous
		   (if (< (current-column)
1006 1007
			  (setq current (progn (back-to-indentation)
					       (current-column))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1008
		       (if (eolp) previous 0)
1009 1010
		     (delete-region (point)
				    (progn (beginning-of-line) (point)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1011
		     (if (eolp)
1012 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
			 (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)))
1039
				     sh-shell-file)
1040
	    (delete-region sh-header-marker end)))
1041
      (shell-command-on-region start end (concat sh-shell-file " -")))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1042 1043 1044 1045 1046


(defun sh-remember-variable (var)
  "Make VARIABLE available for future completing reads in this buffer."
  (or (< (length var) sh-remember-variable-min)
1047
      (getenv var)
1048 1049
      (assoc var sh-shell-variables)
      (setq sh-shell-variables (cons (cons var var) sh-shell-variables)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1050 1051 1052 1053 1054 1055
  var)



(defun sh-quoted-p ()
  "Is point preceded by an odd number of backslashes?"
1056
  (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1057 1058 1059 1060 1061 1062

;; statement syntax-commands for various shells

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

1063 1064
(define-skeleton sh-case
  "Insert a case/switch statement.  See `sh-feature'."
1065 1066 1067
  (csh "expression: "
       "switch( " str " )" \n
       > "case " (read-string "pattern: ") ?: \n
1068
       > _ \n
1069
       "breaksw" \n
1070
       ( "other pattern, %s: "
1071
	 < "case " str ?: \n
1072
	 > _ \n
1073 1074
	 "breaksw" \n)
       < "default:" \n
1075 1076
       > _ \n
       resume:
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
       < < "endsw")
  (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"))
1103 1104 1105 1106 1107