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