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