sh-script.el 146 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 4
;; Copyright (C) 1993-1997, 1999, 2001-2013 Free Software Foundation,
;; Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
5

Karl Heuer's avatar
Karl Heuer committed
6
;; Author: Daniel Pfeiffer <occitan@esperanto.org>
7
;; Version: 2.0f
Richard M. Stallman's avatar
Richard M. Stallman committed
8
;; Maintainer: FSF
9
;; Keywords: languages, unix
Richard M. Stallman's avatar
Richard M. Stallman committed
10 11 12

;; This file is part of GNU Emacs.

13
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
17 18 19 20 21 22 23

;; 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
24
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
25 26 27

;;; Commentary:

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

34 35
;;; Known Bugs:

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

40 41 42 43
;;		Indentation
;;	 	===========
;; Indentation for rc and es modes is very limited, but for Bourne shells
;; and its derivatives it is quite customizable.
44
;;
45 46
;; The following description applies to sh and derived shells (bash,
;; zsh, ...).
47
;;
48 49 50 51
;; There are various customization variables which allow tailoring to
;; a wide variety of styles.  Most of these variables are named
;; sh-indent-for-XXX and sh-indent-after-XXX.  For example.
;; sh-indent-after-if controls the indenting of a line following
Stefan Monnier's avatar
Stefan Monnier committed
52
;; an if statement, and sh-indent-for-fi controls the indentation
53
;; of the line containing the fi.
54
;;
55 56 57 58
;; You can set each to a numeric value, but it is often more convenient
;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
;; By changing this one variable you can increase or decrease how much
;; indentation there is.  Valid symbols:
59
;;
60 61 62 63 64 65
;; 	+   Indent right by sh-basic-offset
;; 	-   Indent left  by sh-basic-offset
;; 	++  Indent right twice sh-basic-offset
;; 	--  Indent left  twice sh-basic-offset
;; 	*   Indent right half sh-basic-offset
;; 	/   Indent left  half sh-basic-offset.
66
;;
67
;; There are 4 commands to help set the indentation variables:
68
;;
69 70 71
;; `sh-show-indent'
;;    This shows what variable controls the indentation of the current
;;    line and its value.
72
;;
73 74 75 76 77 78 79
;; `sh-set-indent'
;;    This allows you to set the value of the variable controlling the
;;    current line's indentation.  You can enter a number or one of a
;;    number of special symbols to denote the value of sh-basic-offset,
;;    or its negative, or half it, or twice it, etc.  If you've used
;;    cc-mode this should be familiar.  If you forget which symbols are
;;    valid simply press C-h at the prompt.
80
;;
81 82 83 84 85
;; `sh-learn-line-indent'
;;    Simply make the line look the way you want it, then invoke this
;;    command.  It will set the variable to the value that makes the line
;;    indent like that.  If called with a prefix argument then it will set
;;    the value to one of the symbols if applicable.
86
;;
87 88 89 90 91 92 93 94 95 96 97 98
;; `sh-learn-buffer-indent'
;;    This is the deluxe function!  It "learns" the whole buffer (use
;;    narrowing if you want it to process only part).  It outputs to a
;;    buffer *indent* any conflicts it finds, and all the variables it has
;;    learned.  This buffer is a sort of Occur mode buffer, allowing you to
;;    easily find where something was set.  It is popped to automatically
;;    if there are any conflicts found or if `sh-popup-occur-buffer' is
;;    non-nil.
;;    `sh-indent-comment' will be set if all comments follow  the same
;;    pattern;  if they don't it will be set to nil.
;;    Whether `sh-basic-offset' is set is determined by variable
;;    `sh-learn-basic-offset'.
99
;;
100 101 102 103 104 105 106
;;    Unfortunately, `sh-learn-buffer-indent' can take a long time to run
;;    (e.g. if there are large case statements).  Perhaps it does not make
;;    sense to run it on large buffers: if lots of lines have different
;;    indentation styles it will produce a lot of diagnostics in the
;;    *indent* buffer; if there is a consistent style then running
;;    `sh-learn-buffer-indent' on a small region of the buffer should
;;    suffice.
107
;;
108 109 110 111 112 113 114
;; 	Saving indentation values
;; 	-------------------------
;; After you've learned the values in a buffer, how to you remember
;; them?   Originally I had hoped that `sh-learn-buffer-indent'
;; would make this unnecessary;  simply learn the values when you visit
;; the buffer.
;; You can do this automatically like this:
115
;;   (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
116
;;
117
;; However...  `sh-learn-buffer-indent' is extremely slow,
Stefan Monnier's avatar
Stefan Monnier committed
118
;; especially on large-ish buffer.  Also, if there are conflicts the
119
;; "last one wins" which may not produce the desired setting.
120
;;
121 122
;; So...There is a minimal way of being able to save indentation values and
;; to reload them in another buffer or at another point in time.
123
;;
124 125 126 127 128 129 130
;; Use `sh-name-style' to give a name to the indentation settings of
;; 	the current buffer.
;; Use `sh-load-style' to load indentation settings for the current
;; 	buffer from a specific style.
;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
;; 	in lisp code.  You can then store it in a file and later use
;; 	`load-file' to load it.
131
;;
132 133 134 135
;; 	Indentation variables - buffer local or global?
;; 	----------------------------------------------
;; I think that often having them buffer-local makes sense,
;; especially if one is using `sh-learn-buffer-indent'.  However, if
Stefan Monnier's avatar
Stefan Monnier committed
136
;; a user sets values using customization, these changes won't appear
137
;; to work if the variables are already local!
138
;;
Stefan Monnier's avatar
Stefan Monnier committed
139
;; To get round this, there is a variable `sh-make-vars-local' and 2
140
;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
141
;;
Stefan Monnier's avatar
Stefan Monnier committed
142
;; If `sh-make-vars-local' is non-nil, then these variables become
143
;; buffer local when the mode is established.
Stefan Monnier's avatar
Stefan Monnier committed
144
;; If this is nil, then the variables are global.  At any time you
145
;; can make them local with the command `sh-make-vars-local'.
Stefan Monnier's avatar
Stefan Monnier committed
146
;; Conversely, to update with the global values you can use the
147
;; command `sh-reset-indent-vars-to-global-values'.
148
;;
Stefan Monnier's avatar
Stefan Monnier committed
149
;; This may be awkward, but the intent is to cover all cases.
150
;;
151 152 153
;; 	Awkward things, pitfalls
;; 	------------------------
;; Indentation for a sh script is complicated for a number of reasons:
154
;;
Stefan Monnier's avatar
Stefan Monnier committed
155
;; 1. You can't format by simply looking at symbols, you need to look
156 157 158 159
;;    at keywords.  [This is not the case for rc and es shells.]
;; 2. The character ")" is used both as a matched pair "(" ... ")" and
;;    as a stand-alone symbol (in a case alternative).  This makes
;;    things quite tricky!
Stefan Monnier's avatar
Stefan Monnier committed
160
;; 3. Here-documents in a script should be treated "as is", and when
161 162 163 164 165
;;    they terminate we want to revert to the indentation of the line
;;    containing the "<<" symbol.
;; 4. A line may be continued using the "\".
;; 5. The character "#" (outside a string) normally starts a comment,
;;    but it doesn't in the sequence "$#"!
166
;;
167
;; To try and address points 2 3 and 5 I used a feature that cperl mode
Stefan Monnier's avatar
Stefan Monnier committed
168
;; uses, that of a text's syntax property.  This, however, has 2
169 170 171
;; disadvantages:
;; 1. We need to scan the buffer to find which ")" symbols belong to a
;;    case alternative, to find any here documents, and handle "$#".
172
;;
173 174 175 176
;; 	Bugs
;; 	----
;; - Indenting many lines is slow.  It currently does each line
;;   independently, rather than saving state information.
177
;;
178
;; - `sh-learn-buffer-indent' is extremely slow.
179
;;
180 181 182 183 184 185 186 187 188 189
;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
;;   part of a case-pattern.  You need to add a semi-colon after "esac" to
;;   coerce sh-script into doing the right thing.
;;
;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
;;   a case-pattern.  You need to put the "in" between quotes to coerce
;;   sh-script into doing the right thing.
;;
;; - A line starting with "}>foo" is not indented like "} >foo".
;;
190 191
;; Richard Sharman <rsharman@pobox.com>  June 1999.

Richard M. Stallman's avatar
Richard M. Stallman committed
192 193 194
;;; Code:

;; page 1:	variables and settings
195 196 197 198
;; page 2:	indentation stuff
;; page 3:	mode-command and utility functions
;; page 4:	statement syntax-commands for various shells
;; page 5:	various other commands
Richard M. Stallman's avatar
Richard M. Stallman committed
199

Dave Love's avatar
Dave Love committed
200 201
(eval-when-compile
  (require 'skeleton)
Stefan Monnier's avatar
Stefan Monnier committed
202
  (require 'cl-lib)
Dave Love's avatar
Dave Love committed
203
  (require 'comint))
204 205
(require 'executable)

Leo Liu's avatar
Leo Liu committed
206 207 208 209 210
(autoload 'comint-completion-at-point "comint")
(autoload 'comint-filename-completion "comint")
(autoload 'shell-command-completion "shell")
(autoload 'shell-environment-variable-completion "shell")

211 212 213
(defvar font-lock-comment-face)
(defvar font-lock-set-defaults)
(defvar font-lock-string-face)
214 215


216
(defgroup sh nil
217
  "Shell programming utilities."
218 219 220
  :group 'languages)

(defgroup sh-script nil
221
  "Shell script mode."
222
  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
223 224 225 226 227
  :group 'sh
  :prefix "sh-")


(defcustom sh-ancestor-alist
228 229
  '((ash . sh)
    (bash . jsh)
230
    (bash2 . jsh)
231 232 233 234 235 236 237 238 239 240 241 242 243
    (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)
244 245
    (zsh . ksh88)
    (rpm . sh))
246
  "Alist showing the direct ancestor of various shells.
247 248 249 250 251
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
Chong Yidong's avatar
Chong Yidong committed
252 253
  tcsh		TENEX C Shell
    itcsh	Ian's TENEX C Shell
254 255 256
rc		Plan 9 Shell
  es		Extensible Shell
sh		Bourne Shell
Chong Yidong's avatar
Chong Yidong committed
257
  ash		Almquist Shell
258 259 260 261 262 263 264 265 266 267
  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
268 269 270
  wsh		? Shell"
  :type '(repeat (cons symbol symbol))
  :group 'sh-script)
271 272


273
(defcustom sh-alias-alist
274
  (append (if (eq system-type 'gnu/linux)
275
	     '((csh . tcsh)
276
	       (ksh . pdksh)))
277 278
	 ;; for the time being
	 '((ksh . ksh88)
279
           (bash2 . bash)
280
	   (sh5 . sh)))
281
  "Alist for transforming shell names to what they really are.
282
Use this where the name of the executable doesn't correspond to the type of
283 284 285
shell it really is."
  :type '(repeat (cons symbol symbol))
  :group 'sh-script)
286 287


288
(defcustom sh-shell-file
289
  (or
290 291
   ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
   ;; the executable extension, so comparisons with the list of
292
   ;; known shells work.
293
   (and (memq system-type '(ms-dos windows-nt))
294 295 296 297 298 299 300
	(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)
301 302
			  '("command.com" "cmd.exe" "4dos.com" "ndos.com"
			    "cmdproxy.exe")))
303 304
	      "/bin/sh"
	    (file-name-sans-extension (downcase shell)))))
305 306
   (getenv "SHELL")
   "/bin/sh")
307
  "The executable file name for the shell being programmed."
308 309
  :type 'string
  :group 'sh-script)
310 311


312
(defcustom sh-shell-arg
313
  ;; bash does not need any options when run in a shell script,
314
  '((bash)
315 316
    (csh . "-f")
    (pdksh)
317
    ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
318
    (ksh88)
319
    ;; -p means don't initialize functions from the environment.
320
    (rc . "-p")
321 322 323 324
    ;; Someone proposed -motif, but we don't want to encourage
    ;; use of a non-free widget set.
    (wksh)
    ;; -f means don't run .zshrc.
325
    (zsh . "-f"))
326
  "Single argument string for the magic number.  See `sh-feature'."
327 328 329
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (const :tag "No Arguments" nil)
			       (string :tag "Arguments")
Kenichi Handa's avatar
Kenichi Handa committed
330
			       (sexp :format "Evaluate: %v"))))
331
  :group 'sh-script)
332

333
(defcustom sh-imenu-generic-expression
334
  `((sh
335
     . ((nil
336 337
	 ;; function FOO
	 ;; function FOO()
338
         "^\\s-*function\\s-+\\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
339 340 341
         1)
	;; FOO()
	(nil
342
	 "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
343 344
	 1)
	)))
345
  "Alist of regular expressions for recognizing shell function definitions.
346 347 348 349 350 351 352
See `sh-feature' and `imenu-generic-expression'."
  :type '(alist :key-type (symbol :tag "Shell")
		:value-type (alist :key-type (choice :tag "Title"
						     string
						     (const :tag "None" nil))
				   :value-type
				   (repeat :tag "Regexp, index..." sexp)))
Dan Nicolaescu's avatar
Dan Nicolaescu committed
353
  :group 'sh-script
354
  :version "20.4")
355

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
(defun sh-current-defun-name ()
  "Find the name of function or variable at point.
For use in `add-log-current-defun-function'."
  (save-excursion
    (end-of-line)
    (when (re-search-backward
	   (concat "\\(?:"
		   ;; function FOO
		   ;; function FOO()
		   "^\\s-*function\\s-+\\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
		   "\\)\\|\\(?:"
		   ;; FOO()
		   "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
		   "\\)\\|\\(?:"
		   ;; FOO=
		   "^\\([[:alpha:]_][[:alnum:]_]*\\)="
		   "\\)")
	   nil t)
      (or (match-string-no-properties 1)
	  (match-string-no-properties 2)
	  (match-string-no-properties 3)))))

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

384 385 386
(defvar sh-shell-variables-initialized nil
  "Non-nil if `sh-shell-variables' is initialized.")

387 388
(defun sh-canonicalize-shell (shell)
  "Convert a shell name SHELL to the one we should handle it as."
389
  (if (string-match "\\.exe\\'" shell)
390
      (setq shell (substring shell 0 (match-beginning 0))))
391 392 393 394
  (or (symbolp shell)
      (setq shell (intern shell)))
  (or (cdr (assq shell sh-alias-alist))
      shell))
395

396 397
(defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
  "The shell being programmed.  This is set by \\[sh-set-shell].")
Dan Nicolaescu's avatar
Dan Nicolaescu committed
398
;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
399

400 401 402
(define-abbrev-table 'sh-mode-abbrev-table ())


403 404 405
;; I turned off this feature because it doesn't permit typing commands
;; in the usual way without help.
;;(defvar sh-abbrevs
Kenichi Handa's avatar
Kenichi Handa committed
406
;;  '((csh sh-abbrevs shell
407 408 409
;;	 "switch" 'sh-case
;;	 "getopts" 'sh-while-getopts)

Kenichi Handa's avatar
Kenichi Handa committed
410
;;    (es sh-abbrevs shell
411 412
;;	"function" 'sh-function)

Kenichi Handa's avatar
Kenichi Handa committed
413
;;    (ksh88 sh-abbrevs sh
414 415
;;	   "select" 'sh-select)

Kenichi Handa's avatar
Kenichi Handa committed
416
;;    (rc sh-abbrevs shell
417 418 419
;;	"case" 'sh-case
;;	"function" 'sh-function)

Kenichi Handa's avatar
Kenichi Handa committed
420
;;    (sh sh-abbrevs shell
421 422 423 424 425 426 427 428 429 430 431 432
;;	"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)

Kenichi Handa's avatar
Kenichi Handa committed
433
;;    (zsh sh-abbrevs ksh88
434 435
;;	 "repeat" 'sh-repeat))
;;  "Abbrev-table used in Shell-Script mode.  See `sh-feature'.
436 437
;;;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
438 439 440



Kenichi Handa's avatar
Kenichi Handa committed
441 442 443 444 445 446 447
(defun sh-mode-syntax-table (table &rest list)
  "Copy TABLE and set syntax for successive CHARs according to strings S."
  (setq table (copy-syntax-table table))
  (while list
    (modify-syntax-entry (pop list) (pop list) table))
  table)

448
(defvar sh-mode-syntax-table
Kenichi Handa's avatar
Kenichi Handa committed
449
  (sh-mode-syntax-table ()
450 451 452 453 454
	?\# "<"
	?\n ">#"
	?\" "\"\""
	?\' "\"'"
	?\` "\"`"
455 456 457 458
	;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
	;; to work fine. This is needed so that dabbrev-expand
	;; $VARNAME works.
	?$ "'"
459 460 461 462 463 464
	?! "_"
	?% "_"
	?: "_"
	?. "_"
	?^ "_"
	?~ "_"
465
	?, "_"
466
	?= "."
467 468
	?< "."
	?> ".")
469 470
  "The syntax table to use for Shell-Script mode.
This is buffer-local in every such buffer.")
471

Kenichi Handa's avatar
Kenichi Handa committed
472 473
(defvar sh-mode-syntax-table-input
  '((sh . nil))
474
  "Syntax-table used in Shell-Script mode.  See `sh-feature'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
475 476

(defvar sh-mode-map
477
  (let ((map (make-sparse-keymap))
478
	(menu-map (make-sparse-keymap)))
Richard M. Stallman's avatar
Richard M. Stallman committed
479 480 481
    (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)
482
    (define-key map "\C-c\C-t" 'sh-tmp-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
483
    (define-key map "\C-c\C-s" 'sh-select)
484 485
    (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
486 487 488 489
    (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)
490 491 492 493
    (define-key map "\C-c?" 'sh-show-indent)
    (define-key map "\C-c=" 'sh-set-indent)
    (define-key map "\C-c<" 'sh-learn-line-indent)
    (define-key map "\C-c>" 'sh-learn-buffer-indent)
494
    (define-key map "\C-c\C-\\" 'sh-backslash-region)
495

Richard M. Stallman's avatar
Richard M. Stallman committed
496 497
    (define-key map "=" 'sh-assignment)
    (define-key map "\C-c+" 'sh-add)
498 499
    (define-key map "\C-\M-x" 'sh-execute-region)
    (define-key map "\C-c\C-x" 'executable-interpret)
500 501 502
    (define-key map "\C-c\C-n" 'sh-send-line-or-region-and-step)
    (define-key map "\C-c\C-d" 'sh-cd-here)
    (define-key map "\C-c\C-z" 'sh-show-shell)
Richard M. Stallman's avatar
Richard M. Stallman committed
503

504 505
    (define-key map [remap delete-backward-char]
      'backward-delete-char-untabify)
Richard M. Stallman's avatar
Richard M. Stallman committed
506
    (define-key map "\C-c:" 'sh-set-shell)
507 508
    (define-key map [remap backward-sentence] 'sh-beginning-of-command)
    (define-key map [remap forward-sentence] 'sh-end-of-command)
509 510 511
    (define-key map [menu-bar sh-script] (cons "Sh-Script" menu-map))
    (define-key menu-map [sh-learn-buffer-indent]
      '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
512
        :help "Learn how to indent the buffer the way it currently is."))
513 514
    (define-key menu-map [sh-learn-line-indent]
      '(menu-item "Learn line indentation" sh-learn-line-indent
515
        :help "Learn how to indent a line as it currently is indented"))
516 517
    (define-key menu-map [sh-show-indent]
      '(menu-item "Show indentation" sh-show-indent
Dan Nicolaescu's avatar
Dan Nicolaescu committed
518
		  :help "Show the how the current line would be indented"))
519 520 521 522
    (define-key menu-map [sh-set-indent]
      '(menu-item "Set indentation" sh-set-indent
		  :help "Set the indentation for the current line"))

Dan Nicolaescu's avatar
Dan Nicolaescu committed
523
    (define-key menu-map [sh-pair]
524
      '(menu-item "Insert braces and quotes in pairs"
525 526 527
        electric-pair-mode
        :button (:toggle . (bound-and-true-p electric-pair-mode))
        :help "Inserting a brace or quote automatically inserts the matching pair"))
Dan Nicolaescu's avatar
Dan Nicolaescu committed
528

529 530 531 532 533 534 535
    (define-key menu-map [sh-s0] '("--"))
    ;; Insert
    (define-key menu-map [sh-function]
      '(menu-item "Function..." sh-function
		  :help "Insert a function definition"))
    (define-key menu-map [sh-add]
      '(menu-item "Addition..." sh-add
536
        :help "Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    (define-key menu-map [sh-until]
      '(menu-item "Until Loop" sh-until
		  :help "Insert an until loop"))
    (define-key menu-map [sh-repeat]
      '(menu-item "Repeat Loop" sh-repeat
		  :help "Insert a repeat loop definition"))
    (define-key menu-map [sh-while]
      '(menu-item "While Loop" sh-while
		  :help "Insert a while loop"))
    (define-key menu-map [sh-getopts]
      '(menu-item "Options Loop" sh-while-getopts
		  :help "Insert a while getopts loop."))
    (define-key menu-map [sh-indexed-loop]
      '(menu-item "Indexed Loop" sh-indexed-loop
		  :help "Insert an indexed loop from 1 to n."))
    (define-key menu-map [sh-select]
      '(menu-item "Select Statement" sh-select
		  :help "Insert a select statement "))
    (define-key menu-map [sh-if]
      '(menu-item "If Statement" sh-if
		  :help "Insert an if statement"))
    (define-key menu-map [sh-for]
      '(menu-item "For Loop" sh-for
		  :help "Insert a for loop"))
    (define-key menu-map [sh-case]
      '(menu-item "Case Statement" sh-case
		  :help "Insert a case/switch statement"))
    (define-key menu-map [sh-s1] '("--"))
    (define-key menu-map [sh-exec]
      '(menu-item "Execute region" sh-execute-region
567
        :help "Pass optional header and region to a subshell for noninteractive execution"))
568 569
    (define-key menu-map [sh-exec-interpret]
      '(menu-item "Execute script..." executable-interpret
570
        :help "Run script with user-specified args, and collect output in a buffer"))
571 572 573 574 575
    (define-key menu-map [sh-set-shell]
      '(menu-item "Set shell type..." sh-set-shell
		  :help "Set this buffer's shell to SHELL (a string)"))
    (define-key menu-map [sh-backslash-region]
      '(menu-item "Backslash region" sh-backslash-region
576
        :help "Insert, align, or delete end-of-line backslashes on the lines in the region."))
Richard M. Stallman's avatar
Richard M. Stallman committed
577 578 579
    map)
  "Keymap used in Shell-Script mode.")

580 581 582 583
(defvar sh-skeleton-pair-default-alist '((?( _ ?)) (?\))
				      (?[ ?\s _ ?\s ?]) (?\])
				      (?{ _ ?}) (?\}))
  "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
Richard M. Stallman's avatar
Richard M. Stallman committed
584

585
(defcustom sh-dynamic-complete-functions
Leo Liu's avatar
Leo Liu committed
586 587 588
  '(shell-environment-variable-completion
    shell-command-completion
    comint-filename-completion)
589
  "Functions for doing TAB dynamic completion."
590 591
  :type '(repeat function)
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
592

593
(defcustom sh-assignment-regexp
594
  `((csh . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
595
    ;; actually spaces are only supported in let/(( ... ))
596 597
    (ksh88 . ,(concat "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?"
                      "[ \t]*\\(?:[-+*/%&|~^]\\|<<\\|>>\\)?="))
598
    (bash . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?\\+?=")
599 600 601
    (rc . "\\<\\([[:alnum:]_*]+\\)[ \t]*=")
    (sh . "\\<\\([[:alnum:]_]+\\)="))
  "Regexp for the variable name and what may follow in an assignment.
602
First grouping matches the variable name.  This is upto and including the `='
603 604 605
sign.  See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice regexp
Kenichi Handa's avatar
Kenichi Handa committed
606
			       (sexp :format "Evaluate: %v"))))
607
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
608 609


610 611 612 613
(defcustom sh-indentation 4
  "The width for further indentation in Shell-Script mode."
  :type 'integer
  :group 'sh-script)
614
(put 'sh-indentation 'safe-local-variable 'integerp)
Richard M. Stallman's avatar
Richard M. Stallman committed
615

616
(defcustom sh-remember-variable-min 3
617
  "Don't remember variables less than this length for completing reads."
618 619
  :type 'integer
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
620 621


622
(defvar sh-header-marker nil
623
  "When non-nil is the end of header for prepending by \\[sh-execute-region].
624
That command is also used for setting this variable.")
625
(make-variable-buffer-local 'sh-header-marker)
626

627
(defcustom sh-beginning-of-command
628 629
  "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
  "Regexp to determine the beginning of a shell command.
630 631 632
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
633

634

635
(defcustom sh-end-of-command
636 637
  "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
  "Regexp to determine the end of a shell command.
638 639 640
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
641 642 643



644
(defcustom sh-here-document-word "EOF"
645
  "Word to delimit here documents.
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
If the first character of this string is \"-\", this is taken as
part of the redirection operator, rather than part of the
word (that is, \"<<-\" instead of \"<<\").  This is a feature
used by some shells (for example Bash) to indicate that leading
tabs inside the here document should be ignored.  In this case,
Emacs indents the initial body and end of the here document with
tabs, to the same level as the start (note that apart from this
there is no support for indentation of here documents).  This
will only work correctly if `sh-basic-offset' is a multiple of
`tab-width'.

Any quote characters or leading whitespace in the word are
removed when closing the here document."
  :type 'string
  :group 'sh-script)

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

Karl Heuer's avatar
Karl Heuer committed
663 664 665 666 667
(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
668

669 670 671
;; customized this out of sheer bravado.  not for the faint of heart.
;; but it *did* have an asterisk in the docstring!
(defcustom sh-builtins
Kenichi Handa's avatar
Kenichi Handa committed
672
  '((bash sh-append posix
673
	  "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
Kenichi Handa's avatar
Kenichi Handa committed
674 675 676
          "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
          "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
          "source" "suspend" "typeset" "unalias")
Richard M. Stallman's avatar
Richard M. Stallman committed
677

678
    ;; The next entry is only used for defining the others
Kenichi Handa's avatar
Kenichi Handa committed
679
    (bourne sh-append shell
680 681
	    "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
	    "times" "ulimit")
Richard M. Stallman's avatar
Richard M. Stallman committed
682

Kenichi Handa's avatar
Kenichi Handa committed
683
    (csh sh-append shell
684 685 686
	 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
	 "setenv" "source" "time" "unalias" "unhash")

Kenichi Handa's avatar
Kenichi Handa committed
687
    (dtksh sh-append wksh)
Richard M. Stallman's avatar
Richard M. Stallman committed
688

689 690
    (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
691

Kenichi Handa's avatar
Kenichi Handa committed
692
    (jsh sh-append sh
693
	 "bg" "fg" "jobs" "kill" "stop" "suspend")
Richard M. Stallman's avatar
Richard M. Stallman committed
694

Kenichi Handa's avatar
Kenichi Handa committed
695
    (jcsh sh-append csh
696
	  "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
697

Kenichi Handa's avatar
Kenichi Handa committed
698
    (ksh88 sh-append bourne
699 700
	   "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
	   "typeset" "unalias" "whence")
701

Kenichi Handa's avatar
Kenichi Handa committed
702
    (oash sh-append sh
703 704 705 706 707
	  "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
	  "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
	  "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
	  "wmtitle" "wrefresh")

Kenichi Handa's avatar
Kenichi Handa committed
708
    (pdksh sh-append ksh88
709 710
	   "bind")

Kenichi Handa's avatar
Kenichi Handa committed
711
    (posix sh-append sh
712 713
	   "command")

714 715
    (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
	"whatis")
716

Kenichi Handa's avatar
Kenichi Handa committed
717
    (sh sh-append bourne
718 719 720
	"hash" "test" "type")

    ;; The next entry is only used for defining the others
721 722
    (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")

Kenichi Handa's avatar
Kenichi Handa committed
723
    (wksh sh-append ksh88
724
          ;; FIXME: This looks too much like a regexp.  --Stef
725
	  "Xt[A-Z][A-Za-z]*")
726

Kenichi Handa's avatar
Kenichi Handa committed
727
    (zsh sh-append ksh88
728 729 730 731 732 733
	 "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"))
734
  "List of all shell builtins for completing read and fontification.
735
Note that on some systems not all builtins are available or some are
736 737 738
implemented as aliases.  See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (repeat string)
Kenichi Handa's avatar
Kenichi Handa committed
739
			       (sexp :format "Evaluate: %v"))))
740
  :group 'sh-script)
741 742


743

744
(defcustom sh-leading-keywords
Kenichi Handa's avatar
Kenichi Handa committed
745 746 747 748
  '((bash sh-append sh
          "time")

    (csh "else")
749 750 751 752 753

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

    (rc "else")

754
    (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
755
  "List of keywords that may be immediately followed by a builtin or keyword.
756 757
Given some confusion between keywords and builtins depending on shell and
system, the distinction here has been based on whether they influence the
758 759 760
flow of control or syntax.  See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (repeat string)
Kenichi Handa's avatar
Kenichi Handa committed
761
			       (sexp :format "Evaluate: %v"))))
762
  :group 'sh-script)
763 764


765
(defcustom sh-other-keywords
Kenichi Handa's avatar
Kenichi Handa committed
766
  '((bash sh-append bourne
767
	  "bye" "logout" "select")
768 769

    ;; The next entry is only used for defining the others
Kenichi Handa's avatar
Kenichi Handa committed
770
    (bourne sh-append sh
771
	    "function")
772

Kenichi Handa's avatar
Kenichi Handa committed
773
    (csh sh-append shell
774 775
	 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
	 "if" "logout" "onintr" "repeat" "switch" "then" "while")
776

777 778
    (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
	"return" "throw" "while")
779

Kenichi Handa's avatar
Kenichi Handa committed
780
    (ksh88 sh-append bourne
781
	   "select")
782

783 784
    (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
	"while")
785

Kenichi Handa's avatar
Kenichi Handa committed
786
    (sh sh-append shell
787 788
	"done" "esac" "fi" "for" "in" "return")

789 790
    ;; The next entry is only used for defining the others
    (shell "break" "case" "continue" "exec" "exit")
791

Kenichi Handa's avatar
Kenichi Handa committed
792
    (zsh sh-append bash
793
	 "select" "foreach"))
794
  "List of keywords not in `sh-leading-keywords'.
795 796 797
See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (repeat string)
Kenichi Handa's avatar
Kenichi Handa committed
798
			       (sexp :format "Evaluate: %v"))))
799
  :group 'sh-script)
800 801 802 803



(defvar sh-variables
Kenichi Handa's avatar
Kenichi Handa committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
  '((bash sh-append sh
	  "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
	  "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
	  "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
	  "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
	  "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
	  "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
	  "HISTIGNORE" "history_control" "HISTSIZE"
	  "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
	  "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
	  "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
	  "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
	  "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
	  "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
	  "SHLVL" "TIMEFORMAT" "TMOUT" "UID")

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

Kenichi Handa's avatar
Kenichi Handa committed
825
    (es sh-append shell
826 827 828
	"apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
	"pid" "prompt" "signals")

Kenichi Handa's avatar
Kenichi Handa committed
829
    (jcsh sh-append csh
830
	  "notify")
831

Kenichi Handa's avatar
Kenichi Handa committed
832
    (ksh88 sh-append sh
833 834 835 836
	   "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
	   "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
	   "TMOUT")

Kenichi Handa's avatar
Kenichi Handa committed
837
    (oash sh-append sh
838 839
	  "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")

Kenichi Handa's avatar
Kenichi Handa committed
840
    (rc sh-append shell
841 842 843
	"apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
	"prompt" "status")

Kenichi Handa's avatar
Kenichi Handa committed
844
    (sh sh-append shell
845 846 847 848 849 850 851 852
	"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")

Kenichi Handa's avatar
Kenichi Handa committed
853
    (tcsh sh-append csh
854 855 856 857 858 859 860 861 862 863
	  "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")

Kenichi Handa's avatar
Kenichi Handa committed
864
    (zsh sh-append ksh88
865 866 867 868 869 870 871 872 873 874
	 "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'.")

875

876
;; Font-Lock support
877