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