*** empty log message ***
[bpt/emacs.git] / lisp / progmodes / sh-script.el
CommitLineData
ac59aed8 1;;; sh-script.el --- shell-script editing commands for Emacs
b578f267 2
67b9b71f 3;; Copyright (C) 1993, 1994, 1995, 1996, 1997, 1999, 2001, 2003, 2004, 2005
cf8b1bef 4;; Free Software Foundation, Inc.
ac59aed8 5
3e910376 6;; Author: Daniel Pfeiffer <occitan@esperanto.org>
f964dfcb 7;; Version: 2.0f
ac59aed8 8;; Maintainer: FSF
133693bc 9;; Keywords: languages, unix
ac59aed8
RS
10
11;; This file is part of GNU Emacs.
12
13;; GNU Emacs is free software; you can redistribute it and/or modify
14;; it under the terms of the GNU General Public License as published by
15;; the Free Software Foundation; either version 2, or (at your option)
16;; any later version.
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
b578f267
EN
24;; along with GNU Emacs; see the file COPYING. If not, write to the
25;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26;; Boston, MA 02111-1307, USA.
ac59aed8
RS
27
28;;; Commentary:
29
133693bc
KH
30;; Major mode for editing shell scripts. Bourne, C and rc shells as well
31;; as various derivatives are supported and easily derived from. Structured
32;; statements can be inserted with one command or abbrev. Completion is
33;; available for filenames, variables known from the script, the shell and
34;; the environment as well as commands.
ac59aed8 35
133693bc
KH
36;;; Known Bugs:
37
bfc8e97b 38;; - In Bourne the keyword `in' is not anchored to case, for, select ...
133693bc
KH
39;; - Variables in `"' strings aren't fontified because there's no way of
40;; syntactically distinguishing those from `'' strings.
e932f2d2 41
f964dfcb
GM
42;; Indentation
43;; ===========
44;; Indentation for rc and es modes is very limited, but for Bourne shells
45;; and its derivatives it is quite customizable.
035107fa 46;;
f964dfcb
GM
47;; The following description applies to sh and derived shells (bash,
48;; zsh, ...).
035107fa 49;;
f964dfcb
GM
50;; There are various customization variables which allow tailoring to
51;; a wide variety of styles. Most of these variables are named
52;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
53;; sh-indent-after-if controls the indenting of a line following
8db2b9fb 54;; an if statement, and sh-indent-for-fi controls the indentation
f964dfcb 55;; of the line containing the fi.
035107fa 56;;
f964dfcb
GM
57;; You can set each to a numeric value, but it is often more convenient
58;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
59;; By changing this one variable you can increase or decrease how much
60;; indentation there is. Valid symbols:
035107fa 61;;
f964dfcb
GM
62;; + Indent right by sh-basic-offset
63;; - Indent left by sh-basic-offset
64;; ++ Indent right twice sh-basic-offset
65;; -- Indent left twice sh-basic-offset
66;; * Indent right half sh-basic-offset
67;; / Indent left half sh-basic-offset.
035107fa 68;;
f964dfcb 69;; There are 4 commands to help set the indentation variables:
035107fa 70;;
f964dfcb
GM
71;; `sh-show-indent'
72;; This shows what variable controls the indentation of the current
73;; line and its value.
035107fa 74;;
f964dfcb
GM
75;; `sh-set-indent'
76;; This allows you to set the value of the variable controlling the
77;; current line's indentation. You can enter a number or one of a
78;; number of special symbols to denote the value of sh-basic-offset,
79;; or its negative, or half it, or twice it, etc. If you've used
80;; cc-mode this should be familiar. If you forget which symbols are
81;; valid simply press C-h at the prompt.
035107fa 82;;
f964dfcb
GM
83;; `sh-learn-line-indent'
84;; Simply make the line look the way you want it, then invoke this
85;; command. It will set the variable to the value that makes the line
86;; indent like that. If called with a prefix argument then it will set
87;; the value to one of the symbols if applicable.
035107fa 88;;
f964dfcb
GM
89;; `sh-learn-buffer-indent'
90;; This is the deluxe function! It "learns" the whole buffer (use
91;; narrowing if you want it to process only part). It outputs to a
92;; buffer *indent* any conflicts it finds, and all the variables it has
93;; learned. This buffer is a sort of Occur mode buffer, allowing you to
94;; easily find where something was set. It is popped to automatically
95;; if there are any conflicts found or if `sh-popup-occur-buffer' is
96;; non-nil.
97;; `sh-indent-comment' will be set if all comments follow the same
98;; pattern; if they don't it will be set to nil.
99;; Whether `sh-basic-offset' is set is determined by variable
100;; `sh-learn-basic-offset'.
035107fa 101;;
f964dfcb
GM
102;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
103;; (e.g. if there are large case statements). Perhaps it does not make
104;; sense to run it on large buffers: if lots of lines have different
105;; indentation styles it will produce a lot of diagnostics in the
106;; *indent* buffer; if there is a consistent style then running
107;; `sh-learn-buffer-indent' on a small region of the buffer should
108;; suffice.
035107fa 109;;
f964dfcb
GM
110;; Saving indentation values
111;; -------------------------
112;; After you've learned the values in a buffer, how to you remember
113;; them? Originally I had hoped that `sh-learn-buffer-indent'
114;; would make this unnecessary; simply learn the values when you visit
115;; the buffer.
116;; You can do this automatically like this:
6c5bcbc1 117;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
035107fa 118;;
4a9592f6 119;; However... `sh-learn-buffer-indent' is extremely slow,
8db2b9fb 120;; especially on large-ish buffer. Also, if there are conflicts the
f964dfcb 121;; "last one wins" which may not produce the desired setting.
035107fa 122;;
f964dfcb
GM
123;; So...There is a minimal way of being able to save indentation values and
124;; to reload them in another buffer or at another point in time.
035107fa 125;;
f964dfcb
GM
126;; Use `sh-name-style' to give a name to the indentation settings of
127;; the current buffer.
128;; Use `sh-load-style' to load indentation settings for the current
129;; buffer from a specific style.
130;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
131;; in lisp code. You can then store it in a file and later use
132;; `load-file' to load it.
035107fa 133;;
f964dfcb
GM
134;; Indentation variables - buffer local or global?
135;; ----------------------------------------------
136;; I think that often having them buffer-local makes sense,
137;; especially if one is using `sh-learn-buffer-indent'. However, if
8db2b9fb 138;; a user sets values using customization, these changes won't appear
f964dfcb 139;; to work if the variables are already local!
035107fa 140;;
8db2b9fb 141;; To get round this, there is a variable `sh-make-vars-local' and 2
f964dfcb 142;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
035107fa 143;;
8db2b9fb 144;; If `sh-make-vars-local' is non-nil, then these variables become
f964dfcb 145;; buffer local when the mode is established.
8db2b9fb 146;; If this is nil, then the variables are global. At any time you
f964dfcb 147;; can make them local with the command `sh-make-vars-local'.
8db2b9fb 148;; Conversely, to update with the global values you can use the
f964dfcb 149;; command `sh-reset-indent-vars-to-global-values'.
035107fa 150;;
8db2b9fb 151;; This may be awkward, but the intent is to cover all cases.
035107fa 152;;
f964dfcb
GM
153;; Awkward things, pitfalls
154;; ------------------------
155;; Indentation for a sh script is complicated for a number of reasons:
035107fa 156;;
8db2b9fb 157;; 1. You can't format by simply looking at symbols, you need to look
f964dfcb
GM
158;; at keywords. [This is not the case for rc and es shells.]
159;; 2. The character ")" is used both as a matched pair "(" ... ")" and
160;; as a stand-alone symbol (in a case alternative). This makes
161;; things quite tricky!
8db2b9fb 162;; 3. Here-documents in a script should be treated "as is", and when
f964dfcb
GM
163;; they terminate we want to revert to the indentation of the line
164;; containing the "<<" symbol.
165;; 4. A line may be continued using the "\".
166;; 5. The character "#" (outside a string) normally starts a comment,
167;; but it doesn't in the sequence "$#"!
035107fa 168;;
f964dfcb 169;; To try and address points 2 3 and 5 I used a feature that cperl mode
8db2b9fb 170;; uses, that of a text's syntax property. This, however, has 2
f964dfcb
GM
171;; disadvantages:
172;; 1. We need to scan the buffer to find which ")" symbols belong to a
173;; case alternative, to find any here documents, and handle "$#".
174;; 2. Setting the text property makes the buffer modified. If the
175;; buffer is read-only buffer we have to cheat and bypass the read-only
176;; status. This is for cases where the buffer started read-only buffer
177;; but the user issued `toggle-read-only'.
035107fa 178;;
f964dfcb
GM
179;; Bugs
180;; ----
f964dfcb
GM
181;; - Indenting many lines is slow. It currently does each line
182;; independently, rather than saving state information.
035107fa 183;;
f964dfcb 184;; - `sh-learn-buffer-indent' is extremely slow.
035107fa 185;;
f964dfcb
GM
186;; Richard Sharman <rsharman@pobox.com> June 1999.
187
ac59aed8
RS
188;;; Code:
189
190;; page 1: variables and settings
f964dfcb
GM
191;; page 2: indentation stuff
192;; page 3: mode-command and utility functions
193;; page 4: statement syntax-commands for various shells
194;; page 5: various other commands
ac59aed8 195
d2d00127
DL
196(eval-when-compile
197 (require 'skeleton)
017708e9 198 (require 'cl)
d2d00127 199 (require 'comint))
133693bc
KH
200(require 'executable)
201
2bffb7c4 202
2bffb7c4 203
cd482e05
RS
204(defgroup sh nil
205 "Shell programming utilities"
206 :group 'unix
207 :group 'languages)
208
209(defgroup sh-script nil
210 "Shell script mode"
211 :group 'sh
212 :prefix "sh-")
213
214
215(defcustom sh-ancestor-alist
133693bc
KH
216 '((ash . sh)
217 (bash . jsh)
457316e9 218 (bash2 . jsh)
133693bc
KH
219 (dtksh . ksh)
220 (es . rc)
221 (itcsh . tcsh)
222 (jcsh . csh)
223 (jsh . sh)
224 (ksh . ksh88)
225 (ksh88 . jsh)
226 (oash . sh)
227 (pdksh . ksh88)
228 (posix . sh)
229 (tcsh . csh)
230 (wksh . ksh88)
231 (wsh . sh)
547745f5
RS
232 (zsh . ksh88)
233 (rpm . sh))
133693bc
KH
234 "*Alist showing the direct ancestor of various shells.
235This is the basis for `sh-feature'. See also `sh-alias-alist'.
236By default we have the following three hierarchies:
237
238csh C Shell
239 jcsh C Shell with Job Control
3e2dd647
SM
240 tcsh Turbo C Shell
241 itcsh ? Turbo C Shell
133693bc
KH
242rc Plan 9 Shell
243 es Extensible Shell
244sh Bourne Shell
245 ash ? Shell
246 jsh Bourne Shell with Job Control
247 bash GNU Bourne Again Shell
248 ksh88 Korn Shell '88
249 ksh Korn Shell '93
250 dtksh CDE Desktop Korn Shell
251 pdksh Public Domain Korn Shell
252 wksh Window Korn Shell
253 zsh Z Shell
254 oash SCO OA (curses) Shell
255 posix IEEE 1003.2 Shell Standard
cd482e05
RS
256 wsh ? Shell"
257 :type '(repeat (cons symbol symbol))
258 :group 'sh-script)
133693bc
KH
259
260
cd482e05 261(defcustom sh-alias-alist
3ee5ce58 262 (append (if (eq system-type 'gnu/linux)
133693bc 263 '((csh . tcsh)
aafd074a 264 (ksh . pdksh)))
133693bc
KH
265 ;; for the time being
266 '((ksh . ksh88)
457316e9 267 (bash2 . bash)
133693bc
KH
268 (sh5 . sh)))
269 "*Alist for transforming shell names to what they really are.
270Use this where the name of the executable doesn't correspond to the type of
cd482e05
RS
271shell it really is."
272 :type '(repeat (cons symbol symbol))
273 :group 'sh-script)
133693bc
KH
274
275
cd482e05 276(defcustom sh-shell-file
d9de8c04 277 (or
5c449169
RS
278 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
279 ;; the executable extension, so comparisons with the list of
d9de8c04 280 ;; known shells work.
5c449169 281 (and (memq system-type '(ms-dos windows-nt))
eee86eff
EZ
282 (let* ((shell (getenv "SHELL"))
283 (shell-base
284 (and shell (file-name-nondirectory shell))))
285 ;; shell-script mode doesn't support DOS/Windows shells,
286 ;; so use the default instead.
287 (if (or (null shell)
288 (member (downcase shell-base)
ced7b4a4
RS
289 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
290 "cmdproxy.exe")))
eee86eff
EZ
291 "/bin/sh"
292 (file-name-sans-extension (downcase shell)))))
d9de8c04
RS
293 (getenv "SHELL")
294 "/bin/sh")
cd482e05
RS
295 "*The executable file name for the shell being programmed."
296 :type 'string
297 :group 'sh-script)
133693bc
KH
298
299
cd482e05 300(defcustom sh-shell-arg
8d31ff15 301 ;; bash does not need any options when run in a shell script,
8e46e267 302 '((bash)
133693bc 303 (csh . "-f")
133693bc 304 (pdksh)
8d31ff15 305 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
8e46e267 306 (ksh88)
8d31ff15 307 ;; -p means don't initialize functions from the environment.
133693bc 308 (rc . "-p")
8d31ff15
RS
309 ;; Someone proposed -motif, but we don't want to encourage
310 ;; use of a non-free widget set.
311 (wksh)
312 ;; -f means don't run .zshrc.
133693bc 313 (zsh . "-f"))
cd482e05
RS
314 "*Single argument string for the magic number. See `sh-feature'."
315 :type '(repeat (cons (symbol :tag "Shell")
316 (choice (const :tag "No Arguments" nil)
317 (string :tag "Arguments")
5d18b953 318 (sexp :format "Evaluate: %v"))))
cd482e05 319 :group 'sh-script)
133693bc 320
aa2c2426 321(defcustom sh-imenu-generic-expression
6c5bcbc1
SM
322 `((sh
323 . ((nil "^\\s-*\\(function\\s-+\\)?\\([A-Za-z_][A-Za-z_0-9]+\\)\\s-*()" 2))))
83c5d68f
DL
324 "*Alist of regular expressions for recognizing shell function definitions.
325See `sh-feature' and `imenu-generic-expression'."
326 :type '(alist :key-type (symbol :tag "Shell")
327 :value-type (alist :key-type (choice :tag "Title"
328 string
329 (const :tag "None" nil))
330 :value-type
331 (repeat :tag "Regexp, index..." sexp)))
cd32a7ba 332 :group 'sh-script
f964dfcb 333 :version "20.4")
aa2c2426 334
5a989d6e
RS
335(defvar sh-shell-variables nil
336 "Alist of shell variable names that should be included in completion.
337These are used for completion in addition to all the variables named
338in `process-environment'. Each element looks like (VAR . VAR), where
339the car and cdr are the same symbol.")
133693bc 340
5d73ac66
RS
341(defvar sh-shell-variables-initialized nil
342 "Non-nil if `sh-shell-variables' is initialized.")
343
aafd074a
KH
344(defun sh-canonicalize-shell (shell)
345 "Convert a shell name SHELL to the one we should handle it as."
842cc0e6 346 (if (string-match "\\.exe\\'" shell)
c8b88e9f 347 (setq shell (substring shell 0 (match-beginning 0))))
aafd074a
KH
348 (or (symbolp shell)
349 (setq shell (intern shell)))
350 (or (cdr (assq shell sh-alias-alist))
351 shell))
133693bc 352
aafd074a
KH
353(defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
354 "The shell being programmed. This is set by \\[sh-set-shell].")
133693bc 355
8a0d0722
RS
356(defvar sh-mode-abbrev-table nil)
357
358(define-abbrev-table 'sh-mode-abbrev-table ())
359
360
3e2dd647
SM
361;; I turned off this feature because it doesn't permit typing commands
362;; in the usual way without help.
363;;(defvar sh-abbrevs
720baa46 364;; '((csh sh-abbrevs shell
3e2dd647
SM
365;; "switch" 'sh-case
366;; "getopts" 'sh-while-getopts)
367
720baa46 368;; (es sh-abbrevs shell
3e2dd647
SM
369;; "function" 'sh-function)
370
720baa46 371;; (ksh88 sh-abbrevs sh
3e2dd647
SM
372;; "select" 'sh-select)
373
720baa46 374;; (rc sh-abbrevs shell
3e2dd647
SM
375;; "case" 'sh-case
376;; "function" 'sh-function)
377
720baa46 378;; (sh sh-abbrevs shell
3e2dd647
SM
379;; "case" 'sh-case
380;; "function" 'sh-function
381;; "until" 'sh-until
382;; "getopts" 'sh-while-getopts)
383
384;; ;; The next entry is only used for defining the others
385;; (shell "for" sh-for
386;; "loop" sh-indexed-loop
387;; "if" sh-if
388;; "tmpfile" sh-tmp-file
389;; "while" sh-while)
390
720baa46 391;; (zsh sh-abbrevs ksh88
3e2dd647
SM
392;; "repeat" 'sh-repeat))
393;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
aafd074a
KH
394;;;Due to the internal workings of abbrev tables, the shell name symbol is
395;;;actually defined as the table for the like of \\[edit-abbrevs].")
ac59aed8 396
ac59aed8
RS
397
398
1bf87f6b
RS
399(defun sh-mode-syntax-table (table &rest list)
400 "Copy TABLE and set syntax for successive CHARs according to strings S."
401 (setq table (copy-syntax-table table))
402 (while list
403 (modify-syntax-entry (pop list) (pop list) table))
404 table)
405
830144d5
RS
406(defvar sh-mode-syntax-table nil
407 "The syntax table to use for Shell-Script mode.
408This is buffer-local in every such buffer.")
409
1bf87f6b
RS
410(defvar sh-mode-default-syntax-table
411 (sh-mode-syntax-table ()
b1e851bb 412 ?\# "<"
b1e851bb
RS
413 ?\n ">#"
414 ?\" "\"\""
415 ?\' "\"'"
416 ?\` "\"`"
417 ?! "_"
418 ?% "_"
419 ?: "_"
420 ?. "_"
421 ?^ "_"
422 ?~ "_"
29653ebc 423 ?, "_"
56858354 424 ?= "."
b1e851bb
RS
425 ?< "."
426 ?> ".")
1bf87f6b 427 "Default syntax table for shell mode.")
b1e851bb 428
1bf87f6b
RS
429(defvar sh-mode-syntax-table-input
430 '((sh . nil))
b1e851bb 431 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
ac59aed8
RS
432
433(defvar sh-mode-map
bfc8e97b
KH
434 (let ((map (make-sparse-keymap))
435 (menu-map (make-sparse-keymap "Insert")))
ac59aed8
RS
436 (define-key map "\C-c(" 'sh-function)
437 (define-key map "\C-c\C-w" 'sh-while)
438 (define-key map "\C-c\C-u" 'sh-until)
133693bc 439 (define-key map "\C-c\C-t" 'sh-tmp-file)
ac59aed8 440 (define-key map "\C-c\C-s" 'sh-select)
133693bc
KH
441 (define-key map "\C-c\C-r" 'sh-repeat)
442 (define-key map "\C-c\C-o" 'sh-while-getopts)
ac59aed8
RS
443 (define-key map "\C-c\C-l" 'sh-indexed-loop)
444 (define-key map "\C-c\C-i" 'sh-if)
445 (define-key map "\C-c\C-f" 'sh-for)
446 (define-key map "\C-c\C-c" 'sh-case)
f964dfcb
GM
447 (define-key map "\C-c?" 'sh-show-indent)
448 (define-key map "\C-c=" 'sh-set-indent)
449 (define-key map "\C-c<" 'sh-learn-line-indent)
450 (define-key map "\C-c>" 'sh-learn-buffer-indent)
bdd5fa99 451 (define-key map "\C-c\C-\\" 'sh-backslash-region)
133693bc 452
ac59aed8
RS
453 (define-key map "=" 'sh-assignment)
454 (define-key map "\C-c+" 'sh-add)
fd4ea9a2
RS
455 (define-key map "\C-\M-x" 'sh-execute-region)
456 (define-key map "\C-c\C-x" 'executable-interpret)
133693bc 457 (define-key map "<" 'sh-maybe-here-document)
81ed2d75
KH
458 (define-key map "(" 'skeleton-pair-insert-maybe)
459 (define-key map "{" 'skeleton-pair-insert-maybe)
460 (define-key map "[" 'skeleton-pair-insert-maybe)
461 (define-key map "'" 'skeleton-pair-insert-maybe)
462 (define-key map "`" 'skeleton-pair-insert-maybe)
463 (define-key map "\"" 'skeleton-pair-insert-maybe)
ac59aed8 464
5d1825c6
AS
465 (define-key map [remap complete-tag] 'comint-dynamic-complete)
466 (define-key map [remap newline-and-indent] 'sh-newline-and-indent)
467 (define-key map [remap delete-backward-char]
468 'backward-delete-char-untabify)
ac59aed8 469 (define-key map "\C-c:" 'sh-set-shell)
5d1825c6
AS
470 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
471 (define-key map [remap forward-sentence] 'sh-end-of-command)
bfc8e97b
KH
472 (define-key map [menu-bar insert] (cons "Insert" menu-map))
473 (define-key menu-map [sh-while] '("While Loop" . sh-while))
474 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
475 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
476 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
477 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
6c5bcbc1
SM
478 (define-key menu-map [sh-getopts] '("Options Loop" . sh-while-getopts))
479 (define-key menu-map [sh-indexed-loop] '("Indexed Loop" . sh-indexed-loop))
bfc8e97b
KH
480 (define-key menu-map [sh-if] '("If Statement" . sh-if))
481 (define-key menu-map [sh-for] '("For Loop" . sh-for))
482 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
ac59aed8
RS
483 map)
484 "Keymap used in Shell-Script mode.")
485
486
487
cd482e05 488(defcustom sh-dynamic-complete-functions
133693bc
KH
489 '(shell-dynamic-complete-environment-variable
490 shell-dynamic-complete-command
491 comint-dynamic-complete-filename)
cd482e05
RS
492 "*Functions for doing TAB dynamic completion."
493 :type '(repeat function)
494 :group 'sh-script)
ac59aed8
RS
495
496
cd482e05 497(defcustom sh-require-final-newline
133693bc 498 '((csh . t)
61871c70 499 (pdksh . t))
133693bc 500 "*Value of `require-final-newline' in Shell-Script mode buffers.
61871c70 501\(SHELL . t) means use the value of `mode-require-final-newline' for SHELL.
cd482e05
RS
502See `sh-feature'."
503 :type '(repeat (cons (symbol :tag "Shell")
504 (choice (const :tag "require" t)
5d18b953 505 (sexp :format "Evaluate: %v"))))
cd482e05 506 :group 'sh-script)
ac59aed8
RS
507
508
c410bd65 509(defcustom sh-assignment-regexp
133693bc
KH
510 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
511 ;; actually spaces are only supported in let/(( ... ))
512 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
513 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
514 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
515 "*Regexp for the variable name and what may follow in an assignment.
516First grouping matches the variable name. This is upto and including the `='
cd482e05
RS
517sign. See `sh-feature'."
518 :type '(repeat (cons (symbol :tag "Shell")
519 (choice regexp
5d18b953 520 (sexp :format "Evaluate: %v"))))
cd482e05 521 :group 'sh-script)
ac59aed8 522
ac59aed8 523
cd482e05
RS
524(defcustom sh-indentation 4
525 "The width for further indentation in Shell-Script mode."
526 :type 'integer
527 :group 'sh-script)
ac59aed8 528
ac59aed8 529
cd482e05
RS
530(defcustom sh-remember-variable-min 3
531 "*Don't remember variables less than this length for completing reads."
532 :type 'integer
533 :group 'sh-script)
ac59aed8
RS
534
535
133693bc 536(defvar sh-header-marker nil
f964dfcb 537 "When non-nil is the end of header for prepending by \\[sh-execute-region].
133693bc
KH
538That command is also used for setting this variable.")
539
540
cd482e05 541(defcustom sh-beginning-of-command
84bfbb44 542 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
ac59aed8 543 "*Regexp to determine the beginning of a shell command.
cd482e05
RS
544The actual command starts at the beginning of the second \\(grouping\\)."
545 :type 'regexp
546 :group 'sh-script)
ac59aed8 547
133693bc 548
cd482e05 549(defcustom sh-end-of-command
84bfbb44 550 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
ac59aed8 551 "*Regexp to determine the end of a shell command.
cd482e05
RS
552The actual command ends at the end of the first \\(grouping\\)."
553 :type 'regexp
554 :group 'sh-script)
ac59aed8
RS
555
556
557
546e2f6f 558(defcustom sh-here-document-word "EOF"
18368c4a 559 "Word to delimit here documents.
546e2f6f
GM
560If the first character of this string is \"-\", this is taken as
561part of the redirection operator, rather than part of the
562word (that is, \"<<-\" instead of \"<<\"). This is a feature
563used by some shells (for example Bash) to indicate that leading
564tabs inside the here document should be ignored. In this case,
565Emacs indents the initial body and end of the here document with
566tabs, to the same level as the start (note that apart from this
567there is no support for indentation of here documents). This
568will only work correctly if `sh-basic-offset' is a multiple of
569`tab-width'.
570
571Any quote characters or leading whitespace in the word are
572removed when closing the here document."
573 :type 'string
574 :group 'sh-script)
575
ac59aed8 576
225f6185
KH
577(defvar sh-test
578 '((sh "[ ]" . 3)
579 (ksh88 "[[ ]]" . 4))
580 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
581
ac59aed8 582
cd482e05
RS
583;; customized this out of sheer bravado. not for the faint of heart.
584;; but it *did* have an asterisk in the docstring!
585(defcustom sh-builtins
1bf87f6b 586 '((bash sh-append posix
450a39ff 587 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
fa1d74c5 588 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
b8acc4ed
GM
589 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
590 "source" "suspend" "typeset" "unalias")
ac59aed8 591
133693bc 592 ;; The next entry is only used for defining the others
1bf87f6b 593 (bourne sh-append shell
84bfbb44
KH
594 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
595 "times" "ulimit")
ac59aed8 596
1bf87f6b 597 (csh sh-append shell
84bfbb44
KH
598 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
599 "setenv" "source" "time" "unalias" "unhash")
600
1bf87f6b 601 (dtksh sh-append wksh)
ac59aed8 602
84bfbb44
KH
603 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
604 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
ac59aed8 605
1bf87f6b 606 (jsh sh-append sh
133693bc 607 "bg" "fg" "jobs" "kill" "stop" "suspend")
ac59aed8 608
1bf87f6b 609 (jcsh sh-append csh
6c5bcbc1 610 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
133693bc 611
1bf87f6b 612 (ksh88 sh-append bourne
84bfbb44
KH
613 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
614 "typeset" "unalias" "whence")
133693bc 615
1bf87f6b 616 (oash sh-append sh
133693bc
KH
617 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
618 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
619 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
620 "wmtitle" "wrefresh")
621
1bf87f6b 622 (pdksh sh-append ksh88
133693bc
KH
623 "bind")
624
1bf87f6b 625 (posix sh-append sh
133693bc
KH
626 "command")
627
84bfbb44
KH
628 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
629 "whatis")
133693bc 630
1bf87f6b 631 (sh sh-append bourne
133693bc
KH
632 "hash" "test" "type")
633
634 ;; The next entry is only used for defining the others
84bfbb44
KH
635 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
636
1bf87f6b 637 (wksh sh-append ksh88
84bfbb44 638 "Xt[A-Z][A-Za-z]*")
133693bc 639
1bf87f6b 640 (zsh sh-append ksh88
84bfbb44
KH
641 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
642 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
643 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
644 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
645 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
646 "which"))
133693bc
KH
647 "*List of all shell builtins for completing read and fontification.
648Note that on some systems not all builtins are available or some are
cd482e05
RS
649implemented as aliases. See `sh-feature'."
650 :type '(repeat (cons (symbol :tag "Shell")
651 (choice (repeat string)
5d18b953 652 (sexp :format "Evaluate: %v"))))
cd482e05 653 :group 'sh-script)
133693bc
KH
654
655
84bfbb44 656
cd482e05 657(defcustom sh-leading-keywords
1bf87f6b 658 '((bash sh-append sh
fa1d74c5
GM
659 "time")
660
661 (csh "else")
84bfbb44
KH
662
663 (es "true" "unwind-protect" "whatis")
664
665 (rc "else")
666
14116f3c 667 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
84bfbb44
KH
668 "*List of keywords that may be immediately followed by a builtin or keyword.
669Given some confusion between keywords and builtins depending on shell and
670system, the distinction here has been based on whether they influence the
cd482e05
RS
671flow of control or syntax. See `sh-feature'."
672 :type '(repeat (cons (symbol :tag "Shell")
673 (choice (repeat string)
5d18b953 674 (sexp :format "Evaluate: %v"))))
cd482e05 675 :group 'sh-script)
84bfbb44
KH
676
677
cd482e05 678(defcustom sh-other-keywords
1bf87f6b 679 '((bash sh-append bourne
bc387269 680 "bye" "logout" "select")
133693bc
KH
681
682 ;; The next entry is only used for defining the others
1bf87f6b 683 (bourne sh-append sh
d9de8c04 684 "function")
133693bc 685
1bf87f6b 686 (csh sh-append shell
84bfbb44
KH
687 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
688 "if" "logout" "onintr" "repeat" "switch" "then" "while")
133693bc 689
84bfbb44
KH
690 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
691 "return" "throw" "while")
133693bc 692
1bf87f6b 693 (ksh88 sh-append bourne
84bfbb44 694 "select")
133693bc 695
84bfbb44
KH
696 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
697 "while")
133693bc 698
1bf87f6b 699 (sh sh-append shell
d9de8c04
RS
700 "done" "esac" "fi" "for" "in" "return")
701
84bfbb44
KH
702 ;; The next entry is only used for defining the others
703 (shell "break" "case" "continue" "exec" "exit")
133693bc 704
1bf87f6b 705 (zsh sh-append bash
84bfbb44
KH
706 "select"))
707 "*List of keywords not in `sh-leading-keywords'.
cd482e05
RS
708See `sh-feature'."
709 :type '(repeat (cons (symbol :tag "Shell")
710 (choice (repeat string)
5d18b953 711 (sexp :format "Evaluate: %v"))))
cd482e05 712 :group 'sh-script)
133693bc
KH
713
714
715
716(defvar sh-variables
1bf87f6b 717 '((bash sh-append sh
fa1d74c5
GM
718 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
719 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
720 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
721 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
722 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
723 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
724 "HISTIGNORE" "history_control" "HISTSIZE"
725 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
726 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
727 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
728 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
729 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
730 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
731 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
133693bc 732
1bf87f6b 733 (csh sh-append shell
133693bc
KH
734 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
735 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
736 "shell" "status" "time" "verbose")
737
1bf87f6b 738 (es sh-append shell
133693bc
KH
739 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
740 "pid" "prompt" "signals")
741
1bf87f6b 742 (jcsh sh-append csh
6c5bcbc1 743 "notify")
133693bc 744
1bf87f6b 745 (ksh88 sh-append sh
133693bc
KH
746 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
747 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
748 "TMOUT")
749
1bf87f6b 750 (oash sh-append sh
133693bc
KH
751 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
752
1bf87f6b 753 (rc sh-append shell
133693bc
KH
754 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
755 "prompt" "status")
756
1bf87f6b 757 (sh sh-append shell
133693bc
KH
758 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
759
760 ;; The next entry is only used for defining the others
761 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
762 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
763 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
764 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
765
1bf87f6b 766 (tcsh sh-append csh
133693bc
KH
767 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
768 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
769 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
770 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
771 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
772 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
773 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
774 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
775 "wordchars")
776
1bf87f6b 777 (zsh sh-append ksh88
133693bc
KH
778 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
779 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
780 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
781 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
782 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
783 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
784 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
785 "List of all shell variables available for completing read.
786See `sh-feature'.")
787
aace6150 788\f
3e2dd647 789;; Font-Lock support
aace6150
SM
790
791(defface sh-heredoc-face
ea81d57e
DN
792 '((((min-colors 88) (class color)
793 (background dark))
794 (:foreground "yellow1" :weight bold))
795 (((class color)
aace6150 796 (background dark))
1fd714a4 797 (:foreground "yellow" :weight bold))
aace6150
SM
798 (((class color)
799 (background light))
800 (:foreground "tan" ))
801 (t
1fd714a4 802 (:weight bold)))
aace6150
SM
803 "Face to show a here-document"
804 :group 'sh-indentation)
805(defvar sh-heredoc-face 'sh-heredoc-face)
133693bc 806
450a39ff
GM
807(defface sh-escaped-newline '((t :inherit font-lock-string-face))
808 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
809 :group 'sh-script
810 :version "22.1")
133693bc
KH
811
812(defvar sh-font-lock-keywords
1bf87f6b 813 '((csh sh-append shell
b8acc4ed
GM
814 ("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
815 font-lock-variable-name-face))
133693bc 816
1bf87f6b 817 (es sh-append executable-font-lock-keywords
b8acc4ed
GM
818 ("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
819 font-lock-variable-name-face))
133693bc 820
1bf87f6b 821 (rc sh-append es)
133693bc 822
1bf87f6b 823 (sh sh-append shell
4d7ce99c 824 ;; Variable names.
b8acc4ed 825 ("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
4d7ce99c
RS
826 font-lock-variable-name-face)
827 ;; Function names.
b8acc4ed
GM
828 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
829 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
d5f2a899
DP
830 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
831 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
832 1 font-lock-negation-char-face))
133693bc
KH
833
834 ;; The next entry is only used for defining the others
1bf87f6b 835 (shell sh-append executable-font-lock-keywords
3154202d 836 ;; Using font-lock-string-face here confuses sh-get-indent-info.
450a39ff 837 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
b8acc4ed
GM
838 ("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
839 ("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
547745f5 840 font-lock-variable-name-face))
1bf87f6b 841 (rpm sh-append rpm2
b8acc4ed 842 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
1bf87f6b 843 (rpm2 sh-append shell
b8acc4ed 844 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
38c979d3 845 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
133693bc 846
84bfbb44 847(defvar sh-font-lock-keywords-1
bfc8e97b 848 '((sh "[ \t]in\\>"))
38c979d3 849 "Subdued level highlighting for Shell Script modes.")
84bfbb44
KH
850
851(defvar sh-font-lock-keywords-2 ()
38c979d3 852 "Gaudy level highlighting for Shell Script modes.")
84bfbb44 853
34939e2c
SM
854;; These are used for the syntax table stuff (derived from cperl-mode).
855;; Note: parse-sexp-lookup-properties must be set to t for it to work.
856(defconst sh-st-punc (string-to-syntax "."))
bffd712e 857(defconst sh-st-symbol (string-to-syntax "_"))
34939e2c
SM
858(defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
859
67b9b71f 860(defconst sh-here-doc-open-re "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\)+\\).*\\(\n\\)")
3e2dd647
SM
861
862(defvar sh-here-doc-markers nil)
863(make-variable-buffer-local 'sh-here-doc-markers)
864(defvar sh-here-doc-re sh-here-doc-open-re)
865(make-variable-buffer-local 'sh-here-doc-re)
866
867(defun sh-font-lock-close-heredoc (bol eof indented)
868 "Determine the syntax of the \\n after an EOF.
869If non-nil INDENTED indicates that the EOF was indented."
187cd25b 870 (let* ((eof-re (if eof (regexp-quote eof) ""))
035107fa 871 ;; A rough regexp that should find the opening <<EOF back.
3e2dd647
SM
872 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
873 ;; Use \s| to cheaply check it's an open-heredoc.
035107fa 874 eof-re "['\"]?\\([ \t|;&)<>].*\\)?\\s|"))
3e2dd647 875 ;; A regexp that will find other EOFs.
035107fa 876 (ere (concat "^" (if indented "[ \t]*") eof-re "\n"))
3e2dd647
SM
877 (start (save-excursion
878 (goto-char bol)
879 (re-search-backward (concat sre "\\|" ere) nil t))))
880 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
881 ;; found a close-heredoc which makes the current close-heredoc inoperant.
882 (cond
883 ((when (and start (match-end 1)
884 (not (and indented (= (match-beginning 1) (match-end 1))))
885 (not (sh-in-comment-or-string (match-beginning 0))))
886 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
887 (save-excursion
888 (goto-char start)
889 (setq start (line-beginning-position 2))
890 (while
891 (progn
892 (re-search-forward "<<") ; Skip ourselves.
893 (and (re-search-forward sh-here-doc-open-re start 'move)
894 (goto-char (match-beginning 0))
895 (sh-in-comment-or-string (point)))))
896 ;; No <<EOF2 found after our <<.
897 (= (point) start)))
898 sh-here-doc-syntax)
899 ((not (or start (save-excursion (re-search-forward sre nil t))))
900 ;; There's no <<EOF either before or after us,
901 ;; so we should remove ourselves from font-lock's keywords.
902 (setq sh-here-doc-markers (delete eof sh-here-doc-markers))
903 (setq sh-here-doc-re
904 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
905 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))
906 nil))))
907
908(defun sh-font-lock-open-heredoc (start string)
909 "Determine the syntax of the \\n after a <<EOF.
910START is the position of <<.
911STRING is the actual word used as delimiter (f.ex. \"EOF\").
912INDENTED is non-nil if the here document's content (and the EOF mark) can
913be indented (i.e. a <<- was used rather than just <<)."
914 (unless (or (memq (char-before start) '(?< ?>))
915 (sh-in-comment-or-string start))
34939e2c
SM
916 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
917 ;; font-lock keywords to detect the end of this here document.
3e2dd647
SM
918 (let ((str (replace-regexp-in-string "['\"]" "" string)))
919 (unless (member str sh-here-doc-markers)
920 (push str sh-here-doc-markers)
921 (setq sh-here-doc-re
922 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
923 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))))
34939e2c
SM
924 sh-here-doc-syntax))
925
3e2dd647
SM
926(defun sh-font-lock-here-doc (limit)
927 "Search for a heredoc marker."
928 ;; This looks silly, but it's because `sh-here-doc-re' keeps changing.
929 (re-search-forward sh-here-doc-re limit t))
930
485219e0
SM
931(defun sh-is-quoted-p (pos)
932 (and (eq (char-before pos) ?\\)
933 (not (sh-is-quoted-p (1- pos)))))
934
34939e2c
SM
935(defun sh-font-lock-paren (start)
936 (save-excursion
937 (goto-char start)
938 ;; Skip through all patterns
939 (while
940 (progn
941 (forward-comment (- (point-max)))
942 ;; Skip through one pattern
943 (while
944 (or (/= 0 (skip-syntax-backward "w_"))
28226607 945 (/= 0 (skip-chars-backward "?[]*@/\\"))
485219e0
SM
946 (and (sh-is-quoted-p (1- (point)))
947 (goto-char (- (point) 2)))
34939e2c
SM
948 (when (memq (char-before) '(?\" ?\'))
949 (condition-case nil (progn (backward-sexp 1) t)
950 (error nil)))))
951 (forward-comment (- (point-max)))
952 (when (eq (char-before) ?|)
953 (backward-char 1) t)))
954 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
955 sh-st-punc)))
956
38c979d3 957(defconst sh-font-lock-syntactic-keywords
bffd712e
SM
958 ;; A `#' begins a comment when it is unquoted and at the beginning of a
959 ;; word. In the shell, words are separated by metacharacters.
960 ;; The list of special chars is taken from the single-unix spec
961 ;; of the shell command language (under `quoting') but with `$' removed.
962 `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol)
34939e2c 963 ;; Find HEREDOC starters and add a corresponding rule for the ender.
3e2dd647
SM
964 (sh-font-lock-here-doc
965 (2 (sh-font-lock-open-heredoc
966 (match-beginning 0) (match-string 1)) nil t)
967 (5 (sh-font-lock-close-heredoc
968 (match-beginning 0) (match-string 4)
187cd25b
SS
969 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3))))
970 nil t))
34939e2c
SM
971 ;; Distinguish the special close-paren in `case'.
972 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
f964dfcb 973
aace6150
SM
974(defun sh-font-lock-syntactic-face-function (state)
975 (if (nth 3 state)
976 (if (char-valid-p (nth 3 state))
977 font-lock-string-face
978 sh-heredoc-face)
979 font-lock-comment-face))
980
f964dfcb
GM
981(defgroup sh-indentation nil
982 "Variables controlling indentation in shell scripts.
983
984Note: customizing these variables will not affect existing buffers if
985`sh-make-vars-local' is no-nil. See the documentation for
986variable `sh-make-vars-local', command `sh-make-vars-local'
987and command `sh-reset-indent-vars-to-global-values'."
988 :group 'sh-script)
989
990
991(defcustom sh-set-shell-hook nil
992 "*Hook run by `sh-set-shell'."
6c5bcbc1 993 :type 'hook
f964dfcb
GM
994 :group 'sh-script)
995
996(defcustom sh-mode-hook nil
997 "*Hook run by `sh-mode'."
6c5bcbc1 998 :type 'hook
f964dfcb
GM
999 :group 'sh-script)
1000
1001(defcustom sh-learn-basic-offset nil
1002 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1003
1004nil mean: never.
1005t means: only if there seems to be an obvious value.
1006Anything else means: whenever we have a \"good guess\" as to the value."
1007 :type '(choice
1008 (const :tag "Never" nil)
1009 (const :tag "Only if sure" t)
8db2b9fb 1010 (const :tag "If have a good guess" usually))
f964dfcb
GM
1011 :group 'sh-indentation)
1012
1013(defcustom sh-popup-occur-buffer nil
8db2b9fb
SM
1014 "*Controls when `sh-learn-buffer-indent' pops the *indent* buffer.
1015If t it is always shown. If nil, it is shown only when there
f964dfcb
GM
1016are conflicts."
1017 :type '(choice
1018 (const :tag "Only when there are conflicts." nil)
8db2b9fb 1019 (const :tag "Always" t))
f964dfcb
GM
1020 :group 'sh-indentation)
1021
1022(defcustom sh-blink t
8db2b9fb 1023 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
f964dfcb
GM
1024The position on the line is not necessarily meaningful.
1025In some cases the line will be the matching keyword, but this is not
1026always the case."
1027 :type 'boolean
1028 :group 'sh-indentation)
1029
1030(defcustom sh-first-lines-indent 0
1031 "*The indentation of the first non-blank non-comment line.
1032Usually 0 meaning first column.
8db2b9fb 1033Can be set to a number, or to nil which means leave it as is."
f964dfcb
GM
1034 :type '(choice
1035 (const :tag "Leave as is" nil)
1036 (integer :tag "Column number"
8db2b9fb 1037 :menu-tag "Indent to this col (0 means first col)" ))
f964dfcb
GM
1038 :group 'sh-indentation)
1039
1040
1041(defcustom sh-basic-offset 4
8db2b9fb 1042 "*The default indentation increment.
f964dfcb
GM
1043This value is used for the + and - symbols in an indentation variable."
1044 :type 'integer
1045 :group 'sh-indentation)
1046
1047(defcustom sh-indent-comment nil
1048 "*How a comment line is to be indented.
1049nil means leave it as it is;
8db2b9fb 1050t means indent it as a normal line, aligning it to previous non-blank
f964dfcb 1051 non-comment line;
8db2b9fb 1052a number means align to that column, e.g. 0 means fist column."
f964dfcb
GM
1053 :type '(choice
1054 (const :tag "Leave as is." nil)
1055 (const :tag "Indent as a normal line." t)
1056 (integer :menu-tag "Indent to this col (0 means first col)."
6c5bcbc1 1057 :tag "Indent to column number.") )
f964dfcb
GM
1058 :group 'sh-indentation)
1059
1060
1061(defvar sh-debug nil
1062 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1063
1064
1065;; Uncomment this defun and comment the defmacro for debugging.
1066;; (defun sh-debug (&rest args)
1067;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1068;; (if sh-debug
1069;; (apply 'message args)))
1070(defmacro sh-debug (&rest args))
1071
d92474ed
SM
1072(defconst sh-symbol-list
1073 '((const :tag "+ " :value +
1074 :menu-tag "+ Indent right by sh-basic-offset")
1075 (const :tag "- " :value -
1076 :menu-tag "- Indent left by sh-basic-offset")
1077 (const :tag "++" :value ++
1078 :menu-tag "++ Indent right twice sh-basic-offset")
1079 (const :tag "--" :value --
1080 :menu-tag "-- Indent left twice sh-basic-offset")
1081 (const :tag "* " :value *
1082 :menu-tag "* Indent right half sh-basic-offset")
1083 (const :tag "/ " :value /
1084 :menu-tag "/ Indent left half sh-basic-offset")))
f964dfcb
GM
1085
1086(defcustom sh-indent-for-else 0
1087 "*How much to indent an else relative to an if. Usually 0."
1088 :type `(choice
1089 (integer :menu-tag "A number (positive=>indent right)"
1090 :tag "A number")
1091 (const :tag "--") ;; separator!
1092 ,@ sh-symbol-list
1093 )
1094 :group 'sh-indentation)
1095
d92474ed 1096(defconst sh-number-or-symbol-list
6c5bcbc1
SM
1097 (append '((integer :menu-tag "A number (positive=>indent right)"
1098 :tag "A number")
1099 (const :tag "--")) ; separator
d92474ed 1100 sh-symbol-list))
f964dfcb
GM
1101
1102(defcustom sh-indent-for-fi 0
4a9592f6 1103 "*How much to indent a fi relative to an if. Usually 0."
f964dfcb
GM
1104 :type `(choice ,@ sh-number-or-symbol-list )
1105 :group 'sh-indentation)
1106
1107(defcustom sh-indent-for-done '0
4a9592f6 1108 "*How much to indent a done relative to its matching stmt. Usually 0."
f964dfcb
GM
1109 :type `(choice ,@ sh-number-or-symbol-list )
1110 :group 'sh-indentation)
1111
1112(defcustom sh-indent-after-else '+
1113 "*How much to indent a statement after an else statement."
1114 :type `(choice ,@ sh-number-or-symbol-list )
1115 :group 'sh-indentation)
1116
1117(defcustom sh-indent-after-if '+
1118 "*How much to indent a statement after an if statement.
1119This includes lines after else and elif statements, too, but
1120does not affect then else elif or fi statements themselves."
1121 :type `(choice ,@ sh-number-or-symbol-list )
1122 :group 'sh-indentation)
1123
bae7df15 1124(defcustom sh-indent-for-then 0
b554bbff 1125 "*How much to indent a then relative to an if."
f964dfcb
GM
1126 :type `(choice ,@ sh-number-or-symbol-list )
1127 :group 'sh-indentation)
1128
3f0f48c0 1129(defcustom sh-indent-for-do 0
f964dfcb 1130 "*How much to indent a do statement.
8db2b9fb 1131This is relative to the statement before the do, i.e. the
f964dfcb
GM
1132while until or for statement."
1133 :type `(choice ,@ sh-number-or-symbol-list)
1134 :group 'sh-indentation)
1135
1136(defcustom sh-indent-after-do '*
6c5bcbc1 1137 "*How much to indent a line after a do statement.
f964dfcb 1138This is used when the do is the first word of the line.
8db2b9fb 1139This is relative to the statement before the do, e.g. a
f964dfcb
GM
1140while for repeat or select statement."
1141 :type `(choice ,@ sh-number-or-symbol-list)
1142 :group 'sh-indentation)
1143
1144(defcustom sh-indent-after-loop-construct '+
1145 "*How much to indent a statement after a loop construct.
1146
1147This variable is used when the keyword \"do\" is on the same line as the
1148loop statement (e.g. \"until\", \"while\" or \"for\").
1149If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1150 :type `(choice ,@ sh-number-or-symbol-list)
1151 :group 'sh-indentation)
1152
1153
1154(defcustom sh-indent-after-done 0
1155 "*How much to indent a statement after a \"done\" keyword.
1156Normally this is 0, which aligns the \"done\" to the matching
1157looping construct line.
1158Setting it non-zero allows you to have the \"do\" statement on a line
1159by itself and align the done under to do."
1160 :type `(choice ,@ sh-number-or-symbol-list)
1161 :group 'sh-indentation)
1162
1163(defcustom sh-indent-for-case-label '+
1164 "*How much to indent a case label statement.
1165This is relative to the line containing the case statement."
1166 :type `(choice ,@ sh-number-or-symbol-list)
1167 :group 'sh-indentation)
1168
1169(defcustom sh-indent-for-case-alt '++
1170 "*How much to indent statements after the case label.
1171This is relative to the line containing the case statement."
1172 :type `(choice ,@ sh-number-or-symbol-list)
1173 :group 'sh-indentation)
1174
1175
1176(defcustom sh-indent-for-continuation '+
1177 "*How much to indent for a continuation statement."
1178 :type `(choice ,@ sh-number-or-symbol-list)
1179 :group 'sh-indentation)
1180
1181(defcustom sh-indent-after-open '+
1182 "*How much to indent after a line with an opening parenthesis or brace.
1183For an open paren after a function `sh-indent-after-function' is used."
1184 :type `(choice ,@ sh-number-or-symbol-list)
1185 :group 'sh-indentation)
1186
1187(defcustom sh-indent-after-function '+
1188 "*How much to indent after a function line."
1189 :type `(choice ,@ sh-number-or-symbol-list)
1190 :group 'sh-indentation)
1191
1192;; These 2 are for the rc shell:
1193
1194(defcustom sh-indent-after-switch '+
1195 "*How much to indent a case statement relative to the switch statement.
1196This is for the rc shell."
1197 :type `(choice ,@ sh-number-or-symbol-list)
1198 :group 'sh-indentation)
1199
1200(defcustom sh-indent-after-case '+
1201 "*How much to indent a statement relative to the case statement.
1202This is for the rc shell."
1203 :type `(choice ,@ sh-number-or-symbol-list)
1204 :group 'sh-indentation)
1205
bdd5fa99
RS
1206(defcustom sh-backslash-column 48
1207 "*Column in which `sh-backslash-region' inserts backslashes."
1208 :type 'integer
1209 :group 'sh)
1210
1211(defcustom sh-backslash-align t
1212 "*If non-nil, `sh-backslash-region' will align backslashes."
1213 :type 'boolean
1214 :group 'sh)
1215
f964dfcb
GM
1216;; Internal use - not designed to be changed by the user:
1217
f964dfcb
GM
1218(defun sh-mkword-regexpr (word)
1219 "Make a regexp which matches WORD as a word.
8db2b9fb 1220This specifically excludes an occurrence of WORD followed by
f964dfcb
GM
1221punctuation characters like '-'."
1222 (concat word "\\([^-a-z0-9_]\\|$\\)"))
1223
d92474ed 1224(defconst sh-re-done (sh-mkword-regexpr "done"))
f964dfcb
GM
1225
1226
1227(defconst sh-kws-for-done
d92474ed 1228 '((sh . ( "while" "until" "for" ) )
f964dfcb
GM
1229 (bash . ( "while" "until" "for" "select" ) )
1230 (ksh88 . ( "while" "until" "for" "select" ) )
d92474ed
SM
1231 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1232 "Which keywords can match the word `done' in this shell.")
f964dfcb
GM
1233
1234
1235(defconst sh-indent-supported
d92474ed 1236 '((sh . t)
f964dfcb 1237 (csh . nil)
d92474ed
SM
1238 (rc . t))
1239 "Shell types that shell indenting can do something with.")
1240
1241(defvar sh-indent-supported-here nil
1242 "Non-nil if we support indentation for the current buffer's shell type.")
f964dfcb 1243
f964dfcb
GM
1244(defconst sh-var-list
1245 '(
1246 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1247 sh-indent-after-do sh-indent-after-done
1248 sh-indent-after-else
1249 sh-indent-after-if
1250 sh-indent-after-loop-construct
1251 sh-indent-after-open
1252 sh-indent-comment
1253 sh-indent-for-case-alt
1254 sh-indent-for-case-label
1255 sh-indent-for-continuation
1256 sh-indent-for-do
1257 sh-indent-for-done
1258 sh-indent-for-else
1259 sh-indent-for-fi
1260 sh-indent-for-then
1261 )
1262 "A list of variables used by script mode to control indentation.
1263This list is used when switching between buffer-local and global
8db2b9fb 1264values of variables, and for the commands using indentation styles.")
f964dfcb
GM
1265
1266(defvar sh-make-vars-local t
1267 "*Controls whether indentation variables are local to the buffer.
8db2b9fb
SM
1268If non-nil, indentation variables are made local initially.
1269If nil, you can later make the variables local by invoking
f964dfcb
GM
1270command `sh-make-vars-local'.
1271The default is t because I assume that in one Emacs session one is
1272frequently editing existing scripts with different styles.")
1273
133693bc
KH
1274\f
1275;; mode-command and utility functions
1276
fc8318f6 1277;;;###autoload
a7dba40b 1278(defun sh-mode ()
ac59aed8
RS
1279 "Major mode for editing shell scripts.
1280This mode works for many shells, since they all have roughly the same syntax,
1281as far as commands, arguments, variables, pipes, comments etc. are concerned.
1282Unless the file's magic number indicates the shell, your usual shell is
1283assumed. Since filenames rarely give a clue, they are not further analyzed.
1284
133693bc
KH
1285This mode adapts to the variations between shells (see `sh-set-shell') by
1286means of an inheritance based feature lookup (see `sh-feature'). This
1287mechanism applies to all variables (including skeletons) that pertain to
1288shell-specific features.
ac59aed8 1289
133693bc
KH
1290The default style of this mode is that of Rosenblatt's Korn shell book.
1291The syntax of the statements varies with the shell being used. The
1292following commands are available, based on the current shell's syntax:
ac59aed8
RS
1293
1294\\[sh-case] case statement
1295\\[sh-for] for loop
1296\\[sh-function] function definition
1297\\[sh-if] if statement
1298\\[sh-indexed-loop] indexed loop from 1 to n
133693bc
KH
1299\\[sh-while-getopts] while getopts loop
1300\\[sh-repeat] repeat loop
1301\\[sh-select] select loop
ac59aed8
RS
1302\\[sh-until] until loop
1303\\[sh-while] while loop
1304
f964dfcb
GM
1305For sh and rc shells indentation commands are:
1306\\[sh-show-indent] Show the variable controlling this line's indentation.
1307\\[sh-set-indent] Set then variable controlling this line's indentation.
1308\\[sh-learn-line-indent] Change the indentation variable so this line
1309would indent to the way it currently is.
1310\\[sh-learn-buffer-indent] Set the indentation variables so the
8db2b9fb 1311buffer indents as it currently is indented.
f964dfcb
GM
1312
1313
ac59aed8
RS
1314\\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1315\\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1316\\[sh-end-of-command] Go to end of successive commands.
1317\\[sh-beginning-of-command] Go to beginning of successive commands.
1318\\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
133693bc 1319\\[sh-execute-region] Have optional header and region be executed in a subshell.
ac59aed8 1320
ac59aed8 1321\\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
b52b132f 1322\{, (, [, ', \", `
133693bc
KH
1323 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1324
1325If you generally program a shell different from your login shell you can
aafd074a 1326set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
133693bc
KH
1327indicate what shell it is use `sh-alias-alist' to translate.
1328
1329If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1330with your script for an edit-interpret-debug cycle."
a7dba40b
RS
1331 (interactive)
1332 (kill-all-local-variables)
1333 (setq major-mode 'sh-mode
1334 mode-name "Shell-script")
1335 (use-local-map sh-mode-map)
84bfbb44 1336 (make-local-variable 'skeleton-end-hook)
133693bc
KH
1337 (make-local-variable 'paragraph-start)
1338 (make-local-variable 'paragraph-separate)
ac59aed8
RS
1339 (make-local-variable 'comment-start)
1340 (make-local-variable 'comment-start-skip)
ac59aed8 1341 (make-local-variable 'require-final-newline)
133693bc 1342 (make-local-variable 'sh-header-marker)
aafd074a 1343 (make-local-variable 'sh-shell-file)
ac59aed8 1344 (make-local-variable 'sh-shell)
81ed2d75
KH
1345 (make-local-variable 'skeleton-pair-alist)
1346 (make-local-variable 'skeleton-pair-filter)
133693bc
KH
1347 (make-local-variable 'comint-dynamic-complete-functions)
1348 (make-local-variable 'comint-prompt-regexp)
84bfbb44 1349 (make-local-variable 'font-lock-defaults)
133693bc 1350 (make-local-variable 'skeleton-filter)
cd76025c 1351 (make-local-variable 'skeleton-newline-indent-rigidly)
5d73ac66
RS
1352 (make-local-variable 'sh-shell-variables)
1353 (make-local-variable 'sh-shell-variables-initialized)
aa2c2426 1354 (make-local-variable 'imenu-generic-expression)
f964dfcb 1355 (make-local-variable 'sh-indent-supported-here)
aace6150 1356 (setq skeleton-end-hook (lambda ()
84bfbb44 1357 (or (eolp) (newline) (indent-relative)))
bfc8e97b 1358 paragraph-start (concat page-delimiter "\\|$")
133693bc 1359 paragraph-separate paragraph-start
ac59aed8 1360 comment-start "# "
133693bc
KH
1361 comint-dynamic-complete-functions sh-dynamic-complete-functions
1362 ;; we can't look if previous line ended with `\'
1363 comint-prompt-regexp "^[ \t]*"
84bfbb44 1364 font-lock-defaults
34939e2c 1365 `((sh-font-lock-keywords
38c979d3
SM
1366 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1367 nil nil
1368 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
3e2dd647 1369 (font-lock-syntactic-keywords . sh-font-lock-syntactic-keywords)
aace6150
SM
1370 (font-lock-syntactic-face-function
1371 . sh-font-lock-syntactic-face-function))
81ed2d75
KH
1372 skeleton-pair-alist '((?` _ ?`))
1373 skeleton-pair-filter 'sh-quoted-p
133693bc
KH
1374 skeleton-further-elements '((< '(- (min sh-indentation
1375 (current-column)))))
cd76025c 1376 skeleton-filter 'sh-feature
f964dfcb 1377 skeleton-newline-indent-rigidly t
f964dfcb 1378 sh-indent-supported-here nil)
6c5bcbc1 1379 (set (make-local-variable 'parse-sexp-ignore-comments) t)
e3dce9ba
RS
1380 ;; Parse or insert magic number for exec, and set all variables depending
1381 ;; on the shell thus determined.
1382 (let ((interpreter
1383 (save-excursion
1384 (goto-char (point-min))
547745f5 1385 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1448f589
KH
1386 (match-string 2))
1387 ((and buffer-file-name
1388 (string-match "\\.m?spec$" buffer-file-name))
547745f5 1389 "rpm")))))
1c532f0d
RS
1390 (sh-set-shell (or interpreter sh-shell-file) nil nil))
1391 (run-hooks 'sh-mode-hook))
aace6150 1392
133693bc 1393;;;###autoload
ac59aed8
RS
1394(defalias 'shell-script-mode 'sh-mode)
1395
1396
84bfbb44
KH
1397(defun sh-font-lock-keywords (&optional keywords)
1398 "Function to get simple fontification based on `sh-font-lock-keywords'.
1399This adds rules for comments and assignments."
1400 (sh-feature sh-font-lock-keywords
b946fbad
RS
1401 (when (stringp (sh-feature sh-assignment-regexp))
1402 (lambda (list)
1403 `((,(sh-feature sh-assignment-regexp)
1404 1 font-lock-variable-name-face)
1405 ,@keywords
1406 ,@list)))))
84bfbb44
KH
1407
1408(defun sh-font-lock-keywords-1 (&optional builtins)
1409 "Function to get better fontification including keywords."
3e2dd647
SM
1410 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1411 (regexp-opt (sh-feature sh-leading-keywords) t)
1412 "[ \t]+\\)?"
1413 (regexp-opt (append (sh-feature sh-leading-keywords)
1414 (sh-feature sh-other-keywords))
1415 t))))
84bfbb44
KH
1416 (sh-font-lock-keywords
1417 `(,@(if builtins
3e2dd647
SM
1418 `((,(concat keywords "[ \t]+\\)?"
1419 (regexp-opt (sh-feature sh-builtins) t)
1420 "\\>")
84bfbb44 1421 (2 font-lock-keyword-face nil t)
f802bd02 1422 (6 font-lock-builtin-face))
84bfbb44
KH
1423 ,@(sh-feature sh-font-lock-keywords-2)))
1424 (,(concat keywords "\\)\\>")
1425 2 font-lock-keyword-face)
1426 ,@(sh-feature sh-font-lock-keywords-1)))))
1427
1428(defun sh-font-lock-keywords-2 ()
1429 "Function to get better fontification including keywords and builtins."
1430 (sh-font-lock-keywords-1 t))
1431
ac59aed8 1432
d92474ed
SM
1433(defvar sh-regexp-for-done nil
1434 "A buffer-local regexp to match opening keyword for done.")
1435
1436(defvar sh-kw-alist nil
1437 "A buffer-local, since it is shell-type dependent, list of keywords.")
1438
1439;; ( key-word first-on-this on-prev-line )
1440;; This is used to set `sh-kw-alist' which is a list of sublists each
1441;; having 3 elements:
1442;; a keyword
8db2b9fb
SM
1443;; a rule to check when the keyword appears on "this" line
1444;; a rule to check when the keyword appears on "the previous" line
d92474ed 1445;; The keyword is usually a string and is the first word on a line.
8db2b9fb
SM
1446;; If this keyword appears on the line whose indentation is to be
1447;; calculated, the rule in element 2 is called. If this returns
1448;; non-zero, the resulting point (which may be changed by the rule)
d92474ed
SM
1449;; is used as the default indentation.
1450;; If it returned false or the keyword was not found in the table,
1451;; then the keyword from the previous line is looked up and the rule
1452;; in element 3 is called. In this case, however,
8db2b9fb 1453;; `sh-get-indent-info' does not stop but may keep going and test
d92474ed 1454;; other keywords against rules in element 3. This is because the
8db2b9fb 1455;; preceding line could have, for example, an opening "if" and an
d92474ed
SM
1456;; opening "while" keyword and we need to add the indentation offsets
1457;; for both.
1458;;
1459(defconst sh-kw
6c5bcbc1
SM
1460 '((sh
1461 ("if" nil sh-handle-prev-if)
1462 ("elif" sh-handle-this-else sh-handle-prev-else)
1463 ("else" sh-handle-this-else sh-handle-prev-else)
1464 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1465 ("then" sh-handle-this-then sh-handle-prev-then)
1466 ("(" nil sh-handle-prev-open)
1467 ("{" nil sh-handle-prev-open)
1468 ("[" nil sh-handle-prev-open)
1469 ("}" sh-handle-this-close nil)
1470 (")" sh-handle-this-close nil)
1471 ("]" sh-handle-this-close nil)
1472 ("case" nil sh-handle-prev-case)
1473 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1474 (case-label nil sh-handle-after-case-label) ;; ???
1475 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1476 ("done" sh-handle-this-done sh-handle-prev-done)
1477 ("do" sh-handle-this-do sh-handle-prev-do))
d92474ed
SM
1478
1479 ;; Note: we don't need specific stuff for bash and zsh shells;
1480 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1481 ;; these shells use.
1482 (rc
6c5bcbc1
SM
1483 ("{" nil sh-handle-prev-open)
1484 ("}" sh-handle-this-close nil)
1485 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
d92474ed
SM
1486
1487
616db04b 1488(defun sh-set-shell (shell &optional no-query-flag insert-flag)
133693bc 1489 "Set this buffer's shell to SHELL (a string).
57270c90
RS
1490When used interactively, insert the proper starting #!-line,
1491and make the visited file executable via `executable-set-magic',
1492perhaps querying depending on the value of `executable-query'.
1493
1494When this function is called noninteractively, INSERT-FLAG (the third
1495argument) controls whether to insert a #!-line and think about making
1496the visited file executable, and NO-QUERY-FLAG (the second argument)
1497controls whether to query about making the visited file executable.
1498
133693bc 1499Calls the value of `sh-set-shell-hook' if set."
54aaebc5
JB
1500 (interactive (list (completing-read (format "Shell \(default %s\): "
1501 sh-shell-file)
1502 interpreter-mode-alist
1503 (lambda (x) (eq (cdr x) 'sh-mode))
1504 nil nil nil sh-shell-file)
616db04b
RS
1505 (eq executable-query 'function)
1506 t))
842cc0e6 1507 (if (string-match "\\.exe\\'" shell)
c8b88e9f 1508 (setq shell (substring shell 0 (match-beginning 0))))
133693bc
KH
1509 (setq sh-shell (intern (file-name-nondirectory shell))
1510 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
616db04b 1511 sh-shell))
e3dce9ba
RS
1512 (if insert-flag
1513 (setq sh-shell-file
1514 (executable-set-magic shell (sh-feature sh-shell-arg)
1515 no-query-flag insert-flag)))
1bf87f6b 1516 (let ((tem (sh-feature sh-require-final-newline)))
61871c70
RS
1517 (if (eq tem t)
1518 (setq require-final-newline mode-require-final-newline)))
1bf87f6b 1519 (setq
c8005e70 1520 comment-start-skip "#+[\t ]*"
8a0d0722 1521 local-abbrev-table sh-mode-abbrev-table
133693bc 1522 mode-line-process (format "[%s]" sh-shell)
5a989d6e 1523 sh-shell-variables nil
5d73ac66 1524 sh-shell-variables-initialized nil
aa2c2426 1525 imenu-generic-expression (sh-feature sh-imenu-generic-expression)
c8b88e9f 1526 imenu-case-fold-search nil)
1bf87f6b
RS
1527 (make-local-variable 'sh-mode-syntax-table)
1528 (let ((tem (sh-feature sh-mode-syntax-table-input)))
1529 (setq sh-mode-syntax-table
1530 (if tem (apply 'sh-mode-syntax-table tem)
1531 sh-mode-default-syntax-table)))
1532 (set-syntax-table sh-mode-syntax-table)
6c5bcbc1
SM
1533 (dolist (var (sh-feature sh-variables))
1534 (sh-remember-variable var))
1535 (make-local-variable 'indent-line-function)
f964dfcb
GM
1536 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1537 (progn
1538 (message "Setting up indent for shell type %s" sh-shell)
6c5bcbc1 1539 (set (make-local-variable 'parse-sexp-lookup-properties) t)
6c5bcbc1 1540 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
f964dfcb
GM
1541 (let ((regexp (sh-feature sh-kws-for-done)))
1542 (if regexp
6c5bcbc1
SM
1543 (set (make-local-variable 'sh-regexp-for-done)
1544 (sh-mkword-regexpr (regexp-opt regexp t)))))
f964dfcb
GM
1545 (message "setting up indent stuff")
1546 ;; sh-mode has already made indent-line-function local
1547 ;; but do it in case this is called before that.
f964dfcb 1548 (setq indent-line-function 'sh-indent-line)
f964dfcb
GM
1549 (if sh-make-vars-local
1550 (sh-make-vars-local))
1551 (message "Indentation setup for shell type %s" sh-shell))
1552 (message "No indentation for this shell type.")
1553 (setq indent-line-function 'sh-basic-indent-line))
133693bc
KH
1554 (run-hooks 'sh-set-shell-hook))
1555
1556
ac59aed8 1557
1bf87f6b 1558(defun sh-feature (alist &optional function)
133693bc
KH
1559 "Index ALIST by the current shell.
1560If ALIST isn't a list where every element is a cons, it is returned as is.
1561Else indexing follows an inheritance logic which works in two ways:
1562
1563 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1564 the alist contains no value for the current shell.
1c64011b 1565 The ultimate default is always `sh'.
133693bc 1566
1bf87f6b
RS
1567 - If the value thus looked up is a list starting with `sh-append',
1568 we call the function `sh-append' with the rest of the list as
1569 arguments, and use the value. However, the next element of the
1570 list is not used as-is; instead, we look it up recursively
1571 in ALIST to allow the function called to define the value for
1572 one shell to be derived from another shell.
133693bc
KH
1573 The value thus determined is physically replaced into the alist.
1574
1575Optional FUNCTION is applied to the determined value and the result is cached
1576in ALIST."
1bf87f6b
RS
1577 (or (if (consp alist)
1578 (let ((l alist))
133693bc
KH
1579 (while (and l (consp (car l)))
1580 (setq l (cdr l)))
1bf87f6b 1581 (if l alist)))
133693bc 1582 (if function
1bf87f6b 1583 (cdr (assoc (setq function (cons sh-shell function)) alist)))
133693bc
KH
1584 (let ((sh-shell sh-shell)
1585 elt val)
1586 (while (and sh-shell
1bf87f6b 1587 (not (setq elt (assq sh-shell alist))))
133693bc 1588 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1c64011b
RS
1589 ;; If the shell is not known, treat it as sh.
1590 (unless elt
1bf87f6b 1591 (setq elt (assq 'sh alist)))
133693bc 1592 (if (and (consp (setq val (cdr elt)))
720baa46 1593 (memq (car val) '(sh-append sh-modify)))
133693bc
KH
1594 (setcdr elt
1595 (setq val
720baa46 1596 (apply (car val)
1bf87f6b 1597 (let ((sh-shell (car (cdr val))))
b8acc4ed
GM
1598 (if (assq sh-shell alist)
1599 (sh-feature alist)
1600 (eval sh-shell)))
1bf87f6b 1601 (cddr val)))))
133693bc 1602 (if function
1bf87f6b 1603 (nconc alist
133693bc
KH
1604 (list (cons function
1605 (setq sh-shell (car function)
1606 val (funcall (cdr function) val))))))
1607 val)))
1608
1609
1610
3e2dd647
SM
1611;; I commented this out because nobody calls it -- rms.
1612;;(defun sh-abbrevs (ancestor &rest list)
1613;; "Iff it isn't, define the current shell as abbrev table and fill that.
1614;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1615;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1616;;according to the remaining arguments NAMEi EXPANSIONi ...
1617;;EXPANSION may be either a string or a skeleton command."
1618;; (or (if (boundp sh-shell)
1619;; (symbol-value sh-shell))
1620;; (progn
1621;; (if (listp ancestor)
1622;; (nconc list ancestor))
1623;; (define-abbrev-table sh-shell ())
1624;; (if (vectorp ancestor)
1625;; (mapatoms (lambda (atom)
1626;; (or (eq atom 0)
1627;; (define-abbrev (symbol-value sh-shell)
1628;; (symbol-name atom)
1629;; (symbol-value atom)
1630;; (symbol-function atom))))
1631;; ancestor))
1632;; (while list
1633;; (define-abbrev (symbol-value sh-shell)
1634;; (car list)
1635;; (if (stringp (car (cdr list)))
1636;; (car (cdr list))
1637;; "")
1638;; (if (symbolp (car (cdr list)))
1639;; (car (cdr list))))
1640;; (setq list (cdr (cdr list)))))
1641;; (symbol-value sh-shell)))
133693bc
KH
1642
1643
133693bc
KH
1644(defun sh-append (ancestor &rest list)
1645 "Return list composed of first argument (a list) physically appended to rest."
1646 (nconc list ancestor))
1647
1648
1649(defun sh-modify (skeleton &rest list)
1650 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1651 (setq skeleton (copy-sequence skeleton))
1652 (while list
1653 (setcar (or (nthcdr (car list) skeleton)
1654 (error "Index %d out of bounds" (car list)))
1655 (car (cdr list)))
1656 (setq list (nthcdr 2 list)))
1657 skeleton)
ac59aed8
RS
1658
1659
f964dfcb 1660(defun sh-basic-indent-line ()
54c87e27
RS
1661 "Indent a line for Sh mode (shell script mode).
1662Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
133693bc 1663Lines containing only comments are considered empty."
ac59aed8
RS
1664 (interactive)
1665 (let ((previous (save-excursion
54c87e27
RS
1666 (while (and (progn (beginning-of-line)
1667 (not (bobp)))
b46c06de
RS
1668 (progn
1669 (forward-line -1)
1670 (back-to-indentation)
1671 (or (eolp)
1672 (eq (following-char) ?#)))))
133693bc
KH
1673 (current-column)))
1674 current)
ac59aed8
RS
1675 (save-excursion
1676 (indent-to (if (eq this-command 'newline-and-indent)
1677 previous
1678 (if (< (current-column)
133693bc
KH
1679 (setq current (progn (back-to-indentation)
1680 (current-column))))
ac59aed8 1681 (if (eolp) previous 0)
133693bc
KH
1682 (delete-region (point)
1683 (progn (beginning-of-line) (point)))
ac59aed8 1684 (if (eolp)
133693bc
KH
1685 (max previous (* (1+ (/ current sh-indentation))
1686 sh-indentation))
1687 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1688 (if (< (current-column) (current-indentation))
1689 (skip-chars-forward " \t"))))
1690
1691
1692(defun sh-execute-region (start end &optional flag)
1693 "Pass optional header and region to a subshell for noninteractive execution.
1694The working directory is that of the buffer, and only environment variables
1695are already set which is why you can mark a header within the script.
1696
1697With a positive prefix ARG, instead of sending region, define header from
1698beginning of buffer to point. With a negative prefix ARG, instead of sending
1699region, clear header."
1700 (interactive "r\nP")
1701 (if flag
1702 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1703 (point-marker)))
1704 (if sh-header-marker
1705 (save-excursion
1706 (let (buffer-undo-list)
1707 (goto-char sh-header-marker)
1708 (append-to-buffer (current-buffer) start end)
1709 (shell-command-on-region (point-min)
1710 (setq end (+ sh-header-marker
1711 (- end start)))
aafd074a 1712 sh-shell-file)
133693bc 1713 (delete-region sh-header-marker end)))
aafd074a 1714 (shell-command-on-region start end (concat sh-shell-file " -")))))
ac59aed8
RS
1715
1716
1717(defun sh-remember-variable (var)
1718 "Make VARIABLE available for future completing reads in this buffer."
1719 (or (< (length var) sh-remember-variable-min)
133693bc 1720 (getenv var)
5a989d6e 1721 (assoc var sh-shell-variables)
6c5bcbc1 1722 (push (cons var var) sh-shell-variables))
ac59aed8
RS
1723 var)
1724
1725
ac59aed8
RS
1726
1727(defun sh-quoted-p ()
1728 "Is point preceded by an odd number of backslashes?"
133693bc 1729 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
ac59aed8 1730\f
f964dfcb 1731;; Indentation stuff.
f964dfcb
GM
1732(defun sh-must-support-indent ()
1733 "*Signal an error if the shell type for this buffer is not supported.
8db2b9fb 1734Also, the buffer must be in Shell-script mode."
f964dfcb 1735 (unless sh-indent-supported-here
4aa3ba0a 1736 (error "This buffer's shell does not support indentation through Emacs")))
f964dfcb
GM
1737
1738(defun sh-make-vars-local ()
1739 "Make the indentation variables local to this buffer.
1740Normally they already are local. This command is provided in case
1741variable `sh-make-vars-local' has been set to nil.
1742
8db2b9fb 1743To revert all these variables to the global values, use
f964dfcb
GM
1744command `sh-reset-indent-vars-to-global-values'."
1745 (interactive)
f964dfcb
GM
1746 (mapcar 'make-local-variable sh-var-list)
1747 (message "Indentation variable are now local."))
1748
1749(defun sh-reset-indent-vars-to-global-values ()
8db2b9fb
SM
1750 "Reset local indentation variables to the global values.
1751Then, if variable `sh-make-vars-local' is non-nil, make them local."
f964dfcb 1752 (interactive)
f964dfcb
GM
1753 (mapcar 'kill-local-variable sh-var-list)
1754 (if sh-make-vars-local
1755 (mapcar 'make-local-variable sh-var-list)))
1756
1757
f964dfcb
GM
1758;; Theoretically these are only needed in shell and derived modes.
1759;; However, the routines which use them are only called in those modes.
1760(defconst sh-special-keywords "then\\|do")
1761
f964dfcb
GM
1762(defun sh-help-string-for-variable (var)
1763 "Construct a string for `sh-read-variable' when changing variable VAR ."
1764 (let ((msg (documentation-property var 'variable-documentation))
1765 (msg2 ""))
6c5bcbc1 1766 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
f964dfcb
GM
1767 (setq msg2
1768 (format "\n
8db2b9fb
SM
1769You can enter a number (positive to increase indentation,
1770negative to decrease indentation, zero for no change to indentation).
f964dfcb 1771
8db2b9fb 1772Or, you can enter one of the following symbols which are relative to
f964dfcb
GM
1773the value of variable `sh-basic-offset'
1774which in this buffer is currently %s.
1775
1776\t%s."
1777 sh-basic-offset
3e2dd647
SM
1778 (mapconcat (lambda (x)
1779 (nth (1- (length x)) x))
1780 sh-symbol-list "\n\t"))))
f964dfcb
GM
1781 (concat
1782 ;; The following shows the global not the local value!
1783 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1784 msg msg2)))
1785
1786(defun sh-read-variable (var)
1787 "Read a new value for indentation variable VAR."
1788 (interactive "*variable? ") ;; to test
1789 (let ((minibuffer-help-form `(sh-help-string-for-variable
1790 (quote ,var)))
1791 val)
1792 (setq val (read-from-minibuffer
6c5bcbc1
SM
1793 (format "New value for %s (press %s for help): "
1794 var (single-key-description help-char))
1795 (format "%s" (symbol-value var))
1796 nil t))
f964dfcb
GM
1797 val))
1798
1799
1800
1801(defun sh-in-comment-or-string (start)
1802 "Return non-nil if START is in a comment or string."
1803 (save-excursion
3e2dd647
SM
1804 (let ((state (syntax-ppss start)))
1805 (or (nth 3 state) (nth 4 state)))))
f964dfcb
GM
1806
1807(defun sh-goto-matching-if ()
1808 "Go to the matching if for a fi.
1809This handles nested if..fi pairs."
1810 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1811 (if found
1812 (goto-char found))))
1813
1814
1815;; Functions named sh-handle-this-XXX are called when the keyword on the
1816;; line whose indentation is being handled contain XXX;
8db2b9fb 1817;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
f964dfcb
GM
1818
1819(defun sh-handle-prev-if ()
1820 (list '(+ sh-indent-after-if)))
1821
1822(defun sh-handle-this-else ()
1823 (if (sh-goto-matching-if)
1824 ;; (list "aligned to if")
1825 (list "aligned to if" '(+ sh-indent-for-else))
1826 nil
1827 ))
1828
1829(defun sh-handle-prev-else ()
1830 (if (sh-goto-matching-if)
1831 (list '(+ sh-indent-after-if))
1832 ))
1833
1834(defun sh-handle-this-fi ()
1835 (if (sh-goto-matching-if)
1836 (list "aligned to if" '(+ sh-indent-for-fi))
1837 nil
1838 ))
1839
1840(defun sh-handle-prev-fi ()
1841 ;; Why do we have this rule? Because we must go back to the if
1842 ;; to get its indent. We may continue back from there.
1843 ;; We return nil because we don't have anything to add to result,
1844 ;; the side affect of setting align-point is all that matters.
1845 ;; we could return a comment (a string) but I can't think of a good one...
1846 (sh-goto-matching-if)
1847 nil)
1848
1849(defun sh-handle-this-then ()
1850 (let ((p (sh-goto-matching-if)))
1851 (if p
1852 (list '(+ sh-indent-for-then))
1853 )))
1854
1855(defun sh-handle-prev-then ()
1856 (let ((p (sh-goto-matching-if)))
1857 (if p
1858 (list '(+ sh-indent-after-if))
1859 )))
1860
1861(defun sh-handle-prev-open ()
1862 (save-excursion
1863 (let ((x (sh-prev-stmt)))
1864 (if (and x
1865 (progn
1866 (goto-char x)
1867 (or
1868 (looking-at "function\\b")
1869 (looking-at "\\s-*\\S-+\\s-*()")
1870 )))
1871 (list '(+ sh-indent-after-function))
1872 (list '(+ sh-indent-after-open)))
1873 )))
1874
1875(defun sh-handle-this-close ()
1876 (forward-char 1) ;; move over ")"
6c5bcbc1
SM
1877 (if (sh-safe-forward-sexp -1)
1878 (list "aligned to opening paren")))
f964dfcb
GM
1879
1880(defun sh-goto-matching-case ()
1881 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
6c5bcbc1 1882 (if found (goto-char found))))
f964dfcb
GM
1883
1884(defun sh-handle-prev-case ()
1885 ;; This is typically called when point is on same line as a case
1886 ;; we shouldn't -- and can't find prev-case
6c5bcbc1 1887 (if (looking-at ".*\\<case\\>")
f964dfcb 1888 (list '(+ sh-indent-for-case-label))
6c5bcbc1 1889 (error "We don't seem to be on a line with a case"))) ;; debug
f964dfcb
GM
1890
1891(defun sh-handle-this-esac ()
6c5bcbc1
SM
1892 (if (sh-goto-matching-case)
1893 (list "aligned to matching case")))
f964dfcb
GM
1894
1895(defun sh-handle-prev-esac ()
6c5bcbc1
SM
1896 (if (sh-goto-matching-case)
1897 (list "matching case")))
f964dfcb
GM
1898
1899(defun sh-handle-after-case-label ()
6c5bcbc1
SM
1900 (if (sh-goto-matching-case)
1901 (list '(+ sh-indent-for-case-alt))))
f964dfcb
GM
1902
1903(defun sh-handle-prev-case-alt-end ()
6c5bcbc1
SM
1904 (if (sh-goto-matching-case)
1905 (list '(+ sh-indent-for-case-label))))
f964dfcb 1906
6c5bcbc1 1907(defun sh-safe-forward-sexp (&optional arg)
f964dfcb 1908 "Try and do a `forward-sexp', but do not error.
8db2b9fb 1909Return new point if successful, nil if an error occurred."
f964dfcb
GM
1910 (condition-case nil
1911 (progn
6c5bcbc1
SM
1912 (forward-sexp (or arg 1))
1913 (point)) ;; return point if successful
f964dfcb
GM
1914 (error
1915 (sh-debug "oops!(1) %d" (point))
6c5bcbc1 1916 nil))) ;; return nil if fail
f964dfcb
GM
1917
1918(defun sh-goto-match-for-done ()
1919 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
1920 (if found
1921 (goto-char found))))
1922
1923(defun sh-handle-this-done ()
1924 (if (sh-goto-match-for-done)
6c5bcbc1 1925 (list "aligned to do stmt" '(+ sh-indent-for-done))))
f964dfcb
GM
1926
1927(defun sh-handle-prev-done ()
1928 (if (sh-goto-match-for-done)
6c5bcbc1 1929 (list "previous done")))
f964dfcb
GM
1930
1931(defun sh-handle-this-do ()
6c5bcbc1
SM
1932 (if (sh-goto-match-for-done)
1933 (list '(+ sh-indent-for-do))))
f964dfcb
GM
1934
1935(defun sh-handle-prev-do ()
6c5bcbc1
SM
1936 (cond
1937 ((save-restriction
1938 (narrow-to-region
1939 (point)
1940 (save-excursion
1941 (beginning-of-line)
1942 (point)))
1943 (sh-goto-match-for-done))
1944 (sh-debug "match for done found on THIS line")
1945 (list '(+ sh-indent-after-loop-construct)))
1946 ((sh-goto-match-for-done)
1947 (sh-debug "match for done found on PREV line")
1948 (list '(+ sh-indent-after-do)))
1949 (t
1950 (message "match for done NOT found")
1951 nil)))
f964dfcb
GM
1952
1953;; for rc:
1954(defun sh-find-prev-switch ()
1955 "Find the line for the switch keyword matching this line's case keyword."
8db2b9fb 1956 (re-search-backward "\\<switch\\>" nil t))
f964dfcb
GM
1957
1958(defun sh-handle-this-rc-case ()
1959 (if (sh-find-prev-switch)
1960 (list '(+ sh-indent-after-switch))
6c5bcbc1 1961 ;; (list '(+ sh-indent-for-case-label))
f964dfcb
GM
1962 nil))
1963
1964(defun sh-handle-prev-rc-case ()
1965 (list '(+ sh-indent-after-case)))
1966
1967(defun sh-check-rule (n thing)
1968 (let ((rule (nth n (assoc thing sh-kw-alist)))
1969 (val nil))
1970 (if rule
1971 (progn
1972 (setq val (funcall rule))
1973 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1974 n thing (point) rule val)))
1975 val))
1976
1977
1978(defun sh-get-indent-info ()
1979 "Return indent-info for this line.
1980This is a list. nil means the line is to be left as is.
1981Otherwise it contains one or more of the following sublists:
8db2b9fb 1982\(t NUMBER\) NUMBER is the base location in the buffer that indentation is
f964dfcb
GM
1983 relative to. If present, this is always the first of the
1984 sublists. The indentation of the line in question is
8db2b9fb 1985 derived from the indentation of this point, possibly
f964dfcb
GM
1986 modified by subsequent sublists.
1987\(+ VAR\)
1988\(- VAR\) Get the value of variable VAR and add to or subtract from
1989 the indentation calculated so far.
1990\(= VAR\) Get the value of variable VAR and *replace* the
8db2b9fb 1991 indentation with its value. This only occurs for
f964dfcb
GM
1992 special variables such as `sh-indent-comment'.
1993STRING This is ignored for the purposes of calculating
8db2b9fb 1994 indentation, it is printed in certain cases to help show
f964dfcb
GM
1995 what the indentation is based on."
1996 ;; See comments before `sh-kw'.
1997 (save-excursion
485219e0 1998 (let ((have-result nil)
f964dfcb 1999 this-kw
f964dfcb 2000 start
485219e0 2001 val
f964dfcb 2002 (result nil)
f964dfcb
GM
2003 (align-point nil)
2004 prev-line-end x)
2005 (beginning-of-line)
2006 ;; Note: setting result to t means we are done and will return nil.
6c5bcbc1 2007 ;;(This function never returns just t.)
f964dfcb 2008 (cond
485219e0
SM
2009 ((or (and (boundp 'font-lock-string-face) (not (bobp))
2010 (eq (get-text-property (1- (point)) 'face)
2011 font-lock-string-face))
b36581fb 2012 (eq (get-text-property (point) 'face) sh-heredoc-face))
f964dfcb
GM
2013 (setq result t)
2014 (setq have-result t))
2015 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2016 (if (bobp)
6c5bcbc1 2017 (setq result t) ;; return nil if 1st line!
f964dfcb
GM
2018 (setq result (list '(= sh-indent-comment)))
2019 ;; we still need to get previous line in case
8db2b9fb 2020 ;; sh-indent-comment is t (indent as normal)
f964dfcb
GM
2021 (setq align-point (sh-prev-line nil))
2022 (setq have-result nil)
2023 ))
6c5bcbc1 2024 ) ;; cond
035107fa 2025
f964dfcb
GM
2026 (unless have-result
2027 ;; Continuation lines are handled specially
2028 (if (sh-this-is-a-continuation)
2029 (progn
2030 ;; We assume the line being continued is already
2031 ;; properly indented...
2032 ;; (setq prev-line-end (sh-prev-line))
2033 (setq align-point (sh-prev-line nil))
2034 (setq result (list '(+ sh-indent-for-continuation)))
2035 (setq have-result t))
2036 (beginning-of-line)
2037 (skip-chars-forward " \t")
2038 (setq this-kw (sh-get-kw)))
2039
2040 ;; Handle "this" keyword: first word on the line we're
2041 ;; calculating indentation info for.
2042 (if this-kw
2043 (if (setq val (sh-check-rule 1 this-kw))
2044 (progn
2045 (setq align-point (point))
2046 (sh-debug
2047 "this - setting align-point to %d" align-point)
2048 (setq result (append result val))
2049 (setq have-result t)
2050 ;; set prev-line to continue processing remainder
8db2b9fb 2051 ;; of this line as a previous line
f964dfcb
GM
2052 (setq prev-line-end (point))
2053 ))))
2054
2055 (unless have-result
2056 (setq prev-line-end (sh-prev-line 'end)))
2057
2058 (if prev-line-end
2059 (save-excursion
2060 ;; We start off at beginning of this line.
2061 ;; Scan previous statements while this is <=
2062 ;; start of previous line.
6c5bcbc1 2063 (setq start (point)) ;; for debug only
f964dfcb
GM
2064 (goto-char prev-line-end)
2065 (setq x t)
2066 (while (and x (setq x (sh-prev-thing)))
2067 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2068 (cond
2069 ((and (equal x ")")
2070 (equal (get-text-property (1- (point)) 'syntax-table)
34939e2c 2071 sh-st-punc))
f964dfcb
GM
2072 (sh-debug "Case label) here")
2073 (setq x 'case-label)
2074 (if (setq val (sh-check-rule 2 x))
2075 (progn
2076 (setq result (append result val))
2077 (setq align-point (point))))
a3ae17d4
RS
2078 (or (bobp)
2079 (forward-char -1))
f964dfcb
GM
2080 (skip-chars-forward "[a-z0-9]*?")
2081 )
2082 ((string-match "[])}]" x)
6c5bcbc1 2083 (setq x (sh-safe-forward-sexp -1))
f964dfcb
GM
2084 (if x
2085 (progn
2086 (setq align-point (point))
2087 (setq result (append result
2088 (list "aligned to opening paren")))
2089 )))
2090 ((string-match "[[({]" x)
2091 (sh-debug "Checking special thing: %s" x)
2092 (if (setq val (sh-check-rule 2 x))
2093 (setq result (append result val)))
2094 (forward-char -1)
2095 (setq align-point (point)))
2096 ((string-match "[\"'`]" x)
2097 (sh-debug "Skipping back for %s" x)
2098 ;; this was oops-2
6c5bcbc1 2099 (setq x (sh-safe-forward-sexp -1)))
f964dfcb
GM
2100 ((stringp x)
2101 (sh-debug "Checking string %s at %s" x (point))
2102 (if (setq val (sh-check-rule 2 x))
2103 ;; (or (eq t (car val))
2104 ;; (eq t (car (car val))))
2105 (setq result (append result val)))
2106 ;; not sure about this test Wed Jan 27 23:48:35 1999
2107 (setq align-point (point))
2108 (unless (bolp)
2109 (forward-char -1)))
2110 (t
2111 (error "Don't know what to do with %s" x))
2112 )
6c5bcbc1 2113 ) ;; while
f964dfcb
GM
2114 (sh-debug "result is %s" result)
2115 )
2116 (sh-debug "No prev line!")
2117 (sh-debug "result: %s align-point: %s" result align-point)
2118 )
035107fa 2119
f964dfcb
GM
2120 (if align-point
2121 ;; was: (setq result (append result (list (list t align-point))))
2122 (setq result (append (list (list t align-point)) result))
2123 )
2124 (sh-debug "result is now: %s" result)
035107fa 2125
f964dfcb
GM
2126 (or result
2127 (if prev-line-end
2128 (setq result (list (list t prev-line-end)))
2129 (setq result (list (list '= 'sh-first-lines-indent)))
2130 ))
035107fa 2131
f964dfcb
GM
2132 (if (eq result t)
2133 (setq result nil))
2134 (sh-debug "result is: %s" result)
2135 result
6c5bcbc1 2136 ) ;; let
f964dfcb
GM
2137 ))
2138
2139
2140(defun sh-get-indent-var-for-line (&optional info)
2141 "Return the variable controlling indentation for this line.
2142If there is not [just] one such variable, return a string
2143indicating the problem.
2144If INFO is supplied it is used, else it is calculated."
2145 (let ((var nil)
2146 (result nil)
2147 (reason nil)
2148 sym elt)
2149 (or info
2150 (setq info (sh-get-indent-info)))
2151 (if (null info)
2152 (setq result "this line to be left as is")
2153 (while (and info (null result))
2154 (setq elt (car info))
2155 (cond
2156 ((stringp elt)
2157 (setq reason elt)
2158 )
2159 ((not (listp elt))
2160 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2161 ;; so it is a list
2162 ((eq t (car elt))
6c5bcbc1 2163 ) ;; nothing
f964dfcb
GM
2164 ((symbolp (setq sym (nth 1 elt)))
2165 ;; A bit of a kludge - when we see the sh-indent-comment
2166 ;; ignore other variables. Otherwise it is tricky to
2167 ;; "learn" the comment indentation.
2168 (if (eq var 'sh-indent-comment)
2169 (setq result var)
2170 (if var
2171 (setq result
2172 "this line is controlled by more than 1 variable.")
2173 (setq var sym))))
2174 (t
2175 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2176 (setq info (cdr info))
2177 ))
2178 (or result
2179 (setq result var))
2180 (or result
2181 (setq result reason))
2182 (if (null result)
2183 ;; e.g. just had (t POS)
2184 (setq result "line has default indentation"))
2185 result))
2186
2187
2188
2189;; Finding the previous line isn't trivial.
2190;; We must *always* go back one more and see if that is a continuation
8db2b9fb 2191;; line -- it is the PREVIOUS line which is continued, not the one
f964dfcb
GM
2192;; we are going to!
2193;; Also, we want to treat a whole "here document" as one big line,
2194;; because we may want to a align to the beginning of it.
2195;;
2196;; What we do:
6c5bcbc1 2197;; - go back to previous non-empty line
8db2b9fb 2198;; - if this is in a here-document, go to the beginning of it
6c5bcbc1 2199;; - while previous line is continued, go back one line
f964dfcb
GM
2200(defun sh-prev-line (&optional end)
2201 "Back to end of previous non-comment non-empty line.
8db2b9fb 2202Go to beginning of logical line unless END is non-nil, in which case
f964dfcb 2203we go to the end of the previous line and do not check for continuations."
6c5bcbc1
SM
2204 (save-excursion
2205 (beginning-of-line)
2206 (forward-comment (- (point-max)))
2207 (unless end (beginning-of-line))
2208 (when (and (not (bobp))
34939e2c 2209 (equal (get-text-property (1- (point)) 'face)
b36581fb 2210 sh-heredoc-face))
34939e2c 2211 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
6c5bcbc1
SM
2212 (when p1
2213 (goto-char p1)
34939e2c
SM
2214 (if end
2215 (end-of-line)
2216 (beginning-of-line)))))
6c5bcbc1
SM
2217 (unless end
2218 ;; we must check previous lines to see if they are continuation lines
2219 ;; if so, we must return position of first of them
2220 (while (and (sh-this-is-a-continuation)
2221 (>= 0 (forward-line -1))))
f964dfcb 2222 (beginning-of-line)
6c5bcbc1
SM
2223 (skip-chars-forward " \t"))
2224 (point)))
f964dfcb
GM
2225
2226
2227(defun sh-prev-stmt ()
2228 "Return the address of the previous stmt or nil."
2229 ;; This is used when we are trying to find a matching keyword.
8db2b9fb 2230 ;; Searching backward for the keyword would certainly be quicker, but
f964dfcb
GM
2231 ;; it is hard to remove "false matches" -- such as if the keyword
2232 ;; appears in a string or quote. This way is slower, but (I think) safer.
2233 (interactive)
2234 (save-excursion
2235 (let ((going t)
2236 (start (point))
2237 (found nil)
2238 (prev nil))
2239 (skip-chars-backward " \t;|&({[")
2240 (while (and (not found)
2241 (not (bobp))
2242 going)
8db2b9fb 2243 ;; Do a backward-sexp if possible, else backup bit by bit...
6c5bcbc1 2244 (if (sh-safe-forward-sexp -1)
f964dfcb
GM
2245 (progn
2246 (if (looking-at sh-special-keywords)
2247 (progn
2248 (setq found prev))
2249 (setq prev (point))
2250 ))
2251 ;; backward-sexp failed
2252 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2253 (forward-char -1))
2254 (if (bolp)
2255 (let ((back (sh-prev-line nil)))
2256 (if back
2257 (goto-char back)
2258 (setq going nil)))))
2259 (unless found
2260 (skip-chars-backward " \t")
2261 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2262 (eq (char-before) ?\;)
2263 (looking-at "\\s-*[|&]"))
2264 (setq found (point)))))
2265 (if found
2266 (goto-char found))
2267 (if found
2268 (progn
2269 (skip-chars-forward " \t|&({[")
2270 (setq found (point))))
2271 (if (>= (point) start)
2272 (progn
2273 (debug "We didn't move!")
2274 (setq found nil))
2275 (or found
2276 (sh-debug "Did not find prev stmt.")))
34939e2c 2277 found)))
f964dfcb
GM
2278
2279
2280(defun sh-get-word ()
2281 "Get a shell word skipping whitespace from point."
2282 (interactive)
2283 (skip-chars-forward "\t ")
2284 (let ((start (point)))
2285 (while
2286 (if (looking-at "[\"'`]")
2287 (sh-safe-forward-sexp)
2288 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2289 (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2290 ))
2291 (buffer-substring start (point))
2292 ))
2293
2294(defun sh-prev-thing ()
2295 "Return the previous thing this logical line."
2296 ;; This is called when `sh-get-indent-info' is working backwards on
2297 ;; the previous line(s) finding what keywords may be relevant for
8db2b9fb 2298 ;; indenting. It moves over sexps if possible, and will stop
f964dfcb
GM
2299 ;; on a ; and at the beginning of a line if it is not a continuation
2300 ;; line.
2301 ;;
2302 ;; Added a kludge for ";;"
2303 ;; Possible return values:
2304 ;; nil - nothing
2305 ;; a string - possibly a keyword
035107fa 2306 ;;
f964dfcb
GM
2307 (if (bolp)
2308 nil
485219e0
SM
2309 (let (c min-point
2310 (start (point)))
f964dfcb
GM
2311 (save-restriction
2312 (narrow-to-region
6c5bcbc1
SM
2313 (if (sh-this-is-a-continuation)
2314 (setq min-point (sh-prev-line nil))
2315 (save-excursion
2316 (beginning-of-line)
2317 (setq min-point (point))))
2318 (point))
f964dfcb
GM
2319 (skip-chars-backward " \t;")
2320 (unless (looking-at "\\s-*;;")
6c5bcbc1
SM
2321 (skip-chars-backward "^)}];\"'`({[")
2322 (setq c (char-before))))
f964dfcb 2323 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
6c5bcbc1 2324 (point) c start min-point)
f964dfcb
GM
2325 (if (< (point) min-point)
2326 (error "point %d < min-point %d" (point) min-point))
2327 (cond
2328 ((looking-at "\\s-*;;")
2329 ;; (message "Found ;; !")
6c5bcbc1 2330 ";;")
f964dfcb
GM
2331 ((or (eq c ?\n)
2332 (eq c nil)
2333 (eq c ?\;))
6c5bcbc1
SM
2334 (save-excursion
2335 ;; skip forward over white space newline and \ at eol
2336 (skip-chars-forward " \t\n\\\\")
2337 (sh-debug "Now at %d start=%d" (point) start)
2338 (if (>= (point) start)
2339 (progn
2340 (sh-debug "point: %d >= start: %d" (point) start)
2341 nil)
2342 (sh-get-word))
2343 ))
f964dfcb
GM
2344 (t
2345 ;; c -- return a string
6c5bcbc1
SM
2346 (char-to-string c)
2347 ))
f964dfcb
GM
2348 )))
2349
2350
2351(defun sh-this-is-a-continuation ()
2352 "Return non-nil if current line is a continuation of previous line."
6c5bcbc1
SM
2353 (save-excursion
2354 (and (zerop (forward-line -1))
2355 (looking-at ".*\\\\$")
2356 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2357 nil nil nil t))))))
f964dfcb
GM
2358
2359(defun sh-get-kw (&optional where and-move)
2360 "Return first word of line from WHERE.
2361If AND-MOVE is non-nil then move to end of word."
2362 (let ((start (point)))
2363 (if where
2364 (goto-char where))
2365 (prog1
2366 (buffer-substring (point)
6c5bcbc1 2367 (progn (skip-chars-forward "^ \t\n;")(point)))
f964dfcb 2368 (unless and-move
34939e2c 2369 (goto-char start)))))
f964dfcb
GM
2370
2371(defun sh-find-prev-matching (open close &optional depth)
2372 "Find a matching token for a set of opening and closing keywords.
2373This takes into account that there may be nested open..close pairings.
2374OPEN and CLOSE are regexps denoting the tokens to be matched.
2375Optional parameter DEPTH (usually 1) says how many to look for."
2376 (let ((parse-sexp-ignore-comments t)
2377 prev)
2378 (setq depth (or depth 1))
2379 (save-excursion
2380 (condition-case nil
2381 (while (and
2382 (/= 0 depth)
2383 (not (bobp))
2384 (setq prev (sh-prev-stmt)))
2385 (goto-char prev)
2386 (save-excursion
2387 (if (looking-at "\\\\\n")
2388 (progn
2389 (forward-char 2)
2390 (skip-chars-forward " \t")))
2391 (cond
2392 ((looking-at open)
2393 (setq depth (1- depth))
2394 (sh-debug "found open at %d - depth = %d" (point) depth))
2395 ((looking-at close)
2396 (setq depth (1+ depth))
2397 (sh-debug "found close - depth = %d" depth))
2398 (t
2399 ))))
6c5bcbc1 2400 (error nil))
f964dfcb
GM
2401 (if (eq depth 0)
2402 prev ;; (point)
2403 nil)
2404 )))
2405
2406
2407(defun sh-var-value (var &optional ignore-error)
2408 "Return the value of variable VAR, interpreting symbols.
2409It can also return t or nil.
eac9c0ef 2410If an invalid value is found, throw an error unless Optional argument
f964dfcb
GM
2411IGNORE-ERROR is non-nil."
2412 (let ((val (symbol-value var)))
2413 (cond
2414 ((numberp val)
2415 val)
2416 ((eq val t)
2417 val)
2418 ((null val)
2419 val)
2420 ((eq val '+)
2421 sh-basic-offset)
2422 ((eq val '-)
2423 (- sh-basic-offset))
2424 ((eq val '++)
2425 (* 2 sh-basic-offset))
2426 ((eq val '--)
2427 (* 2 (- sh-basic-offset)))
2428 ((eq val '*)
2429 (/ sh-basic-offset 2))
2430 ((eq val '/)
2431 (/ (- sh-basic-offset) 2))
2432 (t
2433 (if ignore-error
6c5bcbc1
SM
2434 (progn
2435 (message "Don't know how to handle %s's value of %s" var val)
2436 0)
2437 (error "Don't know how to handle %s's value of %s" var val))
f964dfcb
GM
2438 ))))
2439
2440(defun sh-set-var-value (var value &optional no-symbol)
2441 "Set variable VAR to VALUE.
8db2b9fb 2442Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
f964dfcb
GM
2443can be represented by a symbol then do so."
2444 (cond
2445 (no-symbol
2446 (set var value))
2447 ((= value sh-basic-offset)
2448 (set var '+))
2449 ((= value (- sh-basic-offset))
2450 (set var '-))
2451 ((eq value (* 2 sh-basic-offset))
2452 (set var '++))
2453 ((eq value (* 2 (- sh-basic-offset)))
2454 (set var '--))
2455 ((eq value (/ sh-basic-offset 2))
2456 (set var '*))
2457 ((eq value (/ (- sh-basic-offset) 2))
2458 (set var '/))
2459 (t
2460 (set var value)))
2461 )
2462
2463
2464(defun sh-calculate-indent (&optional info)
2465 "Return the indentation for the current line.
2466If INFO is supplied it is used, else it is calculated from current line."
6c5bcbc1 2467 (let ((ofs 0)
f964dfcb
GM
2468 (base-value 0)
2469 elt a b var val)
2470 (or info
2471 (setq info (sh-get-indent-info)))
6c5bcbc1 2472 (when info
f964dfcb
GM
2473 (while info
2474 (sh-debug "info: %s ofs=%s" info ofs)
2475 (setq elt (car info))
2476 (cond
6c5bcbc1 2477 ((stringp elt)) ;; do nothing?
f964dfcb
GM
2478 ((listp elt)
2479 (setq a (car (car info)))
2480 (setq b (nth 1 (car info)))
2481 (cond
2482 ((eq a t)
2483 (save-excursion
2484 (goto-char b)
2485 (setq val (current-indentation)))
2486 (setq base-value val))
2487 ((symbolp b)
2488 (setq val (sh-var-value b))
2489 (cond
2490 ((eq a '=)
2491 (cond
2492 ((null val)
2493 ;; no indentation
2494 ;; set info to nil so we stop immediately
2495 (setq base-value nil ofs nil info nil))
6c5bcbc1 2496 ((eq val t) (setq ofs 0)) ;; indent as normal line
f964dfcb
GM
2497 (t
2498 ;; The following assume the (t POS) come first!
2499 (setq ofs val base-value 0)
6c5bcbc1
SM
2500 (setq info nil)))) ;; ? stop now
2501 ((eq a '+) (setq ofs (+ ofs val)))
2502 ((eq a '-) (setq ofs (- ofs val)))
f964dfcb
GM
2503 (t
2504 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2505 (t
6c5bcbc1 2506 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
f964dfcb 2507 (t
6c5bcbc1
SM
2508 (error "sh-calculate-indent invalid elt %s" elt)))
2509 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2510 a b val base-value ofs)
2511 (setq info (cdr info)))
f964dfcb
GM
2512 ;; return value:
2513 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2514
2515 (cond
2516 ((or (null base-value)(null ofs))
2517 nil)
2518 ((and (numberp base-value)(numberp ofs))
2519 (sh-debug "base (%d) + ofs (%d) = %d"
6c5bcbc1 2520 base-value ofs (+ base-value ofs))
f964dfcb
GM
2521 (+ base-value ofs)) ;; return value
2522 (t
2523 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2524 base-value ofs)
6c5bcbc1 2525 nil)))))
f964dfcb
GM
2526
2527
3e2dd647 2528(defun sh-indent-line ()
f964dfcb
GM
2529 "Indent the current line."
2530 (interactive)
017708e9 2531 (let ((indent (sh-calculate-indent))
f964dfcb 2532 (pos (- (point-max) (point))))
6c5bcbc1
SM
2533 (when indent
2534 (beginning-of-line)
6c5bcbc1 2535 (skip-chars-forward " \t")
017708e9 2536 (indent-line-to indent)
6c5bcbc1
SM
2537 ;; If initial point was within line's indentation,
2538 ;; position after the indentation. Else stay at same point in text.
2539 (if (> (- (point-max) pos) (point))
2540 (goto-char (- (point-max) pos))))))
f964dfcb
GM
2541
2542
2543(defun sh-blink (blinkpos &optional msg)
2544 "Move cursor momentarily to BLINKPOS and display MSG."
2545 ;; We can get here without it being a number on first line
2546 (if (numberp blinkpos)
2547 (save-excursion
2548 (goto-char blinkpos)
2549 (message msg)
2550 (sit-for blink-matching-delay))
6c5bcbc1 2551 (message msg)))
f964dfcb
GM
2552
2553(defun sh-show-indent (arg)
2554 "Show the how the currently line would be indented.
2555This tells you which variable, if any, controls the indentation of
2556this line.
2557If optional arg ARG is non-null (called interactively with a prefix),
2558a pop up window describes this variable.
2559If variable `sh-blink' is non-nil then momentarily go to the line
2560we are indenting relative to, if applicable."
2561 (interactive "P")
2562 (sh-must-support-indent)
2563 (let* ((info (sh-get-indent-info))
2564 (var (sh-get-indent-var-for-line info))
6c5bcbc1
SM
2565 (curr-indent (current-indentation))
2566 val msg)
f964dfcb
GM
2567 (if (stringp var)
2568 (message (setq msg var))
2569 (setq val (sh-calculate-indent info))
2570
2571 (if (eq curr-indent val)
2572 (setq msg (format "%s is %s" var (symbol-value var)))
2573 (setq msg
2574 (if val
2575 (format "%s (%s) would change indent from %d to: %d"
2576 var (symbol-value var) curr-indent val)
2577 (format "%s (%s) would leave line as is"
2578 var (symbol-value var)))
2579 ))
2580 (if (and arg var)
2581 (describe-variable var)))
2582 (if sh-blink
2583 (let ((info (sh-get-indent-info)))
2584 (if (and info (listp (car info))
2585 (eq (car (car info)) t))
2586 (sh-blink (nth 1 (car info)) msg)
2587 (message msg)))
2588 (message msg))
2589 ))
2590
2591(defun sh-set-indent ()
2592 "Set the indentation for the current line.
2593If the current line is controlled by an indentation variable, prompt
2594for a new value for it."
2595 (interactive)
2596 (sh-must-support-indent)
2597 (let* ((info (sh-get-indent-info))
2598 (var (sh-get-indent-var-for-line info))
485219e0 2599 val old-val indent-val)
f964dfcb
GM
2600 (if (stringp var)
2601 (message (format "Cannot set indent - %s" var))
2602 (setq old-val (symbol-value var))
2603 (setq val (sh-read-variable var))
2604 (condition-case nil
2605 (progn
2606 (set var val)
2607 (setq indent-val (sh-calculate-indent info))
2608 (if indent-val
2609 (message "Variable: %s Value: %s would indent to: %d"
2610 var (symbol-value var) indent-val)
2611 (message "Variable: %s Value: %s would leave line as is."
2612 var (symbol-value var)))
8db2b9fb 2613 ;; I'm not sure about this, indenting it now?
f964dfcb 2614 ;; No. Because it would give the impression that an undo would
8db2b9fb 2615 ;; restore thing, but the value has been altered.
f964dfcb
GM
2616 ;; (sh-indent-line)
2617 )
2618 (error
2619 (set var old-val)
8db2b9fb 2620 (message "Bad value for %s, restoring to previous value %s"
f964dfcb
GM
2621 var old-val)
2622 (sit-for 1)
2623 nil))
2624 )))
2625
2626
2627(defun sh-learn-line-indent (arg)
2628 "Learn how to indent a line as it currently is indented.
2629
2630If there is an indentation variable which controls this line's indentation,
2631then set it to a value which would indent the line the way it
2632presently is.
2633
2634If the value can be represented by one of the symbols then do so
2635unless optional argument ARG (the prefix when interactive) is non-nil."
2636 (interactive "*P")
2637 (sh-must-support-indent)
2638 ;; I'm not sure if we show allow learning on an empty line.
2639 ;; Though it might occasionally be useful I think it usually
2640 ;; would just be confusing.
2641 (if (save-excursion
2642 (beginning-of-line)
2643 (looking-at "\\s-*$"))
2644 (message "sh-learn-line-indent ignores empty lines.")
2645 (let* ((info (sh-get-indent-info))
2646 (var (sh-get-indent-var-for-line info))
2647 ival sval diff new-val
2648 (no-symbol arg)
2649 (curr-indent (current-indentation)))
6c5bcbc1
SM
2650 (cond
2651 ((stringp var)
2652 (message (format "Cannot learn line - %s" var)))
2653 ((eq var 'sh-indent-comment)
2654 ;; This is arbitrary...
2655 ;; - if curr-indent is 0, set to curr-indent
2656 ;; - else if it has the indentation of a "normal" line,
2657 ;; then set to t
2658 ;; - else set to curr-indent.
2659 (setq sh-indent-comment
2660 (if (= curr-indent 0)
2661 0
2662 (let* ((sh-indent-comment t)
2663 (val2 (sh-calculate-indent info)))
2664 (if (= val2 curr-indent)
2665 t
2666 curr-indent))))
2667 (message "%s set to %s" var (symbol-value var))
2668 )
2669 ((numberp (setq sval (sh-var-value var)))
2670 (setq ival (sh-calculate-indent info))
2671 (setq diff (- curr-indent ival))
035107fa 2672
6c5bcbc1
SM
2673 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2674 curr-indent ival diff var sval)
2675 (setq new-val (+ sval diff))
f964dfcb
GM
2676;;; I commented out this because someone might want to replace
2677;;; a value of `+' with the current value of sh-basic-offset
2678;;; or vice-versa.
2679;;; (if (= 0 diff)
2680;;; (message "No change needed!")
6c5bcbc1
SM
2681 (sh-set-var-value var new-val no-symbol)
2682 (message "%s set to %s" var (symbol-value var))
2683 )
2684 (t
2685 (debug)
2686 (message "Cannot change %s" var))))))
f964dfcb
GM
2687
2688
2689
2690(defun sh-mark-init (buffer)
2691 "Initialize a BUFFER to be used by `sh-mark-line'."
348e1411
JB
2692 (save-excursion
2693 (set-buffer (get-buffer-create buffer))
2694 (erase-buffer)
2695 (occur-mode)
2696 ))
f964dfcb
GM
2697
2698
2699(defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2700 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2701Buffer BUFFER is in `occur-mode'.
2702If ADD-LINENUM is non-nil the message is preceded by the line number.
8db2b9fb 2703If OCCUR-POINT is non-nil then the line is marked as a new occurrence
f964dfcb
GM
2704so that `occur-next' and `occur-prev' will work."
2705 (let ((m1 (make-marker))
f964dfcb 2706 start
6c5bcbc1
SM
2707 (line ""))
2708 (when point
2709 (set-marker m1 point (current-buffer))
2710 (if add-linenum
2711 (setq line (format "%d: " (1+ (count-lines 1 point))))))
f964dfcb
GM
2712 (save-excursion
2713 (if (get-buffer buffer)
2714 (set-buffer (get-buffer buffer))
2715 (set-buffer (get-buffer-create buffer))
2716 (occur-mode)
f964dfcb
GM
2717 )
2718 (goto-char (point-max))
2719 (setq start (point))
2720 (insert line)
2721 (if occur-point
2722 (setq occur-point (point)))
2723 (insert message)
2724 (if point
06d74900
EZ
2725 (add-text-properties
2726 start (point)
2727 '(mouse-face highlight
2728 help-echo "mouse-2: go to the line where I learned this")))
f964dfcb
GM
2729 (insert "\n")
2730 (if point
2731 (progn
348e1411 2732 (put-text-property start (point) 'occur-target m1)
f964dfcb 2733 (if occur-point
348e1411
JB
2734 (put-text-property start occur-point
2735 'occur-match t))
f964dfcb
GM
2736 ))
2737 )))
2738
2739
2740
2741;; Is this really worth having?
2742(defvar sh-learned-buffer-hook nil
8db2b9fb 2743 "*An abnormal hook, called with an alist of learned variables.")
3e2dd647 2744;; Example of how to use sh-learned-buffer-hook
035107fa 2745;;
f964dfcb
GM
2746;; (defun what-i-learned (list)
2747;; (let ((p list))
2748;; (save-excursion
2749;; (set-buffer "*scratch*")
2750;; (goto-char (point-max))
2751;; (insert "(setq\n")
2752;; (while p
2753;; (insert (format " %s %s \n"
2754;; (nth 0 (car p)) (nth 1 (car p))))
2755;; (setq p (cdr p)))
2756;; (insert ")\n")
2757;; )))
035107fa 2758;;
f964dfcb
GM
2759;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2760
2761
2762;; Originally this was sh-learn-region-indent (beg end)
8db2b9fb 2763;; However, in practice this was awkward so I changed it to
f964dfcb
GM
2764;; use the whole buffer. Use narrowing if needbe.
2765(defun sh-learn-buffer-indent (&optional arg)
2766 "Learn how to indent the buffer the way it currently is.
2767
2768Output in buffer \"*indent*\" shows any lines which have conflicting
8db2b9fb
SM
2769values of a variable, and the final value of all variables learned.
2770This buffer is popped to automatically if there are any discrepancies.
f964dfcb 2771
8db2b9fb
SM
2772If no prefix ARG is given, then variables are set to numbers.
2773If a prefix arg is given, then variables are set to symbols when
f964dfcb
GM
2774applicable -- e.g. to symbol `+' if the value is that of the
2775basic indent.
2776If a positive numerical prefix is given, then `sh-basic-offset'
2777is set to the prefix's numerical value.
8db2b9fb 2778Otherwise, sh-basic-offset may or may not be changed, according
f964dfcb
GM
2779to the value of variable `sh-learn-basic-offset'.
2780
2781Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2782function completes. The function is abnormal because it is called
8db2b9fb 2783with an alist of variables learned. This feature may be changed or
f964dfcb
GM
2784removed in the future.
2785
2786This command can often take a long time to run."
2787 (interactive "P")
2788 (sh-must-support-indent)
2789 (save-excursion
2790 (goto-char (point-min))
2791 (let ((learned-var-list nil)
2792 (out-buffer "*indent*")
2793 (num-diffs 0)
f964dfcb
GM
2794 previous-set-info
2795 (max 17)
2796 vec
2797 msg
8db2b9fb 2798 (comment-col nil) ;; number if all same, t if seen diff values
f964dfcb
GM
2799 (comments-always-default t) ;; nil if we see one not default
2800 initial-msg
2801 (specified-basic-offset (and arg (numberp arg)
2802 (> arg 0)))
2803 (linenum 0)
2804 suggested)
2805 (setq vec (make-vector max 0))
2806 (sh-mark-init out-buffer)
2807
2808 (if specified-basic-offset
2809 (progn
2810 (setq sh-basic-offset arg)
2811 (setq initial-msg
2812 (format "Using specified sh-basic-offset of %d"
2813 sh-basic-offset)))
2814 (setq initial-msg
2815 (format "Initial value of sh-basic-offset: %s"
2816 sh-basic-offset)))
2817
2818 (while (< (point) (point-max))
2819 (setq linenum (1+ linenum))
6c5bcbc1
SM
2820 ;; (if (zerop (% linenum 10))
2821 (message "line %d" linenum)
2822 ;; )
f964dfcb
GM
2823 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2824 (let* ((sh-indent-comment t) ;; info must return default indent
2825 (info (sh-get-indent-info))
2826 (var (sh-get-indent-var-for-line info))
2827 sval ival diff new-val
2828 (curr-indent (current-indentation)))
2829 (cond
2830 ((null var)
2831 nil)
2832 ((stringp var)
2833 nil)
2834 ((numberp (setq sval (sh-var-value var 'no-error)))
2835 ;; the numberp excludes comments since sval will be t.
2836 (setq ival (sh-calculate-indent))
2837 (setq diff (- curr-indent ival))
2838 (setq new-val (+ sval diff))
2839 (sh-set-var-value var new-val 'no-symbol)
6c5bcbc1 2840 (unless (looking-at "\\s-*#") ;; don't learn from comments
f964dfcb
GM
2841 (if (setq previous-set-info (assoc var learned-var-list))
2842 (progn
8db2b9fb 2843 ;; it was already there, is it same value ?
f964dfcb
GM
2844 (unless (eq (symbol-value var)
2845 (nth 1 previous-set-info))
2846 (sh-mark-line
2847 (format "Variable %s was set to %s"
2848 var (symbol-value var))
2849 (point) out-buffer t t)
2850 (sh-mark-line
2851 (format " but was previously set to %s"
2852 (nth 1 previous-set-info))
2853 (nth 2 previous-set-info) out-buffer t)
2854 (setq num-diffs (1+ num-diffs))
2855 ;; (delete previous-set-info learned-var-list)
2856 (setcdr previous-set-info
2857 (list (symbol-value var) (point)))
2858 )
2859 )
2860 (setq learned-var-list
2861 (append (list (list var (symbol-value var)
2862 (point)))
2863 learned-var-list)))
2864 (if (numberp new-val)
2865 (progn
2866 (sh-debug
2867 "This line's indent value: %d" new-val)
2868 (if (< new-val 0)
2869 (setq new-val (- new-val)))
2870 (if (< new-val max)
2871 (aset vec new-val (1+ (aref vec new-val))))))
2872 ))
2873 ((eq var 'sh-indent-comment)
2874 (unless (= curr-indent (sh-calculate-indent info))
2875 ;; this is not the default indentation
2876 (setq comments-always-default nil)
6c5bcbc1 2877 (if comment-col ;; then we have see one before
f964dfcb 2878 (or (eq comment-col curr-indent)
6c5bcbc1 2879 (setq comment-col t)) ;; seen a different one
f964dfcb 2880 (setq comment-col curr-indent))
6c5bcbc1
SM
2881 ))
2882 (t
f964dfcb
GM
2883 (sh-debug "Cannot learn this line!!!")
2884 ))
2885 (sh-debug
6c5bcbc1 2886 "at %s learned-var-list is %s" (point) learned-var-list)
f964dfcb
GM
2887 ))
2888 (forward-line 1)
2889 ) ;; while
2890 (if sh-debug
2891 (progn
2892 (setq msg (format
2893 "comment-col = %s comments-always-default = %s"
2894 comment-col comments-always-default))
2895 ;; (message msg)
2896 (sh-mark-line msg nil out-buffer)))
2897 (cond
2898 ((eq comment-col 0)
2899 (setq msg "\nComments are all in 1st column.\n"))
2900 (comments-always-default
2901 (setq msg "\nComments follow default indentation.\n")
2902 (setq comment-col t))
2903 ((numberp comment-col)
2904 (setq msg (format "\nComments are in col %d." comment-col)))
2905 (t
8db2b9fb 2906 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
f964dfcb
GM
2907 (setq comment-col nil)
2908 ))
2909 (sh-debug msg)
2910 (sh-mark-line msg nil out-buffer)
2911
2912 (sh-mark-line initial-msg nil out-buffer t t)
2913
2914 (setq suggested (sh-guess-basic-offset vec))
2915
2916 (if (and suggested (not specified-basic-offset))
2917 (let ((new-value
2918 (cond
2919 ;; t => set it if we have a single value as a number
2920 ((and (eq sh-learn-basic-offset t) (numberp suggested))
2921 suggested)
2922 ;; other non-nil => set it if only one value was found
2923 (sh-learn-basic-offset
2924 (if (numberp suggested)
2925 suggested
2926 (if (= (length suggested) 1)
2927 (car suggested))))
2928 (t
2929 nil))))
2930 (if new-value
2931 (progn
2932 (setq learned-var-list
2933 (append (list (list 'sh-basic-offset
2934 (setq sh-basic-offset new-value)
2935 (point-max)))
2936 learned-var-list))
2937 ;; Not sure if we need to put this line in, since
2938 ;; it will appear in the "Learned variable settings".
2939 (sh-mark-line
2940 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
2941 nil out-buffer))
2942 (sh-mark-line
2943 (if (listp suggested)
2944 (format "Possible value(s) for sh-basic-offset: %s"
2945 (mapconcat 'int-to-string suggested " "))
2946 (format "Suggested sh-basic-offset: %d" suggested))
2947 nil out-buffer))))
2948
035107fa 2949
f964dfcb
GM
2950 (setq learned-var-list
2951 (append (list (list 'sh-indent-comment comment-col (point-max)))
6c5bcbc1 2952 learned-var-list))
f964dfcb 2953 (setq sh-indent-comment comment-col)
485219e0 2954 (let ((name (buffer-name)))
f964dfcb
GM
2955 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
2956 (if arg
2957 ;; Set learned variables to symbolic rather than numeric
2958 ;; values where possible.
6c5bcbc1
SM
2959 (dolist (learned-var (reverse learned-var-list))
2960 (let ((var (car learned-var))
2961 (val (nth 1 learned-var)))
2962 (when (and (not (eq var 'sh-basic-offset))
2963 (numberp val))
2964 (sh-set-var-value var val)))))
2965 (dolist (learned-var (reverse learned-var-list))
2966 (let ((var (car learned-var)))
f964dfcb 2967 (sh-mark-line (format " %s %s" var (symbol-value var))
6c5bcbc1 2968 (nth 2 learned-var) out-buffer)))
f964dfcb 2969 (save-excursion
6c5bcbc1
SM
2970 (set-buffer out-buffer)
2971 (goto-char (point-min))
2972 (insert
2973 (format "Indentation values for buffer %s.\n" name)
2974 (format "%d indentation variable%s different values%s\n\n"
2975 num-diffs
2976 (if (= num-diffs 1)
2977 " has" "s have")
2978 (if (zerop num-diffs)
2979 "." ":"))
2980 )))
f964dfcb
GM
2981 ;; Are abnormal hooks considered bad form?
2982 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
2983 (if (or sh-popup-occur-buffer (> num-diffs 0))
2984 (pop-to-buffer out-buffer))
2985 )))
2986
2987(defun sh-guess-basic-offset (vec)
8db2b9fb 2988 "See if we can determine a reasonable value for `sh-basic-offset'.
f964dfcb
GM
2989This is experimental, heuristic and arbitrary!
2990Argument VEC is a vector of information collected by
2991`sh-learn-buffer-indent'.
2992Return values:
2993 number - there appears to be a good single value
8db2b9fb 2994 list of numbers - no obvious one, here is a list of one or more
f964dfcb
GM
2995 reasonable choices
2996 nil - we couldn't find a reasonable one."
2997 (let* ((max (1- (length vec)))
6c5bcbc1 2998 (i 1)
485219e0 2999 (totals (make-vector max 0)))
f964dfcb
GM
3000 (while (< i max)
3001 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
f964dfcb
GM
3002 (if (zerop (% i 2))
3003 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3004 (if (< (* i 2) max)
3005 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
6c5bcbc1
SM
3006 (setq i (1+ i)))
3007
f964dfcb
GM
3008 (let ((x nil)
3009 (result nil)
3010 tot sum p)
3011 (setq i 1)
3012 (while (< i max)
3013 (if (/= (aref totals i) 0)
3014 (setq x (append x (list (cons i (aref totals i))))))
3015 (setq i (1+ i)))
3016
6c5bcbc1 3017 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
f964dfcb
GM
3018 (setq tot (apply '+ (append totals nil)))
3019 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
6c5bcbc1 3020 vec totals tot))
f964dfcb
GM
3021 (cond
3022 ((zerop (length x))
3023 (message "no values!")) ;; we return nil
3024 ((= (length x) 1)
3025 (message "only value is %d" (car (car x)))
6c5bcbc1 3026 (setq result (car (car x)))) ;; return single value
f964dfcb
GM
3027 ((> (cdr (car x)) (/ tot 2))
3028 ;; 1st is > 50%
3029 (message "basic-offset is probably %d" (car (car x)))
3030 (setq result (car (car x)))) ;; again, return a single value
3031 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3032 ;; 1st is >= 2 * 2nd
3033 (message "basic-offset could be %d" (car (car x)))
3034 (setq result (car (car x))))
3035 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3036 ;; 1st & 2nd together >= 50% - return a list
3037 (setq p x sum 0 result nil)
3038 (while (and p
3039 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3040 (setq result (append result (list (car (car p)))))
3041 (setq p (cdr p)))
3042 (message "Possible choices for sh-basic-offset: %s"
3043 (mapconcat 'int-to-string result " ")))
3044 (t
3045 (message "No obvious value for sh-basic-offset. Perhaps %d"
3046 (car (car x)))
3047 ;; result is nil here
3048 ))
34939e2c 3049 result)))
f964dfcb
GM
3050
3051;; ========================================================================
3052
8db2b9fb 3053;; Styles -- a quick and dirty way of saving the indentation settings.
f964dfcb
GM
3054
3055(defvar sh-styles-alist nil
3056 "A list of all known shell indentation styles.")
3057
3058(defun sh-name-style (name &optional confirm-overwrite)
3059 "Name the current indentation settings as a style called NAME.
8db2b9fb 3060If this name exists, the command will prompt whether it should be
f964dfcb 3061overwritten if
8db2b9fb 3062- - it was called interactively with a prefix argument, or
f964dfcb
GM
3063- - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3064 ;; (interactive "sName for this style: ")
3065 (interactive
3066 (list
3067 (read-from-minibuffer "Name for this style? " )
3068 (not current-prefix-arg)))
6c5bcbc1
SM
3069 (let ((slist (cons name
3070 (mapcar (lambda (var) (cons var (symbol-value var)))
3071 sh-var-list)))
3072 (style (assoc name sh-styles-alist)))
3073 (if style
3074 (if (and confirm-overwrite
3075 (not (y-or-n-p "This style exists. Overwrite it? ")))
3076 (message "Not changing style %s" name)
3077 (message "Updating style %s" name)
3078 (setcdr style (cdr slist)))
f964dfcb 3079 (message "Creating new style %s" name)
6c5bcbc1 3080 (push slist sh-styles-alist))))
f964dfcb
GM
3081
3082(defun sh-load-style (name)
3083 "Set shell indentation values for this buffer from those in style NAME."
3084 (interactive (list (completing-read
3085 "Which style to use for this buffer? "
3086 sh-styles-alist nil t)))
3087 (let ((sl (assoc name sh-styles-alist)))
3088 (if (null sl)
3089 (error "sh-load-style - style %s not known" name)
6c5bcbc1
SM
3090 (dolist (var (cdr sl))
3091 (set (car var) (cdr var))))))
f964dfcb
GM
3092
3093(defun sh-save-styles-to-buffer (buff)
3094 "Save all current styles in elisp to buffer BUFF.
3095This is always added to the end of the buffer."
3096 (interactive (list
6c5bcbc1
SM
3097 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3098 (with-current-buffer (get-buffer-create buff)
f964dfcb
GM
3099 (goto-char (point-max))
3100 (insert "\n")
6c5bcbc1 3101 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
f964dfcb
GM
3102
3103
3104\f
ac59aed8
RS
3105;; statement syntax-commands for various shells
3106
3107;; You are welcome to add the syntax or even completely new statements as
3108;; appropriate for your favorite shell.
3109
017708e9
SM
3110(defconst sh-non-closing-paren
3111 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3112 ;; that inherits this property, which then confuses the indentation.
3113 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3114
c410bd65
RS
3115(define-skeleton sh-case
3116 "Insert a case/switch statement. See `sh-feature'."
cef926f3
RS
3117 (csh "expression: "
3118 "switch( " str " )" \n
3119 > "case " (read-string "pattern: ") ?: \n
c410bd65 3120 > _ \n
cef926f3 3121 "breaksw" \n
c410bd65 3122 ( "other pattern, %s: "
cef926f3 3123 < "case " str ?: \n
c410bd65 3124 > _ \n
cef926f3
RS
3125 "breaksw" \n)
3126 < "default:" \n
c410bd65
RS
3127 > _ \n
3128 resume:
3e2dd647 3129 < < "endsw" \n)
cef926f3
RS
3130 (es)
3131 (rc "expression: "
f964dfcb 3132 > "switch( " str " ) {" \n
cef926f3
RS
3133 > "case " (read-string "pattern: ") \n
3134 > _ \n
3135 ( "other pattern, %s: "
f964dfcb 3136 "case " str > \n
cef926f3 3137 > _ \n)
f964dfcb 3138 "case *" > \n
cef926f3
RS
3139 > _ \n
3140 resume:
035107fa 3141 ?\} > \n)
cef926f3 3142 (sh "expression: "
f964dfcb 3143 > "case " str " in" \n
017708e9
SM
3144 ( "pattern, %s: "
3145 > str sh-non-closing-paren \n
cef926f3 3146 > _ \n
8f0b0ca5 3147 ";;" \n)
017708e9 3148 > "*" sh-non-closing-paren \n
cef926f3
RS
3149 > _ \n
3150 resume:
3e2dd647 3151 "esac" > \n))
133693bc
KH
3152
3153(define-skeleton sh-for
3154 "Insert a for loop. See `sh-feature'."
720baa46 3155 (csh sh-modify sh
f964dfcb
GM
3156 1 ""
3157 2 "foreach "
3158 4 " ( "
3159 6 " )"
3160 15 '<
b36581fb 3161 16 "end")
720baa46 3162 (es sh-modify rc
f964dfcb 3163 4 " = ")
720baa46 3164 (rc sh-modify sh
f964dfcb
GM
3165 2 "for( "
3166 6 " ) {"
035107fa 3167 15 ?\} )
ac59aed8 3168 (sh "Index variable: "
f964dfcb 3169 > "for " str " in " _ "; do" \n
133693bc 3170 > _ | ?$ & (sh-remember-variable str) \n
3e2dd647 3171 "done" > \n))
ac59aed8
RS
3172
3173
3174
133693bc
KH
3175(define-skeleton sh-indexed-loop
3176 "Insert an indexed loop from 1 to n. See `sh-feature'."
720baa46 3177 (bash sh-modify posix)
ac59aed8
RS
3178 (csh "Index variable: "
3179 "@ " str " = 1" \n
133693bc
KH
3180 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3181 > _ ?$ str \n
ac59aed8 3182 "@ " str "++" \n
3e2dd647 3183 < "end" \n)
720baa46 3184 (es sh-modify rc
f964dfcb 3185 4 " =")
133693bc 3186 (ksh88 "Index variable: "
f964dfcb
GM
3187 > "integer " str "=0" \n
3188 > "while (( ( " str " += 1 ) <= "
133693bc
KH
3189 (read-string "upper limit: ")
3190 " )); do" \n
f964dfcb 3191 > _ ?$ (sh-remember-variable str) > \n
3e2dd647 3192 "done" > \n)
133693bc 3193 (posix "Index variable: "
f964dfcb 3194 > str "=1" \n
133693bc
KH
3195 "while [ $" str " -le "
3196 (read-string "upper limit: ")
3197 " ]; do" \n
3198 > _ ?$ str \n
3199 str ?= (sh-add (sh-remember-variable str) 1) \n
3e2dd647 3200 "done" > \n)
133693bc 3201 (rc "Index variable: "
f964dfcb 3202 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
133693bc 3203 (read-string "upper limit: ")
f964dfcb 3204 "; i++ ) print i }'`}) {" \n
133693bc 3205 > _ ?$ (sh-remember-variable str) \n
035107fa 3206 ?\} > \n)
133693bc 3207 (sh "Index variable: "
f964dfcb 3208 > "for " str " in `awk 'BEGIN { for( i=1; i<="
133693bc
KH
3209 (read-string "upper limit: ")
3210 "; i++ ) print i }'`; do" \n
3211 > _ ?$ (sh-remember-variable str) \n
3e2dd647 3212 "done" > \n))
ac59aed8
RS
3213
3214
5d73ac66
RS
3215(defun sh-shell-initialize-variables ()
3216 "Scan the buffer for variable assignments.
3217Add these variables to `sh-shell-variables'."
3218 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3219 (save-excursion
3220 (goto-char (point-min))
3221 (setq sh-shell-variables-initialized t)
3222 (while (search-forward "=" nil t)
3223 (sh-assignment 0)))
3224 (message "Scanning buffer `%s' for variable assignments...done"
3225 (buffer-name)))
3226
3227(defvar sh-add-buffer)
3228
3229(defun sh-add-completer (string predicate code)
3230 "Do completion using `sh-shell-variables', but initialize it first.
3231This function is designed for use as the \"completion table\",
3232so it takes three arguments:
3233 STRING, the current buffer contents;
3234 PREDICATE, the predicate for filtering possible matches;
3235 CODE, which says what kind of things to do.
3236CODE can be nil, t or `lambda'.
3237nil means to return the best completion of STRING, or nil if there is none.
3238t means to return a list of all possible completions of STRING.
3239`lambda' means to return t if STRING is a valid completion as it stands."
3240 (let ((sh-shell-variables
3241 (save-excursion
3242 (set-buffer sh-add-buffer)
3243 (or sh-shell-variables-initialized
3244 (sh-shell-initialize-variables))
3245 (nconc (mapcar (lambda (var)
3246 (let ((name
3247 (substring var 0 (string-match "=" var))))
3248 (cons name name)))
3249 process-environment)
3250 sh-shell-variables))))
017708e9 3251 (case code
fa1d74c5 3252 ((nil) (try-completion string sh-shell-variables predicate))
017708e9
SM
3253 (lambda (test-completion string sh-shell-variables predicate))
3254 (t (all-completions string sh-shell-variables predicate)))))
5d73ac66 3255
ac59aed8 3256(defun sh-add (var delta)
133693bc 3257 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
ac59aed8 3258 (interactive
5d73ac66
RS
3259 (let ((sh-add-buffer (current-buffer)))
3260 (list (completing-read "Variable: " 'sh-add-completer)
3261 (prefix-numeric-value current-prefix-arg))))
546e2f6f 3262 (insert (sh-feature '((bash . "$(( ")
133693bc
KH
3263 (ksh88 . "$(( ")
3264 (posix . "$(( ")
3265 (rc . "`{expr $")
3266 (sh . "`expr $")
3267 (zsh . "$[ ")))
3268 (sh-remember-variable var)
3269 (if (< delta 0) " - " " + ")
3270 (number-to-string (abs delta))
546e2f6f 3271 (sh-feature '((bash . " ))")
133693bc
KH
3272 (ksh88 . " ))")
3273 (posix . " ))")
3274 (rc . "}")
3275 (sh . "`")
3276 (zsh . " ]")))))
3277
3278
3279
3280(define-skeleton sh-function
3281 "Insert a function definition. See `sh-feature'."
720baa46 3282 (bash sh-modify ksh88
133693bc
KH
3283 3 "() {")
3284 (ksh88 "name: "
3285 "function " str " {" \n
3286 > _ \n
3e2dd647 3287 < "}" \n)
720baa46 3288 (rc sh-modify ksh88
6c5bcbc1 3289 1 "fn ")
ac59aed8
RS
3290 (sh ()
3291 "() {" \n
3292 > _ \n
3e2dd647 3293 < "}" \n))
ac59aed8
RS
3294
3295
3296
133693bc
KH
3297(define-skeleton sh-if
3298 "Insert an if statement. See `sh-feature'."
ac59aed8
RS
3299 (csh "condition: "
3300 "if( " str " ) then" \n
3301 > _ \n
3302 ( "other condition, %s: "
133693bc
KH
3303 < "else if( " str " ) then" \n
3304 > _ \n)
ac59aed8 3305 < "else" \n
133693bc 3306 > _ \n
ac59aed8 3307 resume:
3e2dd647 3308 < "endif" \n)
133693bc 3309 (es "condition: "
6c5bcbc1
SM
3310 > "if { " str " } {" \n
3311 > _ \n
3312 ( "other condition, %s: "
3313 "} { " str " } {" > \n
3314 > _ \n)
3315 "} {" > \n
3316 > _ \n
3317 resume:
035107fa 3318 ?\} > \n)
f964dfcb 3319 (rc "condition: "
6c5bcbc1
SM
3320 > "if( " str " ) {" \n
3321 > _ \n
3322 ( "other condition, %s: "
3323 "} else if( " str " ) {" > \n
3324 > _ \n)
3325 "} else {" > \n
3326 > _ \n
3327 resume:
035107fa 3328 ?\} > \n)
133693bc 3329 (sh "condition: "
225f6185 3330 '(setq input (sh-feature sh-test))
f964dfcb 3331 > "if " str "; then" \n
133693bc
KH
3332 > _ \n
3333 ( "other condition, %s: "
6c5bcbc1 3334 > "elif " str "; then" > \n
8f0b0ca5 3335 > \n)
6c5bcbc1 3336 "else" > \n
f964dfcb 3337 > \n
133693bc 3338 resume:
3e2dd647 3339 "fi" > \n))
ac59aed8
RS
3340
3341
3342
133693bc
KH
3343(define-skeleton sh-repeat
3344 "Insert a repeat loop definition. See `sh-feature'."
3345 (es nil
f964dfcb 3346 > "forever {" \n
133693bc 3347 > _ \n
035107fa 3348 ?\} > \n)
133693bc 3349 (zsh "factor: "
f964dfcb 3350 > "repeat " str "; do" > \n
6c5bcbc1 3351 > \n
3e2dd647 3352 "done" > \n))
f964dfcb 3353
ea39159e 3354;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
133693bc
KH
3355
3356
3357
3358(define-skeleton sh-select
3359 "Insert a select statement. See `sh-feature'."
3360 (ksh88 "Index variable: "
f964dfcb 3361 > "select " str " in " _ "; do" \n
133693bc 3362 > ?$ str \n
3e2dd647 3363 "done" > \n)
720baa46 3364 (bash sh-append ksh88))
ea39159e 3365;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
133693bc
KH
3366
3367
3368
3369(define-skeleton sh-tmp-file
3370 "Insert code to setup temporary file handling. See `sh-feature'."
720baa46 3371 (bash sh-append ksh88)
133693bc
KH
3372 (csh (file-name-nondirectory (buffer-file-name))
3373 "set tmp = /tmp/" str ".$$" \n
3374 "onintr exit" \n _
3375 (and (goto-char (point-max))
3376 (not (bolp))
3377 ?\n)
3378 "exit:\n"
3e2dd647 3379 "rm $tmp* >&/dev/null" > \n)
133693bc 3380 (es (file-name-nondirectory (buffer-file-name))
f964dfcb
GM
3381 > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3382 ".$pid ) {" \n
133693bc
KH
3383 > "catch @ e {" \n
3384 > "rm $tmp^* >[2]/dev/null" \n
3385 "throw $e" \n
f964dfcb 3386 "} {" > \n
6c5bcbc1 3387 _ \n
035107fa
SS
3388 ?\} > \n
3389 ?\} > \n)
720baa46 3390 (ksh88 sh-modify sh
f964dfcb 3391 7 "EXIT")
133693bc 3392 (rc (file-name-nondirectory (buffer-file-name))
f964dfcb 3393 > "tmp = /tmp/" str ".$pid" \n
3e2dd647 3394 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
133693bc 3395 (sh (file-name-nondirectory (buffer-file-name))
f964dfcb 3396 > "TMP=${TMPDIR:-/tmp}/" str ".$$" \n
3e2dd647 3397 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
ac59aed8
RS
3398
3399
3400
133693bc
KH
3401(define-skeleton sh-until
3402 "Insert an until loop. See `sh-feature'."
ac59aed8 3403 (sh "condition: "
225f6185 3404 '(setq input (sh-feature sh-test))
f964dfcb 3405 > "until " str "; do" \n
ac59aed8 3406 > _ \n
3e2dd647 3407 "done" > \n))
ea39159e 3408;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
133693bc
KH
3409
3410
3411
3412(define-skeleton sh-while
3413 "Insert a while loop. See `sh-feature'."
720baa46 3414 (csh sh-modify sh
f964dfcb
GM
3415 2 ""
3416 3 "while( "
3417 5 " )"
3418 10 '<
b36581fb 3419 11 "end")
720baa46 3420 (es sh-modify sh
f964dfcb
GM
3421 3 "while { "
3422 5 " } {"
035107fa 3423 10 ?\} )
720baa46 3424 (rc sh-modify sh
f964dfcb
GM
3425 3 "while( "
3426 5 " ) {"
035107fa 3427 10 ?\} )
ac59aed8 3428 (sh "condition: "
225f6185 3429 '(setq input (sh-feature sh-test))
f964dfcb 3430 > "while " str "; do" \n
ac59aed8 3431 > _ \n
3e2dd647 3432 "done" > \n))
133693bc
KH
3433
3434
3435
3436(define-skeleton sh-while-getopts
3437 "Insert a while getopts loop. See `sh-feature'.
3438Prompts for an options string which consists of letters for each recognized
3439option followed by a colon `:' if the option accepts an argument."
720baa46 3440 (bash sh-modify sh
133693bc 3441 18 "${0##*/}")
225f6185
KH
3442 (csh nil
3443 "while( 1 )" \n
3444 > "switch( \"$1\" )" \n
3445 '(setq input '("- x" . 2))
3446 > >
3447 ( "option, %s: "
3448 < "case " '(eval str)
3449 '(if (string-match " +" str)
3450 (setq v1 (substring str (match-end 0))
3451 str (substring str 0 (match-beginning 0)))
3452 (setq v1 nil))
3453 str ?: \n
3454 > "set " v1 & " = $2" | -4 & _ \n
3455 (if v1 "shift") & \n
3456 "breaksw" \n)
3457 < "case --:" \n
3458 > "shift" \n
3459 < "default:" \n
3460 > "break" \n
3461 resume:
3462 < < "endsw" \n
3463 "shift" \n
3e2dd647 3464 < "end" \n)
720baa46 3465 (ksh88 sh-modify sh
133693bc
KH
3466 16 "print"
3467 18 "${0##*/}"
bc387269 3468 37 "OPTIND-1")
720baa46 3469 (posix sh-modify sh
133693bc
KH
3470 18 "$(basename $0)")
3471 (sh "optstring: "
f964dfcb 3472 > "while getopts :" str " OPT; do" \n
133693bc 3473 > "case $OPT in" \n
133693bc
KH
3474 '(setq v1 (append (vconcat str) nil))
3475 ( (prog1 (if v1 (char-to-string (car v1)))
3476 (if (eq (nth 1 v1) ?:)
3477 (setq v1 (nthcdr 2 v1)
3478 v2 "\"$OPTARG\"")
3479 (setq v1 (cdr v1)
3480 v2 nil)))
017708e9 3481 > str "|+" str sh-non-closing-paren \n
133693bc 3482 > _ v2 \n
8f0b0ca5 3483 > ";;" \n)
017708e9 3484 > "*" sh-non-closing-paren \n
133693bc 3485 > "echo" " \"usage: " "`basename $0`"
c898fb28 3486 " [+-" '(setq v1 (point)) str
133693bc
KH
3487 '(save-excursion
3488 (while (search-backward ":" v1 t)
c898fb28 3489 (replace-match " ARG] [+-" t t)))
133693bc 3490 (if (eq (preceding-char) ?-) -5)
16ed8416 3491 (if (and (sequencep v1) (length v1)) "] " "} ")
119b42eb 3492 "[--] ARGS...\"" \n
f964dfcb 3493 "exit 2" > \n
6c5bcbc1
SM
3494 "esac" >
3495 \n "done"
3496 > \n
546e2f6f
GM
3497 "shift " (sh-add "OPTIND" -1) \n
3498 "OPTIND=1" \n))
ac59aed8
RS
3499
3500
3501
3502(defun sh-assignment (arg)
133693bc 3503 "Remember preceding identifier for future completion and do self-insert."
ac59aed8 3504 (interactive "p")
133693bc
KH
3505 (self-insert-command arg)
3506 (if (<= arg 1)
ac59aed8
RS
3507 (sh-remember-variable
3508 (save-excursion
133693bc
KH
3509 (if (re-search-forward (sh-feature sh-assignment-regexp)
3510 (prog1 (point)
3511 (beginning-of-line 1))
3512 t)
84bfbb44 3513 (match-string 1))))))
ac59aed8
RS
3514
3515
ac59aed8 3516(defun sh-maybe-here-document (arg)
6c5bcbc1 3517 "Insert self. Without prefix, following unquoted `<' inserts here document.
ac59aed8
RS
3518The document is bounded by `sh-here-document-word'."
3519 (interactive "*P")
3520 (self-insert-command (prefix-numeric-value arg))
3521 (or arg
3522 (not (eq (char-after (- (point) 2)) last-command-char))
3523 (save-excursion
133693bc 3524 (backward-char 2)
ac59aed8 3525 (sh-quoted-p))
546e2f6f
GM
3526 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
3527 (make-string (/ (current-indentation) tab-width) ?\t)
3528 ""))
3529 (delim (replace-regexp-in-string "['\"]" ""
3530 sh-here-document-word)))
ac59aed8 3531 (insert sh-here-document-word)
133693bc 3532 (or (eolp) (looking-at "[ \t]") (insert ? ))
ac59aed8 3533 (end-of-line 1)
133693bc
KH
3534 (while
3535 (sh-quoted-p)
3536 (end-of-line 2))
546e2f6f 3537 (insert ?\n tabs)
18368c4a 3538 (save-excursion
546e2f6f
GM
3539 (insert ?\n tabs (replace-regexp-in-string
3540 "\\`-?[ \t]*" "" delim))))))
ac59aed8
RS
3541
3542\f
3543;; various other commands
3544
133693bc
KH
3545(autoload 'comint-dynamic-complete "comint"
3546 "Dynamically perform completion at point." t)
3547
3548(autoload 'shell-dynamic-complete-command "shell"
3549 "Dynamically complete the command at point." t)
3550
ac59aed8
RS
3551(autoload 'comint-dynamic-complete-filename "comint"
3552 "Dynamically complete the filename at point." t)
3553
133693bc
KH
3554(autoload 'shell-dynamic-complete-environment-variable "shell"
3555 "Dynamically complete the environment variable at point." t)
3556
ac59aed8
RS
3557
3558
cd76025c
KH
3559(defun sh-newline-and-indent ()
3560 "Strip unquoted whitespace, insert newline, and indent like current line."
3561 (interactive "*")
3562 (indent-to (prog1 (current-indentation)
3563 (delete-region (point)
3564 (progn
3565 (or (zerop (skip-chars-backward " \t"))
3566 (if (sh-quoted-p)
3567 (forward-char)))
3568 (point)))
3569 (newline))))
ac59aed8 3570
ac59aed8
RS
3571(defun sh-beginning-of-command ()
3572 "Move point to successive beginnings of commands."
3573 (interactive)
3574 (if (re-search-backward sh-beginning-of-command nil t)
3575 (goto-char (match-beginning 2))))
3576
ac59aed8
RS
3577(defun sh-end-of-command ()
3578 "Move point to successive ends of commands."
3579 (interactive)
3580 (if (re-search-forward sh-end-of-command nil t)
3581 (goto-char (match-end 1))))
3582
bdd5fa99
RS
3583;; Backslashification. Stolen from make-mode.el.
3584
3585(defun sh-backslash-region (from to delete-flag)
3586 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3587With no argument, inserts backslashes and aligns existing backslashes.
3588With an argument, deletes the backslashes.
3589
3590This function does not modify the last line of the region if the region ends
3591right at the start of the following line; it does not modify blank lines
546e2f6f 3592at the start of the region. So you can put the region around an entire
bdd5fa99
RS
3593shell command and conveniently use this command."
3594 (interactive "r\nP")
3595 (save-excursion
3596 (goto-char from)
3597 (let ((column sh-backslash-column)
3598 (endmark (make-marker)))
3599 (move-marker endmark to)
3600 ;; Compute the smallest column number past the ends of all the lines.
3601 (if sh-backslash-align
3602 (progn
3603 (if (not delete-flag)
3604 (while (< (point) to)
3605 (end-of-line)
3606 (if (= (preceding-char) ?\\)
3607 (progn (forward-char -1)
3608 (skip-chars-backward " \t")))
3609 (setq column (max column (1+ (current-column))))
3610 (forward-line 1)))
3611 ;; Adjust upward to a tab column, if that doesn't push
3612 ;; past the margin.
3613 (if (> (% column tab-width) 0)
3614 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
3615 tab-width)))
3616 (if (< adjusted (window-width))
3617 (setq column adjusted))))))
3618 ;; Don't modify blank lines at start of region.
3619 (goto-char from)
3620 (while (and (< (point) endmark) (eolp))
3621 (forward-line 1))
3622 ;; Add or remove backslashes on all the lines.
3623 (while (and (< (point) endmark)
3624 ;; Don't backslashify the last line
3625 ;; if the region ends right at the start of the next line.
3626 (save-excursion
3627 (forward-line 1)
3628 (< (point) endmark)))
3629 (if (not delete-flag)
3630 (sh-append-backslash column)
3631 (sh-delete-backslash))
3632 (forward-line 1))
3633 (move-marker endmark nil))))
3634
3635(defun sh-append-backslash (column)
3636 (end-of-line)
3637 ;; Note that "\\\\" is needed to get one backslash.
3638 (if (= (preceding-char) ?\\)
3639 (progn (forward-char -1)
3640 (delete-horizontal-space)
3641 (indent-to column (if sh-backslash-align nil 1)))
3642 (indent-to column (if sh-backslash-align nil 1))
3643 (insert "\\")))
3644
3645(defun sh-delete-backslash ()
3646 (end-of-line)
3647 (or (bolp)
3648 (progn
3649 (forward-char -1)
3650 (if (looking-at "\\\\")
3651 (delete-region (1+ (point))
3652 (progn (skip-chars-backward " \t") (point)))))))
3653
f7c7053e 3654(provide 'sh-script)
43c89a96 3655
67b9b71f 3656;; arch-tag: eccd8b72-f337-4fc2-ae86-18155a69d937
f964dfcb 3657;;; sh-script.el ends here