sh-script.el 125 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, 97, 1999 by Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

Karl Heuer's avatar
Karl Heuer committed
5
;; Author: Daniel Pfeiffer <occitan@esperanto.org>
6
;; Version: 2.0f
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

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 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 172 173 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
;;		Indentation
;;	 	===========
;; Indentation for rc and es modes is very limited, but for Bourne shells
;; and its derivatives it is quite customizable.
;; 
;; The following description applies to sh and derived shells (bash,
;; zsh, ...).
;; 
;; 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
;; an if statement,  and sh-indent-for-fi controls the indentation
;; of the line containing the fi.
;; 
;; 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:
;; 
;; 	+   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.
;; 
;; There are 4 commands to help set the indentation variables:
;; 
;; `sh-show-indent'
;;    This shows what variable controls the indentation of the current
;;    line and its value.
;; 
;; `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.
;; 
;; `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.
;;    
;; `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'.
;; 
;;    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.
;;   
;; 	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:
;   (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
;; 
;; However...   `sh-learn-buffer-indent' is extremely slow,
;; especially on large-ish buffer.  Also,  if there are conflicts the
;; "last one wins" which may not produce the desired setting.
;; 
;; 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.
;; 
;; 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.
;; 
;; 	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
;; a user sets values using customization,  these changes won't appear
;; to work if the variables are already local!
;; 
;; To get round this,  there is a variable `sh-make-vars-local' and 2
;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
;; 
;; If `sh-make-vars-local' is non-nil,  then these variables become
;; buffer local when the mode is established.
;; If this is nil,  then the variables are global.  At any time you
;; can make them local with the command `sh-make-vars-local'.
;; Conversely,  to update with the global values you can use the
;; command `sh-reset-indent-vars-to-global-values'.
;; 
;; This may be awkward,  but the intent is to cover all cases.
;; 
;; 	Awkward things, pitfalls
;; 	------------------------
;; Indentation for a sh script is complicated for a number of reasons:
;; 
;; 1. You can't format by simply looking at symbols,  you need to look
;;    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!
;; 3. Here-documents in a script should be treated "as is",  and when
;;    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 "$#"!
;; 
;; To try and address points 2 3 and 5 I used a feature that cperl mode
;; uses,  that of a text's syntax property.  This, however, has 2
;; disadvantages:
;; 1. We need to scan the buffer to find which ")" symbols belong to a
;;    case alternative, to find any here documents, and handle "$#".
;; 2. Setting the text property makes the buffer modified.  If the
;;    buffer is read-only buffer we have to cheat and bypass the read-only
;;    status.  This is for cases where the buffer started read-only buffer
;;    but the user issued `toggle-read-only'.
;; 
;; 	Bugs
;; 	----
;; - Here-documents are marked with text properties face and syntax
;;   table.  This serves 2 purposes: stopping indentation while inside
;;   them, and moving over them when finding the previous line to
;;   indent to.  However, if font-lock mode is active when there is
;;   any change inside the here-document font-lock clears that
;;   property.  This causes several problems: lines after the here-doc
;;   will not be re-indentation properly,  words in the here-doc region
;;   may be fontified,  and indentation may occur within the
;;   here-document.
;;   I'm not sure how to fix this, perhaps using the point-entered
;;   property.  Anyway, if you use font lock and change a
;;   here-document,  I recommend using M-x sh-rescan-buffer after the
;;   changes are made.  Similarly, when using higlight-changes-mode,
;;   changes inside a here-document may confuse shell indenting,  but again
;;   using `sh-rescan-buffer' should fix them.
;; 
;; - Indenting many lines is slow.  It currently does each line
;;   independently, rather than saving state information.
;; 
;; - `sh-learn-buffer-indent' is extremely slow.
;; 
;; Richard Sharman <rsharman@pobox.com>  June 1999.

Richard M. Stallman's avatar
Richard M. Stallman committed
203 204 205
;;; Code:

;; page 1:	variables and settings
206 207 208 209
;; 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
210

211 212
(require 'executable)

213 214


215 216 217 218 219 220 221 222 223 224 225 226
(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
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
  '((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)
242 243
    (zsh . ksh88)
    (rpm . sh))
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
  "*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
266 267 268
  wsh		? Shell"
  :type '(repeat (cons symbol symbol))
  :group 'sh-script)
269 270


271
(defcustom sh-alias-alist
272
  (nconc (if (eq system-type 'gnu/linux)
273
	     '((csh . tcsh)
274
	       (ksh . pdksh)))
275 276 277 278 279
	 ;; 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
280 281 282
shell it really is."
  :type '(repeat (cons symbol symbol))
  :group 'sh-script)
283 284


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


309
(defcustom sh-shell-arg
310
  ;; bash does not need any options when run in a shell script,
311
  '((bash)
312 313
    (csh . "-f")
    (pdksh)
314
    ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
315
    (ksh88)
316
    ;; -p means don't initialize functions from the environment.
317
    (rc . "-p")
318 319 320 321
    ;; Someone proposed -motif, but we don't want to encourage
    ;; use of a non-free widget set.
    (wksh)
    ;; -f means don't run .zshrc.
322
    (zsh . "-f"))
323 324 325 326 327 328 329 330
  "*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)
331

332 333 334 335 336 337 338 339 340 341 342
(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
343
  :group 'sh-script
344
  :version "20.4")
345

346 347 348 349 350
(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.")
351

352 353 354
(defvar sh-shell-variables-initialized nil
  "Non-nil if `sh-shell-variables' is initialized.")

355 356
(defun sh-canonicalize-shell (shell)
  "Convert a shell name SHELL to the one we should handle it as."
357
  (if (string-match "\\.exe\\'" shell)
358
      (setq shell (substring shell 0 (match-beginning 0))))
359 360 361 362
  (or (symbolp shell)
      (setq shell (intern shell)))
  (or (cdr (assq shell sh-alias-alist))
      shell))
363

364 365
(defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
  "The shell being programmed.  This is set by \\[sh-set-shell].")
366

367 368 369 370 371 372
;;; 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)
373

374 375
;;;    (es eval sh-abbrevs shell
;;;	"function" 'sh-function)
376

377 378
;;;    (ksh88 eval sh-abbrevs sh
;;;	   "select" 'sh-select)
379

380 381 382
;;;    (rc eval sh-abbrevs shell
;;;	"case" 'sh-case
;;;	"function" 'sh-function)
383

384 385 386 387 388
;;;    (sh eval sh-abbrevs shell
;;;	"case" 'sh-case
;;;	"function" 'sh-function
;;;	"until" 'sh-until
;;;	"getopts" 'sh-while-getopts)
389

390 391 392 393 394 395
;;;    ;; 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)
396

397 398 399 400 401
;;;    (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
402 403 404 405



(defvar sh-mode-syntax-table
406 407 408 409
  '((sh eval sh-mode-syntax-table ()
	?\# "<"
	?\^l ">#"
	?\n ">#"
410 411
	?\" "\"\""
	?\' "\"'"
412
	?\` "\"`"
413 414 415 416 417 418
	?! "_"
	?% "_"
	?: "_"
	?. "_"
	?^ "_"
	?~ "_")
419 420
    (csh eval identity sh)
    (rc eval identity sh))
421 422 423
  "Syntax-table used in Shell-Script mode.  See `sh-feature'.")


Richard M. Stallman's avatar
Richard M. Stallman committed
424 425

(defvar sh-mode-map
426 427
  (let ((map (make-sparse-keymap))
	(menu-map (make-sparse-keymap "Insert")))
Richard M. Stallman's avatar
Richard M. Stallman committed
428 429 430
    (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)
431
    (define-key map "\C-c\C-t" 'sh-tmp-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
432
    (define-key map "\C-c\C-s" 'sh-select)
433 434
    (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
435 436 437 438
    (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)
439 440 441 442
    (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)
443

Richard M. Stallman's avatar
Richard M. Stallman committed
444 445
    (define-key map "=" 'sh-assignment)
    (define-key map "\C-c+" 'sh-add)
446 447
    (define-key map "\C-\M-x" 'sh-execute-region)
    (define-key map "\C-c\C-x" 'executable-interpret)
448
    (define-key map "<" 'sh-maybe-here-document)
449 450 451 452 453 454
    (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)
455 456 457
    (define-key map  ")" 'sh-electric-rparen)
    (define-key map  "<" 'sh-electric-less)
    (define-key map  "#" 'sh-electric-hash)
Richard M. Stallman's avatar
Richard M. Stallman committed
458

459
    (substitute-key-definition 'complete-tag 'comint-dynamic-complete
Richard M. Stallman's avatar
Richard M. Stallman committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473
			       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))
474 475 476 477 478 479 480 481 482 483 484 485 486
    (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
487 488 489 490 491
    map)
  "Keymap used in Shell-Script mode.")



492
(defcustom sh-dynamic-complete-functions
493 494 495
  '(shell-dynamic-complete-environment-variable
    shell-dynamic-complete-command
    comint-dynamic-complete-filename)
496 497 498
  "*Functions for doing TAB dynamic completion."
  :type '(repeat function)
  :group 'sh-script)
Richard M. Stallman's avatar
Richard M. Stallman committed
499 500


501
(defcustom sh-require-final-newline
502 503 504 505 506
  '((csh . t)
    (pdksh . t)
    (rc eval . require-final-newline)
    (sh eval . require-final-newline))
  "*Value of `require-final-newline' in Shell-Script mode buffers.
507 508 509 510 511 512 513
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
514 515


516
(defcustom sh-assignment-regexp
517 518 519 520 521 522 523
  '((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 `='
524 525 526 527 528 529 530
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
531 532


533 534 535 536
(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
537 538


539 540 541 542
(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
543 544


545
(defvar sh-header-marker nil
546
  "When non-nil is the end of header for prepending by \\[sh-execute-region].
547 548 549
That command is also used for setting this variable.")


550
(defcustom sh-beginning-of-command
551
  "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
Richard M. Stallman's avatar
Richard M. Stallman committed
552
  "*Regexp to determine the beginning of a shell command.
553 554 555
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
556

557

558
(defcustom sh-end-of-command
559
  "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
Richard M. Stallman's avatar
Richard M. Stallman committed
560
  "*Regexp to determine the end of a shell command.
561 562 563
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
564 565 566



567
(defvar sh-here-document-word "EOF"
Richard M. Stallman's avatar
Richard M. Stallman committed
568 569
  "Word to delimit here documents.")

Karl Heuer's avatar
Karl Heuer committed
570 571 572 573 574
(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
575

576 577 578
;; customized this out of sheer bravado.  not for the faint of heart.
;; but it *did* have an asterisk in the docstring!
(defcustom sh-builtins
579 580 581 582
  '((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
583

584 585
    ;; The next entry is only used for defining the others
    (bourne eval sh-append shell
586 587
	    "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
	    "times" "ulimit")
Richard M. Stallman's avatar
Richard M. Stallman committed
588

589
    (csh eval sh-append shell
590 591 592 593
	 "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
594

595 596
    (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
597

598 599
    (jsh eval sh-append sh
	 "bg" "fg" "jobs" "kill" "stop" "suspend")
Richard M. Stallman's avatar
Richard M. Stallman committed
600

601 602 603 604
    (jcsh eval sh-append csh
	 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")

    (ksh88 eval sh-append bourne
605 606
	   "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
	   "typeset" "unalias" "whence")
607 608 609 610 611 612 613 614 615 616 617 618 619

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

620 621
    (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
	"whatis")
622 623 624 625 626

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

    ;; The next entry is only used for defining the others
627 628 629 630
    (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")

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

    (zsh eval sh-append ksh88
633 634 635 636 637 638
	 "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"))
639 640
  "*List of all shell builtins for completing read and fontification.
Note that on some systems not all builtins are available or some are
641 642 643 644 645 646 647
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)
648 649


650

651
(defcustom sh-leading-keywords
652 653 654 655 656 657 658 659 660 661
  '((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
662 663 664 665 666 667 668
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)
669 670


671
(defcustom sh-other-keywords
672 673
  '((bash eval sh-append bourne
	  "bye" "logout")
674 675

    ;; The next entry is only used for defining the others
676 677
    (bourne eval sh-append sh
	    "function")
678

679 680 681
    (csh eval sh-append shell
	 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
	 "if" "logout" "onintr" "repeat" "switch" "then" "while")
682

683 684
    (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
	"return" "throw" "while")
685 686

    (ksh88 eval sh-append bourne
687
	   "select")
688

689 690
    (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
	"while")
691

692 693 694
    (sh eval sh-append shell
	"done" "esac" "fi" "for" "in" "return")

695 696
    ;; The next entry is only used for defining the others
    (shell "break" "case" "continue" "exec" "exit")
697

698 699 700
    (zsh eval sh-append bash
	 "select"))
  "*List of keywords not in `sh-leading-keywords'.
701 702 703 704 705 706 707
See `sh-feature'."
  :type '(repeat (cons (symbol :tag "Shell")
		       (choice (repeat string)
			       (cons :format "Evaluate: %v"
				     (const :format "" eval)
				     sexp))))
  :group 'sh-script)
708 709 710 711 712 713 714 715 716 717 718 719 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



(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
782
	   font-lock-variable-name-face))
783 784 785

    (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
786
	  font-lock-variable-name-face))
787

788
    (rc eval identity es)
789 790

    (sh eval sh-append shell
791
	;; Variable names.
792
	'("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
793 794 795 796 797
	  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)))
798 799 800

    ;; The next entry is only used for defining the others
    (shell eval sh-append executable-font-lock-keywords
801
	   '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
802
	   '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
803 804 805 806 807
	     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)))
808
  "Default expressions to highlight in Shell Script modes.  See `sh-feature'.")
809

810
(defvar sh-font-lock-keywords-1
811
  '((sh "[ \t]in\\>"))
812
  "Subdued level highlighting for Shell Script modes.")
813 814

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

817 818
(defconst sh-font-lock-syntactic-keywords
  ;; Mark a `#' character as having punctuation syntax in a variable reference.
819 820 821 822 823 824 825 826
  ;; 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))))
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 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 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 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 960 961 962 963 964 965 966 967 968 969 970 971 972 973 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 1003 1004 1005 1006 1007 1008 1009 1010 1011 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 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 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 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 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163

(defgroup sh-indentation nil
  "Variables controlling indentation in shell scripts.

Note: customizing these variables will not affect existing buffers if
`sh-make-vars-local' is no-nil.  See the documentation for
variable `sh-make-vars-local', command `sh-make-vars-local'
and command `sh-reset-indent-vars-to-global-values'."
  :group 'sh-script)


(defcustom sh-set-shell-hook nil
  "*Hook run by `sh-set-shell'."
   :type 'hook
  :group 'sh-script)

(defcustom sh-mode-hook nil
  "*Hook run by `sh-mode'."
   :type 'hook
  :group 'sh-script)

(defcustom sh-learn-basic-offset nil
  "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.

nil mean:              never.
t means:               only if there seems to be an obvious value.
Anything else means:   whenever we have a \"good guess\" as to the value."
  :type '(choice
	  (const :tag "Never" nil)
	  (const :tag "Only if sure"  t)
	  (const :tag "If have a good guess" usually)
	  )
  :group 'sh-indentation)

(defcustom sh-popup-occur-buffer nil
  "*Controls when  `sh-learn-buffer-indent' poos the *indent* buffer.
If t it is always shown.  If nil,  it is shown only when there
are conflicts."
  :type '(choice
	  (const :tag "Only when there are conflicts." nil)
	  (const :tag "Always"  t)
	  )
  :group 'sh-indentation)

(defcustom sh-blink t
  "*If non-nil,  `sh-show-indent' shows the line indentation is relative to.
The position on the line is not necessarily meaningful.
In some cases the line will be the matching keyword, but this is not
always the case."
  :type 'boolean
  :group 'sh-indentation)

(defcustom sh-first-lines-indent 0
  "*The indentation of the first non-blank non-comment line.
Usually 0 meaning first column.
Can be set to a number,  or to nil which means leave it as is."
  :type '(choice
	  (const :tag "Leave as is"	nil)
	  (integer :tag "Column number"
		   :menu-tag "Indent to this col (0 means first col)" )
	  )
  :group 'sh-indentation)


(defcustom sh-basic-offset 4
  "*The default indentation incrementation.
This value is used for the + and - symbols in an indentation variable."
  :type 'integer
  :group 'sh-indentation)

(defcustom sh-indent-comment nil
  "*How a comment line is to be indented.
nil means leave it as it is;
t  means indent it as a normal line,  aligning it to previous non-blank
   non-comment line;
a number means align to that column,  e.g. 0 means fist column."
  :type '(choice
	  (const :tag "Leave as is." nil)
	  (const :tag "Indent as a normal line."  t)
	  (integer :menu-tag "Indent to this col (0 means first col)."
	   :tag "Indent to column number.") )
  :group 'sh-indentation)


(defvar sh-debug nil
  "Enable lots of debug messages - if function `sh-debug' is enabled.")


;; Uncomment this defun and comment the defmacro for debugging.
;; (defun sh-debug (&rest args)
;;   "For debugging:  display message ARGS if variable SH-DEBUG is non-nil."
;;   (if sh-debug
;;       (apply 'message args)))
(defmacro sh-debug (&rest args))

(setq sh-symbol-list
 '(
   (const :tag "+ "  :value +
	  :menu-tag "+   Indent right by sh-basic-offset")
   (const :tag "- "  :value -
	  :menu-tag "-   Indent left  by sh-basic-offset")
   (const :tag "++"  :value  ++
	  :menu-tag "++  Indent right twice sh-basic-offset")
   (const :tag "--"  :value --
	  :menu-tag "--  Indent left  twice sh-basic-offset")
   (const :tag "* " :value *
	  :menu-tag "*   Indent right half sh-basic-offset")
   (const :tag "/ " :value /
	  :menu-tag "/   Indent left  half sh-basic-offset")
   ))

(defcustom sh-indent-for-else 0
  "*How much to indent an else relative to an if.  Usually 0."
  :type `(choice
	  (integer :menu-tag "A number (positive=>indent right)"
		   :tag "A number")
	  (const :tag "--") ;; separator!
	  ,@ sh-symbol-list
	  )
  :group 'sh-indentation)

(setq sh-number-or-symbol-list
      (append (list '(
		      integer :menu-tag "A number (positive=>indent right)"
			      :tag "A number")
		    '(const :tag "--") ;; separator
		    )
	      sh-symbol-list))

(defcustom sh-indent-for-fi 0
  "*How much to indent a fi relative to an if.   Usually 0."
  :type `(choice ,@ sh-number-or-symbol-list )
  :group 'sh-indentation)

(defcustom sh-indent-for-done '0
  "*How much to indent a done relative to its matching stmt.   Usually 0."
  :type `(choice ,@ sh-number-or-symbol-list )
  :group 'sh-indentation)

(defcustom sh-indent-after-else '+
  "*How much to indent a statement after an else statement."
  :type `(choice ,@ sh-number-or-symbol-list )
  :group 'sh-indentation)

(defcustom sh-indent-after-if '+
  "*How much to indent a statement after an if statement.
This includes lines after else and elif statements, too, but
does not affect then else elif or fi statements themselves."
  :type `(choice ,@ sh-number-or-symbol-list )
  :group 'sh-indentation)

(defcustom sh-indent-for-then '+
  "*How much to indent an then relative to an if."
  :type `(choice ,@ sh-number-or-symbol-list )
  :group 'sh-indentation)

(defcustom sh-indent-for-do '*
  "*How much to indent a do statement.
This is relative to the statement before the do,  i.e. the
while until or for statement."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defcustom sh-indent-after-do '*
"*How much to indent a line after a do statement.
This is used when the do is the first word of the line.
This is relative to the statement before the do,  e.g. a
while for repeat or select statement."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defcustom sh-indent-after-loop-construct '+
  "*How much to indent a statement after a loop construct.

This variable is used when the keyword \"do\" is on the same line as the
loop statement (e.g.  \"until\", \"while\" or \"for\").
If the do is on a line by itself, then `sh-indent-after-do' is used instead."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)


(defcustom sh-indent-after-done 0
  "*How much to indent a statement after a \"done\" keyword.
Normally this is 0, which aligns the \"done\" to the matching
looping construct line.
Setting it non-zero allows you to have the \"do\" statement on a line
by itself and align the done under to do."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defcustom sh-indent-for-case-label '+
  "*How much to indent a case label statement.
This is relative to the line containing the case statement."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defcustom sh-indent-for-case-alt '++
  "*How much to indent statements after the case label.
This is relative to the line containing the case statement."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)


(defcustom sh-indent-for-continuation '+
  "*How much to indent for a continuation statement."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defcustom sh-indent-after-open '+
  "*How much to indent after a line with an opening parenthesis or brace.
For an open paren after a function `sh-indent-after-function' is used."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defcustom sh-indent-after-function '+
  "*How much to indent after a function line."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

;; These 2 are for the rc shell:

(defcustom sh-indent-after-switch '+
  "*How much to indent a case statement relative to the switch statement.
This is for the rc shell."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defcustom sh-indent-after-case '+
  "*How much to indent a statement relative to the case statement.
This is for the rc shell."
  :type `(choice ,@ sh-number-or-symbol-list)
  :group 'sh-indentation)

(defface sh-heredoc-face
  '((((class color)
      (background dark))
     (:foreground "yellow" :bold t))
    (((class color)
      (background light))
     (:foreground "tan" ))
    (t
     (:bold t)))
  "Face to show a here-document"
  :group 'sh-indentation)

(defface sh-st-face
  '((((class color)
      (background dark))
     (:foreground "yellow" :bold t))
    (((class color)
      (background light))
     (:foreground "tan" ))
    (t
     (:bold t)))
  "Face to show characters with special syntax properties."
  :group 'sh-indentation)


;; Internal use - not designed to be changed by the user:

;; These are used for the syntax table stuff (derived from cperl-mode).
;; Note: parse-sexp-lookup-properties must be set to t for it to work.
(defconst sh-here-doc-syntax '(15))	;; generic string
(defconst sh-st-punc '(1))
(defconst sh-special-syntax sh-st-punc)

(defun sh-mkword-regexpr (word)
  "Make a regexp which matches WORD as a word.
This specifically excludes an occurance of WORD followed by
punctuation characters like '-'."
  (concat word "\\([^-a-z0-9_]\\|$\\)"))

(defun sh-mkword-regexp (word)
  "Make a regexp which matches WORD as a word.
This specifically excludes an occurance of WORD followed by
or preceded by punctuation characters like '-'."
  (concat "\\(^\\|[^-a-z0-9_]\\)" word "\\([^-a-z0-9_]\\|$\\)"))

(setq sh-re-done (sh-mkword-regexpr "done"))


(defconst sh-kws-for-done
  '(
    (sh .  ( "while" "until" "for" ) )
    (bash . ( "while" "until" "for" "select"  ) )
    (ksh88 . ( "while" "until" "for" "select"  ) )
    (zsh .  ( "while" "until" "for" "repeat" "select" ) )
    )
  "Which keywords can match the word `done' in this shell."
  )


(defconst sh-indent-supported
  '(
    (sh . t)
    (csh . nil)
    (rc . t)
    )
  "Shell types that shell indenting can do something with."
  )

(defconst sh-electric-rparen-needed
  '(
    (sh . t))
  "Non-nil if the shell type needs an electric handling of case alternatives."
  )

(defconst sh-var-list
  '(
    sh-basic-offset sh-first-lines-indent sh-indent-after-case
    sh-indent-after-do sh-indent-after-done
    sh-indent-after-else
    sh-indent-after-if
    sh-indent-after-loop-construct
    sh-indent-after-open
    sh-indent-comment
    sh-indent-for-case-alt
    sh-indent-for-case-label
    sh-indent-for-continuation
    sh-indent-for-do
    sh-indent-for-done
    sh-indent-for-else
    sh-indent-for-fi
    sh-indent-for-then
    )
  "A list of variables used by script mode to control indentation.
This list is used when switching between buffer-local and global
values of variables,  and for the commands using indenation styles.")

(defvar sh-make-vars-local t
  "*Controls whether indentation variables are local to the buffer.
If non-nil,  indentation variables are made local initially.
If nil,  you can later make the variables local by invoking
command `sh-make-vars-local'.
The default is t because I assume that in one Emacs session one is
frequently editing existing scripts with different styles.")

1164 1165 1166 1167

;; mode-command and utility functions

;;;###autoload
1168
(put 'sh-mode 'mode-class 'special)
Erik Naggum's avatar
Erik Naggum committed
1169 1170

;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
1171 1172 1173 1174 1175 1176 1177
(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.

1178 1179 1180 1181
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
1182

1183 1184 1185
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
1186 1187 1188 1189 1190 1191

\\[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
1192 1193 1194
\\[sh-while-getopts]	 while getopts loop
\\[sh-repeat]	 repeat loop
\\[sh-select]	 select loop
Richard M. Stallman's avatar
Richard M. Stallman committed
1195 1196 1197
\\[sh-until]	 until loop
\\[sh-while]	 while loop

1198 1199 1200 1201 1202 1203 1204 1205 1206
For sh and rc shells indentation commands are:
\\[sh-show-indent]	Show the variable controlling this line's indentation.
\\[sh-set-indent]	Set then variable controlling this line's indentation.
\\[sh-learn-line-indent]	Change the indentation variable so this line
would indent to the way it currently is.
\\[sh-learn-buffer-indent]  Set the indentation variables so the
buffer indents as it currently is indendeted.


Richard M. Stallman's avatar
Richard M. Stallman committed
1207 1208 1209 1210 1211
\\[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.
1212
\\[sh-execute-region]	 Have optional header and region be executed in a subshell.
Richard M. Stallman's avatar
Richard M. Stallman committed
1213 1214 1215

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

If you generally program a shell different from your login shell you can
1219
set `sh-shell-file' accordingly.  If your shell's file name doesn't correctly
1220 1221 1222 1223
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
1224 1225 1226 1227
  (interactive)
  (kill-all-local-variables)
  (use-local-map sh-mode-map)
  (make-local-variable 'indent-line-function)
1228
  (make-local-variable 'indent-region-function)
1229
  (make-local-variable 'skeleton-end-hook)
1230 1231
  (make-local-variable 'paragraph-start)
  (make-local-variable 'paragraph-separate)
Richard M. Stallman's avatar
Richard M. Stallman committed
1232 1233 1234
  (make-local-variable 'comment-start)
  (make-local-variable 'comment-start-skip)
  (make-local-variable 'require-final-newline)
1235
  (make-local-variable 'sh-header-marker)
1236
  (make-local-variable 'sh-shell-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
1237
  (make-local-variable 'sh-shell)
1238 1239
  (make-local-variable 'skeleton-pair-alist)
  (make-local-variable 'skeleton-pair-filter)
1240 1241
  (make-local-variable 'comint-dynamic-complete-functions)
  (make-local-variable 'comint-prompt-regexp)
1242
  (make-local-variable 'font-lock-defaults)
1243
  (make-local-variable 'skeleton-filter)
1244
  (make-local-variable 'skeleton-newline-indent-rigidly)
1245 1246
  (make-local-variable 'sh-shell-variables)
  (make-local-variable 'sh-shell-variables-initialized)
1247
  (make-local-variable 'imenu-generic-expression)
1248 1249
  (make-local-variable 'sh-electric-rparen-needed-here)
  (make-local-variable 'sh-indent-supported-here)
1250
  (make-local-variable 'font-lock-unfontify-region-function)
Richard M. Stallman's avatar
Richard M. Stallman committed
1251 1252
  (setq major-mode 'sh-mode
	mode-name "Shell-script"
1253 1254
	;; not very clever, but enables wrapping skeletons around regions
	indent-region-function (lambda (b e)
1255 1256 1257 1258 1259 1260 1261 1262 1263
				 (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)))
1264
	paragraph-start (concat page-delimiter "\\|$")
1265
	paragraph-separate paragraph-start
Richard M. Stallman's avatar
Richard M. Stallman committed
1266
	comment-start "# "
1267 1268 1269
	comint-dynamic-complete-functions sh-dynamic-complete-functions
	;; we can't look if previous line ended with `\'
	comint-prompt-regexp "^[ \t]*"
1270
	font-lock-defaults
1271 1272 1273 1274 1275
	'((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))
1276 1277
	font-lock-unfontify-region-function 
		'sh-font-lock-unfontify-region-function
1278 1279
	skeleton-pair-alist '((?` _ ?`))
	skeleton-pair-filter 'sh-quoted-p
1280 1281
	skeleton-further-elements '((< '(- (min sh-indentation
						(current-column)))))
1282
	skeleton-filter 'sh-feature
1283 1284 1285
	skeleton-newline-indent-rigidly t
	sh-electric-rparen-needed-here nil
	sh-indent-supported-here nil)
1286 1287
  (make-local-variable 'parse-sexp-ignore-comments)
  (setq parse-sexp-ignore-comments t)
1288 1289 1290 1291 1292
  ;; 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))
1293
	   (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1294 1295 1296
		  (match-string 2))
		 ((and buffer-file-name
		       (string-match "\\.m?spec$" buffer-file-name))
1297
		  "rpm")))))
1298
    (if interpreter
1299
	(sh-set-shell interpreter nil nil)
1300
      (sh-set-shell sh-shell-file nil nil))
Gerd Moellmann's avatar
Gerd Moellmann committed
1301
    (run-hooks 'sh-mode-hook)))
1302
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed