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