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