c57468bf52ffba3fb15781b40a3cb830fa9fad0f
[bpt/emacs.git] / 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-arithmetic-expression (pos)
944 (save-excursion
945 (let ((ppss (syntax-ppss pos)))
946 (when (nth 1 ppss)
947 (goto-char (nth 1 ppss))
948 (and (eq ?\( (char-after))
949 (eq ?\( (char-before))
950 (eq ?\$ (char-before (1- (point)))))))))
951
952 (defun sh-font-lock-open-heredoc (start string eol)
953 "Determine the syntax of the \\n after a <<EOF.
954 START is the position of <<.
955 STRING is the actual word used as delimiter (e.g. \"EOF\").
956 INDENTED is non-nil if the here document's content (and the EOF mark) can
957 be indented (i.e. a <<- was used rather than just <<).
958 Point is at the beginning of the next line."
959 (unless (or (memq (char-before start) '(?< ?>))
960 (sh-in-comment-or-string start)
961 (sh--inside-arithmetic-expression start))
962 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
963 ;; font-lock keywords to detect the end of this here document.
964 (let ((str (replace-regexp-in-string "['\"]" "" string))
965 (ppss (save-excursion (syntax-ppss eol))))
966 (if (nth 4 ppss)
967 ;; The \n not only starts the heredoc but also closes a comment.
968 ;; Let's close the comment just before the \n.
969 (put-text-property (1- eol) eol 'syntax-table '(12))) ;">"
970 (if (or (nth 5 ppss) (> (count-lines start eol) 1))
971 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
972 ;; several lines, make sure we refontify them together.
973 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
974 ;; escaped), it means the right \n is actually further down.
975 ;; Don't bother fixing it now, but place a multiline property so
976 ;; that when jit-lock-context-* refontifies the rest of the
977 ;; buffer, it also refontifies the current line with it.
978 (put-text-property start (1+ eol) 'syntax-multiline t))
979 (put-text-property eol (1+ eol) 'sh-here-doc-marker str)
980 (prog1 sh-here-doc-syntax
981 (goto-char (+ 2 start))))))
982
983 (defun sh-syntax-propertize-here-doc (end)
984 (let ((ppss (syntax-ppss)))
985 (when (eq t (nth 3 ppss))
986 (let ((key (get-text-property (nth 8 ppss) 'sh-here-doc-marker))
987 (case-fold-search nil))
988 (when (re-search-forward
989 (concat "^\\([ \t]*\\)" (regexp-quote key) "\\(\n\\)")
990 end 'move)
991 (let ((eol (match-beginning 2)))
992 (put-text-property eol (1+ eol)
993 'syntax-table sh-here-doc-syntax)))))))
994
995 (defun sh-font-lock-quoted-subshell (limit)
996 "Search for a subshell embedded in a string.
997 Find all the unescaped \" characters within said subshell, remembering that
998 subshells can nest."
999 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
1000 ;; effort to handle multiline cases correctly, so it ends up being
1001 ;; rather flaky.
1002 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1003 ;; bingo we have a $( or a ` inside a ""
1004 (let (;; `state' can be: double-quote, backquote, code.
1005 (state (if (eq (char-before) ?`) 'backquote 'code))
1006 ;; Stacked states in the context.
1007 (states '(double-quote)))
1008 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1009 (< (point) limit)))
1010 ;; unescape " inside a $( ... ) construct.
1011 (pcase (char-after)
1012 (?\' (pcase state
1013 (`double-quote nil)
1014 (_ (forward-char 1) (skip-chars-forward "^'" limit))))
1015 (?\\ (forward-char 1))
1016 (?\" (pcase state
1017 (`double-quote (setq state (pop states)))
1018 (_ (push state states) (setq state 'double-quote)))
1019 (if state (put-text-property (point) (1+ (point))
1020 'syntax-table '(1))))
1021 (?\` (pcase state
1022 (`backquote (setq state (pop states)))
1023 (_ (push state states) (setq state 'backquote))))
1024 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1025 nil
1026 (forward-char 1)
1027 (pcase state
1028 (_ (push state states) (setq state 'code)))))
1029 (?\( (pcase state
1030 (`double-quote nil)
1031 (_ (push state states) (setq state 'code))))
1032 (?\) (pcase state
1033 (`double-quote nil)
1034 (_ (setq state (pop states)))))
1035 (_ (error "Internal error in sh-font-lock-quoted-subshell")))
1036 (forward-char 1)))))
1037
1038
1039 (defun sh-is-quoted-p (pos)
1040 (and (eq (char-before pos) ?\\)
1041 (not (sh-is-quoted-p (1- pos)))))
1042
1043 (defun sh-font-lock-paren (start)
1044 (unless (nth 8 (syntax-ppss))
1045 (save-excursion
1046 (let ((open nil))
1047 (goto-char start)
1048 ;; Skip through all patterns
1049 (while
1050 (progn
1051 (while
1052 (progn
1053 (forward-comment (- (point-max)))
1054 (when (and (eolp) (sh-is-quoted-p (point)))
1055 (forward-char -1)
1056 t)))
1057 ;; Skip through one pattern
1058 (while
1059 (or (/= 0 (skip-syntax-backward "w_"))
1060 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1061 (and (sh-is-quoted-p (1- (point)))
1062 (goto-char (- (point) 2)))
1063 (when (memq (char-before) '(?\" ?\' ?\}))
1064 (condition-case nil (progn (backward-sexp 1) t)
1065 (error nil)))))
1066 ;; Patterns can be preceded by an open-paren (bug#1320).
1067 (when (eq (char-before (point)) ?\()
1068 (backward-char 1)
1069 (setq open (point)))
1070 (while (progn
1071 (forward-comment (- (point-max)))
1072 ;; Maybe we've bumped into an escaped newline.
1073 (sh-is-quoted-p (point)))
1074 (backward-char 1))
1075 (when (eq (char-before) ?|)
1076 (backward-char 1) t)))
1077 (and (> (point) (1+ (point-min)))
1078 (progn (backward-char 2)
1079 (if (> start (line-end-position))
1080 (put-text-property (point) (1+ start)
1081 'syntax-multiline t))
1082 ;; FIXME: The `in' may just be a random argument to
1083 ;; a normal command rather than the real `in' keyword.
1084 ;; I.e. we should look back to try and find the
1085 ;; corresponding `case'.
1086 (and (looking-at ";[;&]\\|\\_<in")
1087 ;; ";; esac )" is a case that looks
1088 ;; like a case-pattern but it's really just a close
1089 ;; paren after a case statement. I.e. if we skipped
1090 ;; over `esac' just now, we're not looking
1091 ;; at a case-pattern.
1092 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1093 (progn
1094 (when open
1095 (put-text-property open (1+ open) 'syntax-table sh-st-punc))
1096 sh-st-punc))))))
1097
1098 (defun sh-font-lock-backslash-quote ()
1099 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1100 ;; In a '...' the backslash is not escaping.
1101 sh-st-punc
1102 nil))
1103
1104 (defun sh-syntax-propertize-function (start end)
1105 (goto-char start)
1106 (sh-syntax-propertize-here-doc end)
1107 (funcall
1108 (syntax-propertize-rules
1109 (sh-here-doc-open-re
1110 (2 (sh-font-lock-open-heredoc
1111 (match-beginning 0) (match-string 1) (match-beginning 2))))
1112 ("\\s|" (0 (prog1 nil (sh-syntax-propertize-here-doc end))))
1113 ;; A `#' begins a comment when it is unquoted and at the
1114 ;; beginning of a word. In the shell, words are separated by
1115 ;; metacharacters. The list of special chars is taken from
1116 ;; the single-unix spec of the shell command language (under
1117 ;; `quoting') but with `$' removed.
1118 ("\\(?:[^|&;<>()`\\\"' \t\n]\\|\\${\\)\\(#+\\)" (1 "_"))
1119 ;; In a '...' the backslash is not escaping.
1120 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1121 ;; Make sure $@ and $? are correctly recognized as sexps.
1122 ("\\$\\([?@]\\)" (1 "_"))
1123 ;; Distinguish the special close-paren in `case'.
1124 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1125 ;; Highlight (possibly nested) subshells inside "" quoted
1126 ;; regions correctly.
1127 ("\"\\(?:\\(?:[^\\\"]\\|\\\\.\\)*?\\)??\\(\\$(\\|`\\)"
1128 (1 (ignore
1129 (if (nth 8 (save-excursion (syntax-ppss (match-beginning 0))))
1130 (goto-char (1+ (match-beginning 0)))
1131 ;; Save excursion because we want to also apply other
1132 ;; syntax-propertize rules within the affected region.
1133 (save-excursion
1134 (sh-font-lock-quoted-subshell end)))))))
1135 (point) end))
1136 (defun sh-font-lock-syntactic-face-function (state)
1137 (let ((q (nth 3 state)))
1138 (if q
1139 (if (characterp q)
1140 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1141 sh-heredoc-face)
1142 font-lock-comment-face)))
1143
1144 (defgroup sh-indentation nil
1145 "Variables controlling indentation in shell scripts.
1146
1147 Note: customizing these variables will not affect existing buffers if
1148 `sh-make-vars-local' is non-nil. See the documentation for
1149 variable `sh-make-vars-local', command `sh-make-vars-local'
1150 and command `sh-reset-indent-vars-to-global-values'."
1151 :group 'sh-script)
1152
1153
1154 (defcustom sh-set-shell-hook nil
1155 "Hook run by `sh-set-shell'."
1156 :type 'hook
1157 :group 'sh-script)
1158
1159 (defcustom sh-mode-hook nil
1160 "Hook run by `sh-mode'."
1161 :type 'hook
1162 :group 'sh-script)
1163
1164 (defcustom sh-learn-basic-offset nil
1165 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1166
1167 nil mean: never.
1168 t means: only if there seems to be an obvious value.
1169 Anything else means: whenever we have a \"good guess\" as to the value."
1170 :type '(choice
1171 (const :tag "Never" nil)
1172 (const :tag "Only if sure" t)
1173 (const :tag "If have a good guess" usually))
1174 :group 'sh-indentation)
1175
1176 (defcustom sh-popup-occur-buffer nil
1177 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1178 If t it is always shown. If nil, it is shown only when there
1179 are conflicts."
1180 :type '(choice
1181 (const :tag "Only when there are conflicts." nil)
1182 (const :tag "Always" t))
1183 :group 'sh-indentation)
1184
1185 (defcustom sh-blink t
1186 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1187 The position on the line is not necessarily meaningful.
1188 In some cases the line will be the matching keyword, but this is not
1189 always the case."
1190 :type 'boolean
1191 :group 'sh-indentation)
1192
1193 (defcustom sh-first-lines-indent 0
1194 "The indentation of the first non-blank non-comment line.
1195 Usually 0 meaning first column.
1196 Can be set to a number, or to nil which means leave it as is."
1197 :type '(choice
1198 (const :tag "Leave as is" nil)
1199 (integer :tag "Column number"
1200 :menu-tag "Indent to this col (0 means first col)" ))
1201 :group 'sh-indentation)
1202
1203
1204 (defcustom sh-basic-offset 4
1205 "The default indentation increment.
1206 This value is used for the `+' and `-' symbols in an indentation variable."
1207 :type 'integer
1208 :group 'sh-indentation)
1209 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1210
1211 (defcustom sh-indent-comment t
1212 "How a comment line is to be indented.
1213 nil means leave it as it is;
1214 t means indent it as a normal line, aligning it to previous non-blank
1215 non-comment line;
1216 a number means align to that column, e.g. 0 means first column."
1217 :type '(choice
1218 (const :tag "Leave as is." nil)
1219 (const :tag "Indent as a normal line." t)
1220 (integer :menu-tag "Indent to this col (0 means first col)."
1221 :tag "Indent to column number.") )
1222 :version "24.3"
1223 :group 'sh-indentation)
1224
1225
1226 (defvar sh-debug nil
1227 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1228
1229
1230 ;; Uncomment this defun and comment the defmacro for debugging.
1231 ;; (defun sh-debug (&rest args)
1232 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1233 ;; (if sh-debug
1234 ;; (apply 'message args)))
1235 (defmacro sh-debug (&rest _args))
1236
1237 (defconst sh-symbol-list
1238 '((const :tag "+ " :value +
1239 :menu-tag "+ Indent right by sh-basic-offset")
1240 (const :tag "- " :value -
1241 :menu-tag "- Indent left by sh-basic-offset")
1242 (const :tag "++" :value ++
1243 :menu-tag "++ Indent right twice sh-basic-offset")
1244 (const :tag "--" :value --
1245 :menu-tag "-- Indent left twice sh-basic-offset")
1246 (const :tag "* " :value *
1247 :menu-tag "* Indent right half sh-basic-offset")
1248 (const :tag "/ " :value /
1249 :menu-tag "/ Indent left half sh-basic-offset")))
1250
1251 (defcustom sh-indent-for-else 0
1252 "How much to indent an `else' relative to its `if'. Usually 0."
1253 :type `(choice
1254 (integer :menu-tag "A number (positive=>indent right)"
1255 :tag "A number")
1256 (const :tag "--") ;; separator!
1257 ,@ sh-symbol-list
1258 )
1259 :group 'sh-indentation)
1260
1261 (defconst sh-number-or-symbol-list
1262 (append '((integer :menu-tag "A number (positive=>indent right)"
1263 :tag "A number")
1264 (const :tag "--")) ; separator
1265 sh-symbol-list))
1266
1267 (defcustom sh-indent-for-fi 0
1268 "How much to indent a `fi' relative to its `if'. Usually 0."
1269 :type `(choice ,@ sh-number-or-symbol-list )
1270 :group 'sh-indentation)
1271
1272 (defcustom sh-indent-for-done 0
1273 "How much to indent a `done' relative to its matching stmt. Usually 0."
1274 :type `(choice ,@ sh-number-or-symbol-list )
1275 :group 'sh-indentation)
1276
1277 (defcustom sh-indent-after-else '+
1278 "How much to indent a statement after an `else' statement."
1279 :type `(choice ,@ sh-number-or-symbol-list )
1280 :group 'sh-indentation)
1281
1282 (defcustom sh-indent-after-if '+
1283 "How much to indent a statement after an `if' statement.
1284 This includes lines after `else' and `elif' statements, too, but
1285 does not affect the `else', `elif' or `fi' statements themselves."
1286 :type `(choice ,@ sh-number-or-symbol-list )
1287 :group 'sh-indentation)
1288
1289 (defcustom sh-indent-for-then 0
1290 "How much to indent a `then' relative to its `if'."
1291 :type `(choice ,@ sh-number-or-symbol-list )
1292 :group 'sh-indentation)
1293
1294 (defcustom sh-indent-for-do 0
1295 "How much to indent a `do' statement.
1296 This is relative to the statement before the `do', typically a
1297 `while', `until', `for', `repeat' or `select' statement."
1298 :type `(choice ,@ sh-number-or-symbol-list)
1299 :group 'sh-indentation)
1300
1301 (defcustom sh-indent-after-do '+
1302 "How much to indent a line after a `do' statement.
1303 This is used when the `do' is the first word of the line.
1304 This is relative to the statement before the `do', typically a
1305 `while', `until', `for', `repeat' or `select' statement."
1306 :type `(choice ,@ sh-number-or-symbol-list)
1307 :group 'sh-indentation)
1308
1309 (defcustom sh-indent-after-loop-construct '+
1310 "How much to indent a statement after a loop construct.
1311
1312 This variable is used when the keyword `do' is on the same line as the
1313 loop statement (e.g., `until', `while' or `for').
1314 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1315 :type `(choice ,@ sh-number-or-symbol-list)
1316 :group 'sh-indentation)
1317
1318
1319 (defcustom sh-indent-after-done 0
1320 "How much to indent a statement after a `done' keyword.
1321 Normally this is 0, which aligns the `done' to the matching
1322 looping construct line.
1323 Setting it non-zero allows you to have the `do' statement on a line
1324 by itself and align the done under to do."
1325 :type `(choice ,@ sh-number-or-symbol-list)
1326 :group 'sh-indentation)
1327
1328 (defcustom sh-indent-for-case-label '+
1329 "How much to indent a case label statement.
1330 This is relative to the line containing the `case' statement."
1331 :type `(choice ,@ sh-number-or-symbol-list)
1332 :group 'sh-indentation)
1333
1334 (defcustom sh-indent-for-case-alt '++
1335 "How much to indent statements after the case label.
1336 This is relative to the line containing the `case' statement."
1337 :type `(choice ,@ sh-number-or-symbol-list)
1338 :group 'sh-indentation)
1339
1340
1341 (defcustom sh-indent-for-continuation '+
1342 "How much to indent for a continuation statement."
1343 :type `(choice ,@ sh-number-or-symbol-list)
1344 :group 'sh-indentation)
1345
1346 (defcustom sh-indent-after-open '+
1347 "How much to indent after a line with an opening parenthesis or brace.
1348 For an open paren after a function, `sh-indent-after-function' is used."
1349 :type `(choice ,@ sh-number-or-symbol-list)
1350 :group 'sh-indentation)
1351
1352 (defcustom sh-indent-after-function '+
1353 "How much to indent after a function line."
1354 :type `(choice ,@ sh-number-or-symbol-list)
1355 :group 'sh-indentation)
1356
1357 ;; These 2 are for the rc shell:
1358
1359 (defcustom sh-indent-after-switch '+
1360 "How much to indent a `case' statement relative to the `switch' statement.
1361 This is for the rc shell."
1362 :type `(choice ,@ sh-number-or-symbol-list)
1363 :group 'sh-indentation)
1364
1365 (defcustom sh-indent-after-case '+
1366 "How much to indent a statement relative to the `case' statement.
1367 This is for the rc shell."
1368 :type `(choice ,@ sh-number-or-symbol-list)
1369 :group 'sh-indentation)
1370
1371 (defcustom sh-backslash-column 48
1372 "Column in which `sh-backslash-region' inserts backslashes."
1373 :type 'integer
1374 :group 'sh)
1375
1376 (defcustom sh-backslash-align t
1377 "If non-nil, `sh-backslash-region' will align backslashes."
1378 :type 'boolean
1379 :group 'sh)
1380
1381 ;; Internal use - not designed to be changed by the user:
1382
1383 (defun sh-mkword-regexpr (word)
1384 "Make a regexp which matches WORD as a word.
1385 This specifically excludes an occurrence of WORD followed by
1386 punctuation characters like '-'."
1387 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1388
1389 (defconst sh-re-done (sh-mkword-regexpr "done"))
1390
1391
1392 (defconst sh-kws-for-done
1393 '((sh . ( "while" "until" "for" ) )
1394 (bash . ( "while" "until" "for" "select" ) )
1395 (ksh88 . ( "while" "until" "for" "select" ) )
1396 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1397 "Which keywords can match the word `done' in this shell.")
1398
1399
1400 (defconst sh-indent-supported
1401 '((sh . sh)
1402 (csh . nil)
1403 (rc . rc))
1404 "Indentation rule set to use for each shell type.")
1405
1406 (defvar sh-indent-supported-here nil
1407 "Non-nil if we support indentation for the current buffer's shell type.")
1408
1409 (defconst sh-var-list
1410 '(
1411 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1412 sh-indent-after-do sh-indent-after-done
1413 sh-indent-after-else
1414 sh-indent-after-if
1415 sh-indent-after-loop-construct
1416 sh-indent-after-open
1417 sh-indent-comment
1418 sh-indent-for-case-alt
1419 sh-indent-for-case-label
1420 sh-indent-for-continuation
1421 sh-indent-for-do
1422 sh-indent-for-done
1423 sh-indent-for-else
1424 sh-indent-for-fi
1425 sh-indent-for-then
1426 )
1427 "A list of variables used by script mode to control indentation.
1428 This list is used when switching between buffer-local and global
1429 values of variables, and for the commands using indentation styles.")
1430
1431 (defvar sh-make-vars-local t
1432 "Controls whether indentation variables are local to the buffer.
1433 If non-nil, indentation variables are made local initially.
1434 If nil, you can later make the variables local by invoking
1435 command `sh-make-vars-local'.
1436 The default is t because I assume that in one Emacs session one is
1437 frequently editing existing scripts with different styles.")
1438
1439 \f
1440 ;; mode-command and utility functions
1441
1442 ;;;###autoload
1443 (define-derived-mode sh-mode prog-mode "Shell-script"
1444 "Major mode for editing shell scripts.
1445 This mode works for many shells, since they all have roughly the same syntax,
1446 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1447 Unless the file's magic number indicates the shell, your usual shell is
1448 assumed. Since filenames rarely give a clue, they are not further analyzed.
1449
1450 This mode adapts to the variations between shells (see `sh-set-shell') by
1451 means of an inheritance based feature lookup (see `sh-feature'). This
1452 mechanism applies to all variables (including skeletons) that pertain to
1453 shell-specific features.
1454
1455 The default style of this mode is that of Rosenblatt's Korn shell book.
1456 The syntax of the statements varies with the shell being used. The
1457 following commands are available, based on the current shell's syntax:
1458 \\<sh-mode-map>
1459 \\[sh-case] case statement
1460 \\[sh-for] for loop
1461 \\[sh-function] function definition
1462 \\[sh-if] if statement
1463 \\[sh-indexed-loop] indexed loop from 1 to n
1464 \\[sh-while-getopts] while getopts loop
1465 \\[sh-repeat] repeat loop
1466 \\[sh-select] select loop
1467 \\[sh-until] until loop
1468 \\[sh-while] while loop
1469
1470 For sh and rc shells indentation commands are:
1471 \\[sh-show-indent] Show the variable controlling this line's indentation.
1472 \\[sh-set-indent] Set then variable controlling this line's indentation.
1473 \\[sh-learn-line-indent] Change the indentation variable so this line
1474 would indent to the way it currently is.
1475 \\[sh-learn-buffer-indent] Set the indentation variables so the
1476 buffer indents as it currently is indented.
1477
1478
1479 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1480 \\[newline-and-indent] Delete unquoted space and indent new line same as this one.
1481 \\[sh-end-of-command] Go to end of successive commands.
1482 \\[sh-beginning-of-command] Go to beginning of successive commands.
1483 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1484 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1485
1486 `sh-electric-here-document-mode' controls whether insertion of two
1487 unquoted < insert a here document.
1488
1489 If you generally program a shell different from your login shell you can
1490 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1491 indicate what shell it is use `sh-alias-alist' to translate.
1492
1493 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1494 with your script for an edit-interpret-debug cycle."
1495 (make-local-variable 'sh-shell-file)
1496 (make-local-variable 'sh-shell)
1497
1498 (set (make-local-variable 'skeleton-pair-default-alist)
1499 sh-skeleton-pair-default-alist)
1500 (set (make-local-variable 'skeleton-end-hook)
1501 (lambda () (or (eolp) (newline) (indent-relative))))
1502
1503 (set (make-local-variable 'paragraph-start) (concat page-delimiter "\\|$"))
1504 (set (make-local-variable 'paragraph-separate) paragraph-start)
1505 (set (make-local-variable 'comment-start) "# ")
1506 (set (make-local-variable 'comment-start-skip) "#+[\t ]*")
1507 (set (make-local-variable 'local-abbrev-table) sh-mode-abbrev-table)
1508 (set (make-local-variable 'comint-dynamic-complete-functions)
1509 sh-dynamic-complete-functions)
1510 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t)
1511 ;; we can't look if previous line ended with `\'
1512 (set (make-local-variable 'comint-prompt-regexp) "^[ \t]*")
1513 (set (make-local-variable 'imenu-case-fold-search) nil)
1514 (set (make-local-variable 'font-lock-defaults)
1515 `((sh-font-lock-keywords
1516 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1517 nil nil
1518 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1519 (font-lock-syntactic-face-function
1520 . sh-font-lock-syntactic-face-function)))
1521 (set (make-local-variable 'syntax-propertize-function)
1522 #'sh-syntax-propertize-function)
1523 (add-hook 'syntax-propertize-extend-region-functions
1524 #'syntax-propertize-multiline 'append 'local)
1525 (sh-electric-here-document-mode 1)
1526 (set (make-local-variable 'skeleton-pair-alist) '((?` _ ?`)))
1527 (set (make-local-variable 'skeleton-pair-filter-function) 'sh-quoted-p)
1528 (set (make-local-variable 'skeleton-further-elements)
1529 '((< '(- (min sh-indentation (current-column))))))
1530 (set (make-local-variable 'skeleton-filter-function) 'sh-feature)
1531 (set (make-local-variable 'skeleton-newline-indent-rigidly) t)
1532 (set (make-local-variable 'defun-prompt-regexp)
1533 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1534 ;; Parse or insert magic number for exec, and set all variables depending
1535 ;; on the shell thus determined.
1536 (sh-set-shell
1537 (cond ((save-excursion
1538 (goto-char (point-min))
1539 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1540 (match-string 2))
1541 ((not buffer-file-name) sh-shell-file)
1542 ;; Checks that use `buffer-file-name' follow.
1543 ((string-match "\\.m?spec\\'" buffer-file-name) "rpm")
1544 ((string-match "[.]sh\\>" buffer-file-name) "sh")
1545 ((string-match "[.]bash\\>" buffer-file-name) "bash")
1546 ((string-match "[.]ksh\\>" buffer-file-name) "ksh")
1547 ((string-match "[.]csh\\>" buffer-file-name) "csh")
1548 ((equal (file-name-nondirectory buffer-file-name) ".profile") "sh")
1549 (t sh-shell-file))
1550 nil nil))
1551
1552 ;;;###autoload
1553 (defalias 'shell-script-mode 'sh-mode)
1554
1555
1556 (defun sh-font-lock-keywords (&optional keywords)
1557 "Function to get simple fontification based on `sh-font-lock-keywords'.
1558 This adds rules for comments and assignments."
1559 (sh-feature sh-font-lock-keywords-var
1560 (when (stringp (sh-feature sh-assignment-regexp))
1561 (lambda (list)
1562 `((,(sh-feature sh-assignment-regexp)
1563 1 font-lock-variable-name-face)
1564 ,@keywords
1565 ,@list
1566 ,@executable-font-lock-keywords)))))
1567
1568 (defun sh-font-lock-keywords-1 (&optional builtins)
1569 "Function to get better fontification including keywords."
1570 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1571 (regexp-opt (sh-feature sh-leading-keywords) t)
1572 "[ \t]+\\)?"
1573 (regexp-opt (append (sh-feature sh-leading-keywords)
1574 (sh-feature sh-other-keywords))
1575 t))))
1576 (sh-font-lock-keywords
1577 `(,@(if builtins
1578 `((,(concat keywords "[ \t]+\\)?"
1579 (regexp-opt (sh-feature sh-builtins) t)
1580 "\\>")
1581 (2 font-lock-keyword-face nil t)
1582 (6 font-lock-builtin-face))
1583 ,@(sh-feature sh-font-lock-keywords-var-2)))
1584 (,(concat keywords "\\)\\>")
1585 2 font-lock-keyword-face)
1586 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1587
1588 (defun sh-font-lock-keywords-2 ()
1589 "Function to get better fontification including keywords and builtins."
1590 (sh-font-lock-keywords-1 t))
1591
1592 ;;; Indentation and navigation with SMIE.
1593
1594 (require 'smie)
1595
1596 ;; The SMIE code should generally be preferred, but it currently does not obey
1597 ;; the various indentation custom-vars, and it misses some important features
1598 ;; of the old code, mostly: sh-learn-line/buffer-indent, sh-show-indent,
1599 ;; sh-name/save/load-style.
1600 (defvar sh-use-smie nil
1601 "Whether to use the SMIE code for navigation and indentation.")
1602
1603 (defun sh-smie--keyword-p (tok)
1604 "Non-nil if TOK (at which we're looking) really is a keyword."
1605 (let ((prev (funcall smie-backward-token-function)))
1606 (if (zerop (length prev))
1607 (looking-back "\\s(" (1- (point)))
1608 (assoc prev smie-grammar))))
1609
1610 (defun sh-smie--newline-semi-p (&optional tok)
1611 "Return non-nil if a newline should be treated as a semi-colon.
1612 Here we assume that a newline should be treated as a semi-colon unless it
1613 comes right after a special keyword.
1614 This function does not pay attention to line-continuations.
1615 If TOK is nil, point should be before the newline; otherwise, TOK is the token
1616 before the newline and in that case point should be just before the token."
1617 (save-excursion
1618 (unless tok
1619 (setq tok (funcall smie-backward-token-function)))
1620 (if (and (zerop (length tok))
1621 (looking-back "\\s(" (1- (point))))
1622 nil
1623 (not (numberp (nth 2 (assoc tok smie-grammar)))))))
1624
1625 ;;;; SMIE support for `sh'.
1626
1627 (defconst sh-smie-sh-grammar
1628 (smie-prec2->grammar
1629 (smie-bnf->prec2
1630 '((exp) ;A constant, or a $var, or a sequence of them...
1631 (cmd ("case" exp "in" branches "esac")
1632 ("if" cmd "then" cmd "fi")
1633 ("if" cmd "then" cmd "else" cmd "fi")
1634 ("if" cmd "then" cmd "elif" cmd "then" cmd "fi")
1635 ("if" cmd "then" cmd "elif" cmd "then" cmd "else" cmd "fi")
1636 ("if" cmd "then" cmd "elif" cmd "then" cmd
1637 "elif" cmd "then" cmd "else" cmd "fi")
1638 ("while" cmd "do" cmd "done")
1639 ("until" cmd "do" cmd "done")
1640 ("for" exp "in" cmd "do" cmd "done")
1641 ("for" exp "do" cmd "done")
1642 ("select" exp "in" cmd "do" cmd "done") ;bash&zsh&ksh88.
1643 ("repeat" exp "do" cmd "done") ;zsh.
1644 (exp "always" exp) ;zsh.
1645 (cmd "|" cmd) (cmd "|&" cmd)
1646 (cmd "&&" cmd) (cmd "||" cmd)
1647 (cmd ";" cmd) (cmd "&" cmd))
1648 (rpattern (rpattern "|" rpattern))
1649 (pattern (rpattern) ("case-(" rpattern))
1650 (branches (branches ";;" branches)
1651 (branches ";&" branches) (branches ";;&" branches) ;bash.
1652 (pattern "case-)" cmd)))
1653 '((assoc ";;" ";&" ";;&"))
1654 '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1655
1656 (defconst sh-smie--sh-operators
1657 (delq nil (mapcar (lambda (x)
1658 (setq x (car x))
1659 (and (stringp x)
1660 (not (string-match "\\`[a-z]" x))
1661 x))
1662 sh-smie-sh-grammar)))
1663
1664 (defconst sh-smie--sh-operators-re (regexp-opt sh-smie--sh-operators))
1665 (defconst sh-smie--sh-operators-back-re
1666 (concat "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*"
1667 "\\(" sh-smie--sh-operators-re "\\)"))
1668
1669 (defun sh-smie--sh-keyword-in-p ()
1670 "Assuming we're looking at \"in\", return non-nil if it's a keyword.
1671 Does not preserve point."
1672 (let ((forward-sexp-function nil)
1673 (words nil) ;We've seen words.
1674 (newline nil) ;We've seen newlines after the words.
1675 (res nil)
1676 prev)
1677 (while (not res)
1678 (setq prev (funcall smie-backward-token-function))
1679 (cond
1680 ((zerop (length prev))
1681 (if newline
1682 (progn (cl-assert words) (setq res 'word))
1683 (setq words t)
1684 (condition-case nil
1685 (forward-sexp -1)
1686 (scan-error (setq res 'unknown)))))
1687 ((equal prev ";")
1688 (if words (setq newline t)
1689 (setq res 'keyword)))
1690 ((member prev '("case" "for" "select")) (setq res 'keyword))
1691 ((assoc prev smie-grammar) (setq res 'word))
1692 (t
1693 (if newline
1694 (progn (cl-assert words) (setq res 'word))
1695 (setq words t)))))
1696 (eq res 'keyword)))
1697
1698 (defun sh-smie--sh-keyword-p (tok)
1699 "Non-nil if TOK (at which we're looking) really is a keyword."
1700 (if (equal tok "in")
1701 (sh-smie--sh-keyword-in-p)
1702 (sh-smie--keyword-p tok)))
1703
1704 (defun sh-smie-sh-forward-token ()
1705 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1706 (save-excursion
1707 (skip-chars-backward " \t")
1708 (not (bolp))))
1709 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1710 ;; Right before a here-doc.
1711 (let ((forward-sexp-function nil))
1712 (forward-sexp 1)
1713 ;; Pretend the here-document is a "newline representing a
1714 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1715 ";")
1716 (let ((semi (sh-smie--newline-semi-p)))
1717 (forward-line 1)
1718 (if semi ";"
1719 (sh-smie-sh-forward-token))))
1720 (forward-comment (point-max))
1721 (cond
1722 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1723 ((looking-at sh-smie--sh-operators-re)
1724 (goto-char (match-end 0))
1725 (let ((tok (match-string-no-properties 0)))
1726 (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1727 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1728 (forward-line 1))
1729 tok))
1730 (t
1731 (let* ((pos (point))
1732 (tok (smie-default-forward-token)))
1733 (cond
1734 ((equal tok ")") "case-)")
1735 ((equal tok "(") "case-(")
1736 ((and tok (string-match "\\`[a-z]" tok)
1737 (assoc tok smie-grammar)
1738 (not
1739 (save-excursion
1740 (goto-char pos)
1741 (sh-smie--sh-keyword-p tok))))
1742 " word ")
1743 (t tok)))))))
1744
1745 (defun sh-smie--looking-back-at-continuation-p ()
1746 (save-excursion
1747 (and (if (eq (char-before) ?\n) (progn (forward-char -1) t) (eolp))
1748 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1749 (line-beginning-position)))))
1750
1751 (defun sh-smie-sh-backward-token ()
1752 (let ((bol (line-beginning-position))
1753 pos tok)
1754 (forward-comment (- (point)))
1755 (cond
1756 ((and (bolp) (not (bobp))
1757 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1758 (not (nth 3 (syntax-ppss))))
1759 ;; Right after a here-document.
1760 (let ((forward-sexp-function nil))
1761 (forward-sexp -1)
1762 ;; Pretend the here-document is a "newline representing a
1763 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1764 ";"))
1765 ((< (point) bol)
1766 (cond
1767 ((sh-smie--looking-back-at-continuation-p)
1768 (forward-char -1)
1769 (funcall smie-backward-token-function))
1770 ((sh-smie--newline-semi-p) ";")
1771 (t (funcall smie-backward-token-function))))
1772 ((looking-back sh-smie--sh-operators-back-re
1773 (line-beginning-position) 'greedy)
1774 (goto-char (match-beginning 1))
1775 (match-string-no-properties 1))
1776 (t
1777 (let ((tok (smie-default-backward-token)))
1778 (cond
1779 ((equal tok ")") "case-)")
1780 ((equal tok "(") "case-(")
1781 ((and tok (string-match "\\`[a-z]" tok)
1782 (assoc tok smie-grammar)
1783 (not (save-excursion (sh-smie--sh-keyword-p tok))))
1784 " word ")
1785 (t tok)))))))
1786
1787 (defcustom sh-indent-after-continuation t
1788 "If non-nil, try to make sure text is indented after a line continuation."
1789 :version "24.3"
1790 :type 'boolean
1791 :group 'sh-indentation)
1792
1793 (defun sh-smie--continuation-start-indent ()
1794 "Return the initial indentation of a continued line.
1795 May return nil if the line should not be treated as continued."
1796 (save-excursion
1797 (forward-line -1)
1798 (unless (sh-smie--looking-back-at-continuation-p)
1799 (current-indentation))))
1800
1801 (defun sh-smie-sh-rules (kind token)
1802 (pcase (cons kind token)
1803 (`(:elem . basic) sh-indentation)
1804 (`(:after . "case-)") (or sh-indentation smie-indent-basic))
1805 ((and `(:before . ,_)
1806 (guard (when sh-indent-after-continuation
1807 (save-excursion
1808 (ignore-errors
1809 (skip-chars-backward " \t")
1810 (sh-smie--looking-back-at-continuation-p))))))
1811 ;; After a line-continuation, make sure the rest is indented.
1812 (let* ((sh-indent-after-continuation nil)
1813 (indent (smie-indent-calculate))
1814 (initial (sh-smie--continuation-start-indent)))
1815 (when (and (numberp indent) (numberp initial)
1816 (<= indent initial))
1817 `(column . ,(+ initial sh-indentation)))))
1818 (`(:before . ,(or `"(" `"{" `"["))
1819 (if (smie-rule-hanging-p) (smie-rule-parent)))
1820 ;; FIXME: Maybe this handling of ;; should be made into
1821 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
1822 (`(:before . ,(or `";;" `";&" `";;&"))
1823 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
1824 (cons 'column (smie-indent-keyword ";"))
1825 (smie-rule-separator kind)))
1826 (`(:after . ,(or `";;" `";&" `";;&"))
1827 (with-demoted-errors
1828 (smie-backward-sexp token)
1829 (cons 'column
1830 (if (or (smie-rule-bolp)
1831 (save-excursion
1832 (and (member (funcall smie-backward-token-function)
1833 '("in" ";;"))
1834 (smie-rule-bolp))))
1835 (current-column)
1836 (smie-indent-calculate)))))
1837 (`(:after . "|") (if (smie-rule-parent-p "|") nil 4))
1838 ))
1839
1840 ;; (defconst sh-smie-csh-grammar
1841 ;; (smie-prec2->grammar
1842 ;; (smie-bnf->prec2
1843 ;; '((exp) ;A constant, or a $var, or a sequence of them…
1844 ;; (elseifcmd (cmd)
1845 ;; (cmd "else" "else-if" exp "then" elseifcmd))
1846 ;; (cmd ("switch" branches "endsw")
1847 ;; ("if" exp)
1848 ;; ("if" exp "then" cmd "endif")
1849 ;; ("if" exp "then" cmd "else" cmd "endif")
1850 ;; ("if" exp "then" elseifcmd "endif")
1851 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
1852 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
1853 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
1854 ;; ;; "else" cmd "endif")
1855 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
1856 ;; ;; "else" "if" exp "then" cmd "endif")
1857 ;; ("while" cmd "end")
1858 ;; ("foreach" cmd "end")
1859 ;; (cmd "|" cmd) (cmd "|&" cmd)
1860 ;; (cmd "&&" cmd) (cmd "||" cmd)
1861 ;; (cmd ";" cmd) (cmd "&" cmd))
1862 ;; ;; This is a lie, but (combined with the corresponding disambiguation
1863 ;; ;; rule) it makes it more clear that `case' and `default' are the key
1864 ;; ;; separators and the `:' is a secondary tokens.
1865 ;; (branches (branches "case" branches)
1866 ;; (branches "default" branches)
1867 ;; (exp ":" branches)))
1868 ;; '((assoc "else" "then" "endif"))
1869 ;; '((assoc "case" "default") (nonassoc ":"))
1870 ;; '((assoc ";;" ";&" ";;&"))
1871 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1872
1873 ;;;; SMIE support for `rc'.
1874
1875 (defconst sh-smie-rc-grammar
1876 (smie-prec2->grammar
1877 (smie-bnf->prec2
1878 '((exp) ;A constant, or a $var, or a sequence of them...
1879 (cmd (cmd "case" cmd)
1880 ("if" exp)
1881 ("switch" exp)
1882 ("for" exp) ("while" exp)
1883 (cmd "|" cmd) (cmd "|&" cmd)
1884 (cmd "&&" cmd) (cmd "||" cmd)
1885 (cmd ";" cmd) (cmd "&" cmd))
1886 (pattern (pattern "|" pattern))
1887 (branches (branches ";;" branches)
1888 (branches ";&" branches) (branches ";;&" branches) ;bash.
1889 (pattern "case-)" cmd)))
1890 '((assoc ";;" ";&" ";;&"))
1891 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1892
1893 (defun sh-smie--rc-after-special-arg-p ()
1894 "Check if we're after the first arg of an if/while/for/... construct.
1895 Returns the construct's token and moves point before it, if so."
1896 (forward-comment (- (point)))
1897 (when (looking-back ")\\|\\_<not" (- (point) 3))
1898 (ignore-errors
1899 (let ((forward-sexp-function nil))
1900 (forward-sexp -1)
1901 (car (member (funcall smie-backward-token-function)
1902 '("if" "for" "switch" "while")))))))
1903
1904 (defun sh-smie--rc-newline-semi-p ()
1905 "Return non-nil if a newline should be treated as a semi-colon.
1906 Point should be before the newline."
1907 (save-excursion
1908 (let ((tok (funcall smie-backward-token-function)))
1909 (if (or (when (equal tok "not") (forward-word 1) t)
1910 (and (zerop (length tok)) (eq (char-before) ?\))))
1911 (not (sh-smie--rc-after-special-arg-p))
1912 (sh-smie--newline-semi-p tok)))))
1913
1914 (defun sh-smie-rc-forward-token ()
1915 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
1916 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1917 (save-excursion
1918 (skip-chars-backward " \t")
1919 (not (bolp))))
1920 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1921 ;; Right before a here-doc.
1922 (let ((forward-sexp-function nil))
1923 (forward-sexp 1)
1924 ;; Pretend the here-document is a "newline representing a
1925 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1926 ";")
1927 (let ((semi (sh-smie--rc-newline-semi-p)))
1928 (forward-line 1)
1929 (if semi ";"
1930 (sh-smie-rc-forward-token))))
1931 (forward-comment (point-max))
1932 (cond
1933 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
1934 ;; ((looking-at sh-smie--rc-operators-re)
1935 ;; (goto-char (match-end 0))
1936 ;; (let ((tok (match-string-no-properties 0)))
1937 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1938 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
1939 ;; (forward-line 1))
1940 ;; tok))
1941 (t
1942 (let* ((pos (point))
1943 (tok (smie-default-forward-token)))
1944 (cond
1945 ;; ((equal tok ")") "case-)")
1946 ((and tok (string-match "\\`[a-z]" tok)
1947 (assoc tok smie-grammar)
1948 (not
1949 (save-excursion
1950 (goto-char pos)
1951 (sh-smie--keyword-p tok))))
1952 " word ")
1953 (t tok)))))))
1954
1955 (defun sh-smie-rc-backward-token ()
1956 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
1957 (let ((bol (line-beginning-position))
1958 pos tok)
1959 (forward-comment (- (point)))
1960 (cond
1961 ((and (bolp) (not (bobp))
1962 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1963 (not (nth 3 (syntax-ppss))))
1964 ;; Right after a here-document.
1965 (let ((forward-sexp-function nil))
1966 (forward-sexp -1)
1967 ;; Pretend the here-document is a "newline representing a
1968 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1969 ";"))
1970 ((< (point) bol) ;We skipped over a newline.
1971 (cond
1972 ;; A continued line.
1973 ((and (eolp)
1974 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1975 (line-beginning-position)))
1976 (forward-char -1)
1977 (funcall smie-backward-token-function))
1978 ((sh-smie--rc-newline-semi-p) ";")
1979 (t (funcall smie-backward-token-function))))
1980 ;; ((looking-back sh-smie--sh-operators-back-re
1981 ;; (line-beginning-position) 'greedy)
1982 ;; (goto-char (match-beginning 1))
1983 ;; (match-string-no-properties 1))
1984 (t
1985 (let ((tok (smie-default-backward-token)))
1986 (cond
1987 ;; ((equal tok ")") "case-)")
1988 ((and tok (string-match "\\`[a-z]" tok)
1989 (assoc tok smie-grammar)
1990 (not (save-excursion (sh-smie--keyword-p tok))))
1991 " word ")
1992 (t tok)))))))
1993
1994 (defun sh-smie-rc-rules (kind token)
1995 (pcase (cons kind token)
1996 (`(:elem . basic) sh-indentation)
1997 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
1998 (`(:after . ";") (if (smie-rule-parent-p "case")
1999 (smie-rule-parent sh-indentation)))
2000 (`(:before . "{")
2001 (save-excursion
2002 (when (sh-smie--rc-after-special-arg-p)
2003 `(column . ,(current-column)))))
2004 (`(:before . ,(or `"(" `"{" `"["))
2005 (if (smie-rule-hanging-p) (smie-rule-parent)))
2006 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2007 ;; treated as an arg to (exp) by default, which indents it all wrong.
2008 ;; To handle it right, we should extend smie-indent-exps so that the
2009 ;; preceding keyword can give special rules. Currently the only special
2010 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2011 ;; with "(exp)", which is rarely the right thing to do, but is better
2012 ;; than nothing.
2013 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
2014 ))
2015
2016 ;;; End of SMIE code.
2017
2018 (defvar sh-regexp-for-done nil
2019 "A buffer-local regexp to match opening keyword for done.")
2020
2021 (defvar sh-kw-alist nil
2022 "A buffer-local, since it is shell-type dependent, list of keywords.")
2023
2024 ;; ( key-word first-on-this on-prev-line )
2025 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2026 ;; having 3 elements:
2027 ;; a keyword
2028 ;; a rule to check when the keyword appears on "this" line
2029 ;; a rule to check when the keyword appears on "the previous" line
2030 ;; The keyword is usually a string and is the first word on a line.
2031 ;; If this keyword appears on the line whose indentation is to be
2032 ;; calculated, the rule in element 2 is called. If this returns
2033 ;; non-zero, the resulting point (which may be changed by the rule)
2034 ;; is used as the default indentation.
2035 ;; If it returned false or the keyword was not found in the table,
2036 ;; then the keyword from the previous line is looked up and the rule
2037 ;; in element 3 is called. In this case, however,
2038 ;; `sh-get-indent-info' does not stop but may keep going and test
2039 ;; other keywords against rules in element 3. This is because the
2040 ;; preceding line could have, for example, an opening "if" and an
2041 ;; opening "while" keyword and we need to add the indentation offsets
2042 ;; for both.
2043 ;;
2044 (defconst sh-kw
2045 '((sh
2046 ("if" nil sh-handle-prev-if)
2047 ("elif" sh-handle-this-else sh-handle-prev-else)
2048 ("else" sh-handle-this-else sh-handle-prev-else)
2049 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2050 ("then" sh-handle-this-then sh-handle-prev-then)
2051 ("(" nil sh-handle-prev-open)
2052 ("{" nil sh-handle-prev-open)
2053 ("[" nil sh-handle-prev-open)
2054 ("}" sh-handle-this-close nil)
2055 (")" sh-handle-this-close nil)
2056 ("]" sh-handle-this-close nil)
2057 ("case" nil sh-handle-prev-case)
2058 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2059 (case-label nil sh-handle-after-case-label) ;; ???
2060 (";;" nil sh-handle-prev-case-alt-end) ;; ???
2061 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2062 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2063 ("done" sh-handle-this-done sh-handle-prev-done)
2064 ("do" sh-handle-this-do sh-handle-prev-do))
2065
2066 ;; Note: we don't need specific stuff for bash and zsh shells;
2067 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2068 ;; these shells use.
2069 (rc
2070 ("{" nil sh-handle-prev-open)
2071 ("}" sh-handle-this-close nil)
2072 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
2073
2074
2075
2076 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
2077 "Set this buffer's shell to SHELL (a string).
2078 When used interactively, insert the proper starting #!-line,
2079 and make the visited file executable via `executable-set-magic',
2080 perhaps querying depending on the value of `executable-query'.
2081
2082 When this function is called noninteractively, INSERT-FLAG (the third
2083 argument) controls whether to insert a #!-line and think about making
2084 the visited file executable, and NO-QUERY-FLAG (the second argument)
2085 controls whether to query about making the visited file executable.
2086
2087 Calls the value of `sh-set-shell-hook' if set."
2088 (interactive (list (completing-read (format "Shell \(default %s\): "
2089 sh-shell-file)
2090 interpreter-mode-alist
2091 (lambda (x) (eq (cdr x) 'sh-mode))
2092 nil nil nil sh-shell-file)
2093 (eq executable-query 'function)
2094 t))
2095 (if (string-match "\\.exe\\'" shell)
2096 (setq shell (substring shell 0 (match-beginning 0))))
2097 (setq sh-shell (intern (file-name-nondirectory shell))
2098 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
2099 sh-shell))
2100 (if insert-flag
2101 (setq sh-shell-file
2102 (executable-set-magic shell (sh-feature sh-shell-arg)
2103 no-query-flag insert-flag)))
2104 (setq mode-line-process (format "[%s]" sh-shell))
2105 (set (make-local-variable 'sh-shell-variables) nil)
2106 (set (make-local-variable 'sh-shell-variables-initialized) nil)
2107 (set (make-local-variable 'imenu-generic-expression)
2108 (sh-feature sh-imenu-generic-expression))
2109 (let ((tem (sh-feature sh-mode-syntax-table-input)))
2110 (when tem
2111 (set (make-local-variable 'sh-mode-syntax-table)
2112 (apply 'sh-mode-syntax-table tem))
2113 (set-syntax-table sh-mode-syntax-table)))
2114 (dolist (var (sh-feature sh-variables))
2115 (sh-remember-variable var))
2116 (if (set (make-local-variable 'sh-indent-supported-here)
2117 (sh-feature sh-indent-supported))
2118 (progn
2119 (message "Setting up indent for shell type %s" sh-shell)
2120 (if sh-use-smie
2121 (let ((mksym (lambda (name)
2122 (intern (format "sh-smie-%s-%s"
2123 sh-indent-supported-here name)))))
2124 (smie-setup (symbol-value (funcall mksym "grammar"))
2125 (funcall mksym "rules")
2126 :forward-token (funcall mksym "forward-token")
2127 :backward-token (funcall mksym "backward-token")))
2128 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2129 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
2130 (let ((regexp (sh-feature sh-kws-for-done)))
2131 (if regexp
2132 (set (make-local-variable 'sh-regexp-for-done)
2133 (sh-mkword-regexpr (regexp-opt regexp t)))))
2134 (message "setting up indent stuff")
2135 ;; sh-mode has already made indent-line-function local
2136 ;; but do it in case this is called before that.
2137 (set (make-local-variable 'indent-line-function) 'sh-indent-line))
2138 (if sh-make-vars-local
2139 (sh-make-vars-local))
2140 (message "Indentation setup for shell type %s" sh-shell))
2141 (message "No indentation for this shell type.")
2142 (setq indent-line-function 'sh-basic-indent-line))
2143 (when font-lock-mode
2144 (setq font-lock-set-defaults nil)
2145 (font-lock-set-defaults)
2146 (font-lock-fontify-buffer))
2147 (run-hooks 'sh-set-shell-hook))
2148
2149
2150 (defun sh-feature (alist &optional function)
2151 "Index ALIST by the current shell.
2152 If ALIST isn't a list where every element is a cons, it is returned as is.
2153 Else indexing follows an inheritance logic which works in two ways:
2154
2155 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2156 the alist contains no value for the current shell.
2157 The ultimate default is always `sh'.
2158
2159 - If the value thus looked up is a list starting with `sh-append',
2160 we call the function `sh-append' with the rest of the list as
2161 arguments, and use the value. However, the next element of the
2162 list is not used as-is; instead, we look it up recursively
2163 in ALIST to allow the function called to define the value for
2164 one shell to be derived from another shell.
2165 The value thus determined is physically replaced into the alist.
2166
2167 If FUNCTION is non-nil, it is called with one argument,
2168 the value thus obtained, and the result is used instead."
2169 (or (if (consp alist)
2170 ;; Check for something that isn't a valid alist.
2171 (let ((l alist))
2172 (while (and l (consp (car l)))
2173 (setq l (cdr l)))
2174 (if l alist)))
2175
2176 (let ((orig-sh-shell sh-shell))
2177 (let ((sh-shell sh-shell)
2178 elt val)
2179 (while (and sh-shell
2180 (not (setq elt (assq sh-shell alist))))
2181 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2182 ;; If the shell is not known, treat it as sh.
2183 (unless elt
2184 (setq elt (assq 'sh alist)))
2185 (setq val (cdr elt))
2186 (if (and (consp val)
2187 (memq (car val) '(sh-append sh-modify)))
2188 (setq val
2189 (apply (car val)
2190 ;; Refer to the value for a different shell,
2191 ;; as a kind of inheritance.
2192 (let ((sh-shell (car (cdr val))))
2193 (sh-feature alist))
2194 (cddr val))))
2195 (if function
2196 (setq sh-shell orig-sh-shell
2197 val (funcall function val)))
2198 val))))
2199
2200
2201
2202 ;; I commented this out because nobody calls it -- rms.
2203 ;;(defun sh-abbrevs (ancestor &rest list)
2204 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
2205 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2206 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2207 ;;according to the remaining arguments NAMEi EXPANSIONi ...
2208 ;;EXPANSION may be either a string or a skeleton command."
2209 ;; (or (if (boundp sh-shell)
2210 ;; (symbol-value sh-shell))
2211 ;; (progn
2212 ;; (if (listp ancestor)
2213 ;; (nconc list ancestor))
2214 ;; (define-abbrev-table sh-shell ())
2215 ;; (if (vectorp ancestor)
2216 ;; (mapatoms (lambda (atom)
2217 ;; (or (eq atom 0)
2218 ;; (define-abbrev (symbol-value sh-shell)
2219 ;; (symbol-name atom)
2220 ;; (symbol-value atom)
2221 ;; (symbol-function atom))))
2222 ;; ancestor))
2223 ;; (while list
2224 ;; (define-abbrev (symbol-value sh-shell)
2225 ;; (car list)
2226 ;; (if (stringp (car (cdr list)))
2227 ;; (car (cdr list))
2228 ;; "")
2229 ;; (if (symbolp (car (cdr list)))
2230 ;; (car (cdr list))))
2231 ;; (setq list (cdr (cdr list)))))
2232 ;; (symbol-value sh-shell)))
2233
2234
2235 (defun sh-append (ancestor &rest list)
2236 "Return list composed of first argument (a list) physically appended to rest."
2237 (nconc list ancestor))
2238
2239
2240 (defun sh-modify (skeleton &rest list)
2241 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2242 (setq skeleton (copy-sequence skeleton))
2243 (while list
2244 (setcar (or (nthcdr (car list) skeleton)
2245 (error "Index %d out of bounds" (car list)))
2246 (car (cdr list)))
2247 (setq list (nthcdr 2 list)))
2248 skeleton)
2249
2250
2251 (defun sh-basic-indent-line ()
2252 "Indent a line for Sh mode (shell script mode).
2253 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2254 Lines containing only comments are considered empty."
2255 (interactive)
2256 (let ((previous (save-excursion
2257 (while (and (progn (beginning-of-line)
2258 (not (bobp)))
2259 (progn
2260 (forward-line -1)
2261 (back-to-indentation)
2262 (or (eolp)
2263 (eq (following-char) ?#)))))
2264 (current-column)))
2265 current)
2266 (save-excursion
2267 (indent-to (if (eq this-command 'newline-and-indent)
2268 previous
2269 (if (< (current-column)
2270 (setq current (progn (back-to-indentation)
2271 (current-column))))
2272 (if (eolp) previous 0)
2273 (delete-region (point)
2274 (progn (beginning-of-line) (point)))
2275 (if (eolp)
2276 (max previous (* (1+ (/ current sh-indentation))
2277 sh-indentation))
2278 (* (1+ (/ current sh-indentation)) sh-indentation))))))
2279 (if (< (current-column) (current-indentation))
2280 (skip-chars-forward " \t"))))
2281
2282
2283 (defun sh-execute-region (start end &optional flag)
2284 "Pass optional header and region to a subshell for noninteractive execution.
2285 The working directory is that of the buffer, and only environment variables
2286 are already set which is why you can mark a header within the script.
2287
2288 With a positive prefix ARG, instead of sending region, define header from
2289 beginning of buffer to point. With a negative prefix ARG, instead of sending
2290 region, clear header."
2291 (interactive "r\nP")
2292 (if flag
2293 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2294 (point-marker)))
2295 (if sh-header-marker
2296 (save-excursion
2297 (let (buffer-undo-list)
2298 (goto-char sh-header-marker)
2299 (append-to-buffer (current-buffer) start end)
2300 (shell-command-on-region (point-min)
2301 (setq end (+ sh-header-marker
2302 (- end start)))
2303 sh-shell-file)
2304 (delete-region sh-header-marker end)))
2305 (shell-command-on-region start end (concat sh-shell-file " -")))))
2306
2307
2308 (defun sh-remember-variable (var)
2309 "Make VARIABLE available for future completing reads in this buffer."
2310 (or (< (length var) sh-remember-variable-min)
2311 (getenv var)
2312 (assoc var sh-shell-variables)
2313 (push (cons var var) sh-shell-variables))
2314 var)
2315
2316
2317
2318 (defun sh-quoted-p ()
2319 "Is point preceded by an odd number of backslashes?"
2320 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
2321 \f
2322 ;; Indentation stuff.
2323 (defun sh-must-support-indent ()
2324 "Signal an error if the shell type for this buffer is not supported.
2325 Also, the buffer must be in Shell-script mode."
2326 (unless sh-indent-supported-here
2327 (error "This buffer's shell does not support indentation through Emacs")))
2328
2329 (defun sh-make-vars-local ()
2330 "Make the indentation variables local to this buffer.
2331 Normally they already are local. This command is provided in case
2332 variable `sh-make-vars-local' has been set to nil.
2333
2334 To revert all these variables to the global values, use
2335 command `sh-reset-indent-vars-to-global-values'."
2336 (interactive)
2337 (mapc 'make-local-variable sh-var-list)
2338 (message "Indentation variables are now local."))
2339
2340 (defun sh-reset-indent-vars-to-global-values ()
2341 "Reset local indentation variables to the global values.
2342 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2343 (interactive)
2344 (mapc 'kill-local-variable sh-var-list)
2345 (if sh-make-vars-local
2346 (mapcar 'make-local-variable sh-var-list)))
2347
2348
2349 ;; Theoretically these are only needed in shell and derived modes.
2350 ;; However, the routines which use them are only called in those modes.
2351 (defconst sh-special-keywords "then\\|do")
2352
2353 (defun sh-help-string-for-variable (var)
2354 "Construct a string for `sh-read-variable' when changing variable VAR ."
2355 (let ((msg (documentation-property var 'variable-documentation))
2356 (msg2 ""))
2357 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
2358 (setq msg2
2359 (format "\n
2360 You can enter a number (positive to increase indentation,
2361 negative to decrease indentation, zero for no change to indentation).
2362
2363 Or, you can enter one of the following symbols which are relative to
2364 the value of variable `sh-basic-offset'
2365 which in this buffer is currently %s.
2366
2367 \t%s."
2368 sh-basic-offset
2369 (mapconcat (lambda (x)
2370 (nth (1- (length x)) x))
2371 sh-symbol-list "\n\t"))))
2372 (concat
2373 ;; The following shows the global not the local value!
2374 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2375 msg msg2)))
2376
2377 (defun sh-read-variable (var)
2378 "Read a new value for indentation variable VAR."
2379 (interactive "*variable? ") ;; to test
2380 (let ((minibuffer-help-form `(sh-help-string-for-variable
2381 (quote ,var)))
2382 val)
2383 (setq val (read-from-minibuffer
2384 (format "New value for %s (press %s for help): "
2385 var (single-key-description help-char))
2386 (format "%s" (symbol-value var))
2387 nil t))
2388 val))
2389
2390
2391
2392 (defun sh-in-comment-or-string (start)
2393 "Return non-nil if START is in a comment or string."
2394 (save-excursion
2395 (let ((state (syntax-ppss start)))
2396 (or (nth 3 state) (nth 4 state)))))
2397
2398 (defun sh-goto-matching-if ()
2399 "Go to the matching if for a fi.
2400 This handles nested if..fi pairs."
2401 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2402 (if found
2403 (goto-char found))))
2404
2405
2406 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2407 ;; line whose indentation is being handled contain XXX;
2408 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2409
2410 (defun sh-handle-prev-if ()
2411 (list '(+ sh-indent-after-if)))
2412
2413 (defun sh-handle-this-else ()
2414 (if (sh-goto-matching-if)
2415 ;; (list "aligned to if")
2416 (list "aligned to if" '(+ sh-indent-for-else))
2417 nil
2418 ))
2419
2420 (defun sh-handle-prev-else ()
2421 (if (sh-goto-matching-if)
2422 (list '(+ sh-indent-after-if))
2423 ))
2424
2425 (defun sh-handle-this-fi ()
2426 (if (sh-goto-matching-if)
2427 (list "aligned to if" '(+ sh-indent-for-fi))
2428 nil
2429 ))
2430
2431 (defun sh-handle-prev-fi ()
2432 ;; Why do we have this rule? Because we must go back to the if
2433 ;; to get its indent. We may continue back from there.
2434 ;; We return nil because we don't have anything to add to result,
2435 ;; the side affect of setting align-point is all that matters.
2436 ;; we could return a comment (a string) but I can't think of a good one...
2437 (sh-goto-matching-if)
2438 nil)
2439
2440 (defun sh-handle-this-then ()
2441 (let ((p (sh-goto-matching-if)))
2442 (if p
2443 (list '(+ sh-indent-for-then))
2444 )))
2445
2446 (defun sh-handle-prev-then ()
2447 (let ((p (sh-goto-matching-if)))
2448 (if p
2449 (list '(+ sh-indent-after-if))
2450 )))
2451
2452 (defun sh-handle-prev-open ()
2453 (save-excursion
2454 (let ((x (sh-prev-stmt)))
2455 (if (and x
2456 (progn
2457 (goto-char x)
2458 (or
2459 (looking-at "function\\b")
2460 (looking-at "\\s-*\\S-+\\s-*()")
2461 )))
2462 (list '(+ sh-indent-after-function))
2463 (list '(+ sh-indent-after-open)))
2464 )))
2465
2466 (defun sh-handle-this-close ()
2467 (forward-char 1) ;; move over ")"
2468 (if (sh-safe-forward-sexp -1)
2469 (list "aligned to opening paren")))
2470
2471 (defun sh-goto-matching-case ()
2472 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2473 (if found (goto-char found))))
2474
2475 (defun sh-handle-prev-case ()
2476 ;; This is typically called when point is on same line as a case
2477 ;; we shouldn't -- and can't find prev-case
2478 (if (looking-at ".*\\<case\\>")
2479 (list '(+ sh-indent-for-case-label))
2480 (error "We don't seem to be on a line with a case"))) ;; debug
2481
2482 (defun sh-handle-this-esac ()
2483 (if (sh-goto-matching-case)
2484 (list "aligned to matching case")))
2485
2486 (defun sh-handle-prev-esac ()
2487 (if (sh-goto-matching-case)
2488 (list "matching case")))
2489
2490 (defun sh-handle-after-case-label ()
2491 (if (sh-goto-matching-case)
2492 (list '(+ sh-indent-for-case-alt))))
2493
2494 (defun sh-handle-prev-case-alt-end ()
2495 (if (sh-goto-matching-case)
2496 (list '(+ sh-indent-for-case-label))))
2497
2498 (defun sh-safe-forward-sexp (&optional arg)
2499 "Try and do a `forward-sexp', but do not error.
2500 Return new point if successful, nil if an error occurred."
2501 (condition-case nil
2502 (progn
2503 (forward-sexp (or arg 1))
2504 (point)) ;; return point if successful
2505 (error
2506 (sh-debug "oops!(1) %d" (point))
2507 nil))) ;; return nil if fail
2508
2509 (defun sh-goto-match-for-done ()
2510 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2511 (if found
2512 (goto-char found))))
2513
2514 (defun sh-handle-this-done ()
2515 (if (sh-goto-match-for-done)
2516 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2517
2518 (defun sh-handle-prev-done ()
2519 (if (sh-goto-match-for-done)
2520 (list "previous done")))
2521
2522 (defun sh-handle-this-do ()
2523 (if (sh-goto-match-for-done)
2524 (list '(+ sh-indent-for-do))))
2525
2526 (defun sh-handle-prev-do ()
2527 (cond
2528 ((save-restriction
2529 (narrow-to-region (point) (line-beginning-position))
2530 (sh-goto-match-for-done))
2531 (sh-debug "match for done found on THIS line")
2532 (list '(+ sh-indent-after-loop-construct)))
2533 ((sh-goto-match-for-done)
2534 (sh-debug "match for done found on PREV line")
2535 (list '(+ sh-indent-after-do)))
2536 (t
2537 (message "match for done NOT found")
2538 nil)))
2539
2540 ;; for rc:
2541 (defun sh-find-prev-switch ()
2542 "Find the line for the switch keyword matching this line's case keyword."
2543 (re-search-backward "\\<switch\\>" nil t))
2544
2545 (defun sh-handle-this-rc-case ()
2546 (if (sh-find-prev-switch)
2547 (list '(+ sh-indent-after-switch))
2548 ;; (list '(+ sh-indent-for-case-label))
2549 nil))
2550
2551 (defun sh-handle-prev-rc-case ()
2552 (list '(+ sh-indent-after-case)))
2553
2554 (defun sh-check-rule (n thing)
2555 (let ((rule (nth n (assoc thing sh-kw-alist)))
2556 (val nil))
2557 (if rule
2558 (progn
2559 (setq val (funcall rule))
2560 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2561 n thing (point) rule val)))
2562 val))
2563
2564
2565 (defun sh-get-indent-info ()
2566 "Return indent-info for this line.
2567 This is a list. nil means the line is to be left as is.
2568 Otherwise it contains one or more of the following sublists:
2569 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2570 relative to. If present, this is always the first of the
2571 sublists. The indentation of the line in question is
2572 derived from the indentation of this point, possibly
2573 modified by subsequent sublists.
2574 \(+ VAR\)
2575 \(- VAR\) Get the value of variable VAR and add to or subtract from
2576 the indentation calculated so far.
2577 \(= VAR\) Get the value of variable VAR and *replace* the
2578 indentation with its value. This only occurs for
2579 special variables such as `sh-indent-comment'.
2580 STRING This is ignored for the purposes of calculating
2581 indentation, it is printed in certain cases to help show
2582 what the indentation is based on."
2583 ;; See comments before `sh-kw'.
2584 (save-excursion
2585 (let ((have-result nil)
2586 this-kw
2587 val
2588 (result nil)
2589 (align-point nil)
2590 prev-line-end x)
2591 (beginning-of-line)
2592 ;; Note: setting result to t means we are done and will return nil.
2593 ;;(This function never returns just t.)
2594 (cond
2595 ((or (nth 3 (syntax-ppss (point)))
2596 (eq (get-text-property (point) 'face) sh-heredoc-face))
2597 ;; String continuation -- don't indent
2598 (setq result t)
2599 (setq have-result t))
2600 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2601 (if (bobp)
2602 (setq result t) ;; return nil if 1st line!
2603 (setq result (list '(= sh-indent-comment)))
2604 ;; we still need to get previous line in case
2605 ;; sh-indent-comment is t (indent as normal)
2606 (setq align-point (sh-prev-line nil))
2607 (setq have-result nil)
2608 ))
2609 ) ;; cond
2610
2611 (unless have-result
2612 ;; Continuation lines are handled specially
2613 (if (sh-this-is-a-continuation)
2614 (progn
2615 (setq result
2616 (if (save-excursion
2617 (beginning-of-line)
2618 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2619 ;; By convention, if the continuation \ is not
2620 ;; preceded by a SPC or a TAB it means that the line
2621 ;; is cut at a place where spaces cannot be freely
2622 ;; added/removed. I.e. do not indent the line.
2623 (list '(= nil))
2624 ;; We assume the line being continued is already
2625 ;; properly indented...
2626 ;; (setq prev-line-end (sh-prev-line))
2627 (setq align-point (sh-prev-line nil))
2628 (list '(+ sh-indent-for-continuation))))
2629 (setq have-result t))
2630 (beginning-of-line)
2631 (skip-chars-forward " \t")
2632 (setq this-kw (sh-get-kw)))
2633
2634 ;; Handle "this" keyword: first word on the line we're
2635 ;; calculating indentation info for.
2636 (if this-kw
2637 (if (setq val (sh-check-rule 1 this-kw))
2638 (progn
2639 (setq align-point (point))
2640 (sh-debug
2641 "this - setting align-point to %d" align-point)
2642 (setq result (append result val))
2643 (setq have-result t)
2644 ;; set prev-line to continue processing remainder
2645 ;; of this line as a previous line
2646 (setq prev-line-end (point))
2647 ))))
2648
2649 (unless have-result
2650 (setq prev-line-end (sh-prev-line 'end)))
2651
2652 (if prev-line-end
2653 (save-excursion
2654 ;; We start off at beginning of this line.
2655 ;; Scan previous statements while this is <=
2656 ;; start of previous line.
2657 (goto-char prev-line-end)
2658 (setq x t)
2659 (while (and x (setq x (sh-prev-thing)))
2660 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2661 (cond
2662 ((and (equal x ")")
2663 (equal (get-text-property (1- (point)) 'syntax-table)
2664 sh-st-punc))
2665 (sh-debug "Case label) here")
2666 (setq x 'case-label)
2667 (if (setq val (sh-check-rule 2 x))
2668 (progn
2669 (setq result (append result val))
2670 (setq align-point (point))))
2671 (or (bobp)
2672 (forward-char -1))
2673 ;; FIXME: This charset looks too much like a regexp. --Stef
2674 (skip-chars-forward "[a-z0-9]*?")
2675 )
2676 ((string-match "[])}]" x)
2677 (setq x (sh-safe-forward-sexp -1))
2678 (if x
2679 (progn
2680 (setq align-point (point))
2681 (setq result (append result
2682 (list "aligned to opening paren")))
2683 )))
2684 ((string-match "[[({]" x)
2685 (sh-debug "Checking special thing: %s" x)
2686 (if (setq val (sh-check-rule 2 x))
2687 (setq result (append result val)))
2688 (forward-char -1)
2689 (setq align-point (point)))
2690 ((string-match "[\"'`]" x)
2691 (sh-debug "Skipping back for %s" x)
2692 ;; this was oops-2
2693 (setq x (sh-safe-forward-sexp -1)))
2694 ((stringp x)
2695 (sh-debug "Checking string %s at %s" x (point))
2696 (if (setq val (sh-check-rule 2 x))
2697 ;; (or (eq t (car val))
2698 ;; (eq t (car (car val))))
2699 (setq result (append result val)))
2700 ;; not sure about this test Wed Jan 27 23:48:35 1999
2701 (setq align-point (point))
2702 (unless (bolp)
2703 (forward-char -1)))
2704 (t
2705 (error "Don't know what to do with %s" x))
2706 )
2707 ) ;; while
2708 (sh-debug "result is %s" result)
2709 )
2710 (sh-debug "No prev line!")
2711 (sh-debug "result: %s align-point: %s" result align-point)
2712 )
2713
2714 (if align-point
2715 ;; was: (setq result (append result (list (list t align-point))))
2716 (setq result (append (list (list t align-point)) result))
2717 )
2718 (sh-debug "result is now: %s" result)
2719
2720 (or result
2721 (setq result (list (if prev-line-end
2722 (list t prev-line-end)
2723 (list '= 'sh-first-lines-indent)))))
2724
2725 (if (eq result t)
2726 (setq result nil))
2727 (sh-debug "result is: %s" result)
2728 result
2729 ) ;; let
2730 ))
2731
2732
2733 (defun sh-get-indent-var-for-line (&optional info)
2734 "Return the variable controlling indentation for this line.
2735 If there is not [just] one such variable, return a string
2736 indicating the problem.
2737 If INFO is supplied it is used, else it is calculated."
2738 (let ((var nil)
2739 (result nil)
2740 (reason nil)
2741 sym elt)
2742 (or info
2743 (setq info (sh-get-indent-info)))
2744 (if (null info)
2745 (setq result "this line to be left as is")
2746 (while (and info (null result))
2747 (setq elt (car info))
2748 (cond
2749 ((stringp elt)
2750 (setq reason elt)
2751 )
2752 ((not (listp elt))
2753 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2754 ;; so it is a list
2755 ((eq t (car elt))
2756 ) ;; nothing
2757 ((symbolp (setq sym (nth 1 elt)))
2758 ;; A bit of a kludge - when we see the sh-indent-comment
2759 ;; ignore other variables. Otherwise it is tricky to
2760 ;; "learn" the comment indentation.
2761 (if (eq var 'sh-indent-comment)
2762 (setq result var)
2763 (if var
2764 (setq result
2765 "this line is controlled by more than 1 variable.")
2766 (setq var sym))))
2767 (t
2768 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2769 (setq info (cdr info))
2770 ))
2771 (or result
2772 (setq result var))
2773 (or result
2774 (setq result reason))
2775 (if (null result)
2776 ;; e.g. just had (t POS)
2777 (setq result "line has default indentation"))
2778 result))
2779
2780
2781
2782 ;; Finding the previous line isn't trivial.
2783 ;; We must *always* go back one more and see if that is a continuation
2784 ;; line -- it is the PREVIOUS line which is continued, not the one
2785 ;; we are going to!
2786 ;; Also, we want to treat a whole "here document" as one big line,
2787 ;; because we may want to a align to the beginning of it.
2788 ;;
2789 ;; What we do:
2790 ;; - go back to previous non-empty line
2791 ;; - if this is in a here-document, go to the beginning of it
2792 ;; - while previous line is continued, go back one line
2793 (defun sh-prev-line (&optional end)
2794 "Back to end of previous non-comment non-empty line.
2795 Go to beginning of logical line unless END is non-nil, in which case
2796 we go to the end of the previous line and do not check for continuations."
2797 (save-excursion
2798 (beginning-of-line)
2799 (forward-comment (- (point-max)))
2800 (unless end (beginning-of-line))
2801 (when (and (not (bobp))
2802 (equal (get-text-property (1- (point)) 'face)
2803 sh-heredoc-face))
2804 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2805 (when p1
2806 (goto-char p1)
2807 (if end
2808 (end-of-line)
2809 (beginning-of-line)))))
2810 (unless end
2811 ;; we must check previous lines to see if they are continuation lines
2812 ;; if so, we must return position of first of them
2813 (while (and (sh-this-is-a-continuation)
2814 (>= 0 (forward-line -1))))
2815 (beginning-of-line)
2816 (skip-chars-forward " \t"))
2817 (point)))
2818
2819
2820 (defun sh-prev-stmt ()
2821 "Return the address of the previous stmt or nil."
2822 ;; This is used when we are trying to find a matching keyword.
2823 ;; Searching backward for the keyword would certainly be quicker, but
2824 ;; it is hard to remove "false matches" -- such as if the keyword
2825 ;; appears in a string or quote. This way is slower, but (I think) safer.
2826 (interactive)
2827 (save-excursion
2828 (let ((going t)
2829 (start (point))
2830 (found nil)
2831 (prev nil))
2832 (skip-chars-backward " \t;|&({[")
2833 (while (and (not found)
2834 (not (bobp))
2835 going)
2836 ;; Do a backward-sexp if possible, else backup bit by bit...
2837 (if (sh-safe-forward-sexp -1)
2838 (progn
2839 (if (looking-at sh-special-keywords)
2840 (progn
2841 (setq found prev))
2842 (setq prev (point))
2843 ))
2844 ;; backward-sexp failed
2845 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2846 (forward-char -1))
2847 (if (bolp)
2848 (let ((back (sh-prev-line nil)))
2849 (if back
2850 (goto-char back)
2851 (setq going nil)))))
2852 (unless found
2853 (skip-chars-backward " \t")
2854 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2855 (eq (char-before) ?\;)
2856 (looking-at "\\s-*[|&]"))
2857 (setq found (point)))))
2858 (if found
2859 (goto-char found))
2860 (if found
2861 (progn
2862 (skip-chars-forward " \t|&({[")
2863 (setq found (point))))
2864 (if (>= (point) start)
2865 (progn
2866 (debug "We didn't move!")
2867 (setq found nil))
2868 (or found
2869 (sh-debug "Did not find prev stmt.")))
2870 found)))
2871
2872
2873 (defun sh-get-word ()
2874 "Get a shell word skipping whitespace from point."
2875 (interactive)
2876 (skip-chars-forward "\t ")
2877 (let ((start (point)))
2878 (while
2879 (if (looking-at "[\"'`]")
2880 (sh-safe-forward-sexp)
2881 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2882 (> (skip-chars-forward "-_$[:alnum:]") 0)
2883 ))
2884 (buffer-substring start (point))
2885 ))
2886
2887 (defun sh-prev-thing ()
2888 "Return the previous thing this logical line."
2889 ;; This is called when `sh-get-indent-info' is working backwards on
2890 ;; the previous line(s) finding what keywords may be relevant for
2891 ;; indenting. It moves over sexps if possible, and will stop
2892 ;; on a ; and at the beginning of a line if it is not a continuation
2893 ;; line.
2894 ;;
2895 ;; Added a kludge for ";;"
2896 ;; Possible return values:
2897 ;; nil - nothing
2898 ;; a string - possibly a keyword
2899 ;;
2900 (if (bolp)
2901 nil
2902 (let ((start (point))
2903 (min-point (if (sh-this-is-a-continuation)
2904 (sh-prev-line nil)
2905 (line-beginning-position))))
2906 (skip-chars-backward " \t;" min-point)
2907 (if (looking-at "\\s-*;[;&]")
2908 ;; (message "Found ;; !")
2909 ";;"
2910 (skip-chars-backward "^)}];\"'`({[" min-point)
2911 (let ((c (if (> (point) min-point) (char-before))))
2912 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2913 (point) c start min-point)
2914 (if (not (memq c '(?\n nil ?\;)))
2915 ;; c -- return a string
2916 (char-to-string c)
2917 ;; Return the leading keyword of the "command" we supposedly
2918 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
2919 ;; `then' that precedes the actual command), so check whether
2920 ;; we're looking at such a keyword and if so, move back forward.
2921 (let ((boundary (point))
2922 kwd next)
2923 (while
2924 (progn
2925 ;; Skip forward over white space newline and \ at eol.
2926 (skip-chars-forward " \t\n\\\\" start)
2927 (if (>= (point) start)
2928 (progn
2929 (sh-debug "point: %d >= start: %d" (point) start)
2930 nil)
2931 (if next (setq boundary next))
2932 (sh-debug "Now at %d start=%d" (point) start)
2933 (setq kwd (sh-get-word))
2934 (if (member kwd (sh-feature sh-leading-keywords))
2935 (progn
2936 (setq next (point))
2937 t)
2938 nil))))
2939 (goto-char boundary)
2940 kwd)))))))
2941
2942
2943 (defun sh-this-is-a-continuation ()
2944 "Return non-nil if current line is a continuation of previous line."
2945 (save-excursion
2946 (and (zerop (forward-line -1))
2947 (looking-at ".*\\\\$")
2948 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2949 nil nil nil t))))))
2950
2951 (defun sh-get-kw (&optional where and-move)
2952 "Return first word of line from WHERE.
2953 If AND-MOVE is non-nil then move to end of word."
2954 (let ((start (point)))
2955 (if where
2956 (goto-char where))
2957 (prog1
2958 (buffer-substring (point)
2959 (progn (skip-chars-forward "^ \t\n;&|")(point)))
2960 (unless and-move
2961 (goto-char start)))))
2962
2963 (defun sh-find-prev-matching (open close &optional depth)
2964 "Find a matching token for a set of opening and closing keywords.
2965 This takes into account that there may be nested open..close pairings.
2966 OPEN and CLOSE are regexps denoting the tokens to be matched.
2967 Optional parameter DEPTH (usually 1) says how many to look for."
2968 (let ((parse-sexp-ignore-comments t)
2969 prev)
2970 (setq depth (or depth 1))
2971 (save-excursion
2972 (condition-case nil
2973 (while (and
2974 (/= 0 depth)
2975 (not (bobp))
2976 (setq prev (sh-prev-stmt)))
2977 (goto-char prev)
2978 (save-excursion
2979 (if (looking-at "\\\\\n")
2980 (progn
2981 (forward-char 2)
2982 (skip-chars-forward " \t")))
2983 (cond
2984 ((looking-at open)
2985 (setq depth (1- depth))
2986 (sh-debug "found open at %d - depth = %d" (point) depth))
2987 ((looking-at close)
2988 (setq depth (1+ depth))
2989 (sh-debug "found close - depth = %d" depth))
2990 (t
2991 ))))
2992 (error nil))
2993 (if (eq depth 0)
2994 prev ;; (point)
2995 nil)
2996 )))
2997
2998
2999 (defun sh-var-value (var &optional ignore-error)
3000 "Return the value of variable VAR, interpreting symbols.
3001 It can also return t or nil.
3002 If an invalid value is found, throw an error unless Optional argument
3003 IGNORE-ERROR is non-nil."
3004 (let ((val (symbol-value var)))
3005 (cond
3006 ((numberp val)
3007 val)
3008 ((eq val t)
3009 val)
3010 ((null val)
3011 val)
3012 ((eq val '+)
3013 sh-basic-offset)
3014 ((eq val '-)
3015 (- sh-basic-offset))
3016 ((eq val '++)
3017 (* 2 sh-basic-offset))
3018 ((eq val '--)
3019 (* 2 (- sh-basic-offset)))
3020 ((eq val '*)
3021 (/ sh-basic-offset 2))
3022 ((eq val '/)
3023 (/ (- sh-basic-offset) 2))
3024 (t
3025 (if ignore-error
3026 (progn
3027 (message "Don't know how to handle %s's value of %s" var val)
3028 0)
3029 (error "Don't know how to handle %s's value of %s" var val))
3030 ))))
3031
3032 (defun sh-set-var-value (var value &optional no-symbol)
3033 "Set variable VAR to VALUE.
3034 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3035 can be represented by a symbol then do so."
3036 (cond
3037 (no-symbol
3038 (set var value))
3039 ((= value sh-basic-offset)
3040 (set var '+))
3041 ((= value (- sh-basic-offset))
3042 (set var '-))
3043 ((eq value (* 2 sh-basic-offset))
3044 (set var '++))
3045 ((eq value (* 2 (- sh-basic-offset)))
3046 (set var '--))
3047 ((eq value (/ sh-basic-offset 2))
3048 (set var '*))
3049 ((eq value (/ (- sh-basic-offset) 2))
3050 (set var '/))
3051 (t
3052 (set var value)))
3053 )
3054
3055
3056 (defun sh-calculate-indent (&optional info)
3057 "Return the indentation for the current line.
3058 If INFO is supplied it is used, else it is calculated from current line."
3059 (let ((ofs 0)
3060 (base-value 0)
3061 elt a b val)
3062 (or info
3063 (setq info (sh-get-indent-info)))
3064 (when info
3065 (while info
3066 (sh-debug "info: %s ofs=%s" info ofs)
3067 (setq elt (car info))
3068 (cond
3069 ((stringp elt)) ;; do nothing?
3070 ((listp elt)
3071 (setq a (car (car info)))
3072 (setq b (nth 1 (car info)))
3073 (cond
3074 ((eq a t)
3075 (save-excursion
3076 (goto-char b)
3077 (setq val (current-indentation)))
3078 (setq base-value val))
3079 ((symbolp b)
3080 (setq val (sh-var-value b))
3081 (cond
3082 ((eq a '=)
3083 (cond
3084 ((null val)
3085 ;; no indentation
3086 ;; set info to nil so we stop immediately
3087 (setq base-value nil ofs nil info nil))
3088 ((eq val t) (setq ofs 0)) ;; indent as normal line
3089 (t
3090 ;; The following assume the (t POS) come first!
3091 (setq ofs val base-value 0)
3092 (setq info nil)))) ;; ? stop now
3093 ((eq a '+) (setq ofs (+ ofs val)))
3094 ((eq a '-) (setq ofs (- ofs val)))
3095 (t
3096 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3097 (t
3098 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
3099 (t
3100 (error "sh-calculate-indent invalid elt %s" elt)))
3101 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3102 a b val base-value ofs)
3103 (setq info (cdr info)))
3104 ;; return value:
3105 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
3106
3107 (cond
3108 ((or (null base-value)(null ofs))
3109 nil)
3110 ((and (numberp base-value)(numberp ofs))
3111 (sh-debug "base (%d) + ofs (%d) = %d"
3112 base-value ofs (+ base-value ofs))
3113 (+ base-value ofs)) ;; return value
3114 (t
3115 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3116 base-value ofs)
3117 nil)))))
3118
3119
3120 (defun sh-indent-line ()
3121 "Indent the current line."
3122 (interactive)
3123 (let ((indent (sh-calculate-indent))
3124 (pos (- (point-max) (point))))
3125 (when indent
3126 (beginning-of-line)
3127 (skip-chars-forward " \t")
3128 (indent-line-to indent)
3129 ;; If initial point was within line's indentation,
3130 ;; position after the indentation. Else stay at same point in text.
3131 (if (> (- (point-max) pos) (point))
3132 (goto-char (- (point-max) pos))))))
3133
3134
3135 (defun sh-blink (blinkpos &optional msg)
3136 "Move cursor momentarily to BLINKPOS and display MSG."
3137 ;; We can get here without it being a number on first line
3138 (if (numberp blinkpos)
3139 (save-excursion
3140 (goto-char blinkpos)
3141 (if msg (message "%s" msg) (message nil))
3142 (sit-for blink-matching-delay))
3143 (if msg (message "%s" msg) (message nil))))
3144
3145 (defun sh-show-indent (arg)
3146 "Show the how the current line would be indented.
3147 This tells you which variable, if any, controls the indentation of
3148 this line.
3149 If optional arg ARG is non-null (called interactively with a prefix),
3150 a pop up window describes this variable.
3151 If variable `sh-blink' is non-nil then momentarily go to the line
3152 we are indenting relative to, if applicable."
3153 (interactive "P")
3154 (sh-must-support-indent)
3155 (let* ((info (sh-get-indent-info))
3156 (var (sh-get-indent-var-for-line info))
3157 (curr-indent (current-indentation))
3158 val msg)
3159 (if (stringp var)
3160 (message "%s" (setq msg var))
3161 (setq val (sh-calculate-indent info))
3162
3163 (if (eq curr-indent val)
3164 (setq msg (format "%s is %s" var (symbol-value var)))
3165 (setq msg
3166 (if val
3167 (format "%s (%s) would change indent from %d to: %d"
3168 var (symbol-value var) curr-indent val)
3169 (format "%s (%s) would leave line as is"
3170 var (symbol-value var)))
3171 ))
3172 (if (and arg var)
3173 (describe-variable var)))
3174 (if sh-blink
3175 (let ((info (sh-get-indent-info)))
3176 (if (and info (listp (car info))
3177 (eq (car (car info)) t))
3178 (sh-blink (nth 1 (car info)) msg)
3179 (message "%s" msg)))
3180 (message "%s" msg))
3181 ))
3182
3183 (defun sh-set-indent ()
3184 "Set the indentation for the current line.
3185 If the current line is controlled by an indentation variable, prompt
3186 for a new value for it."
3187 (interactive)
3188 (sh-must-support-indent)
3189 (let* ((info (sh-get-indent-info))
3190 (var (sh-get-indent-var-for-line info))
3191 val old-val indent-val)
3192 (if (stringp var)
3193 (message "Cannot set indent - %s" var)
3194 (setq old-val (symbol-value var))
3195 (setq val (sh-read-variable var))
3196 (condition-case nil
3197 (progn
3198 (set var val)
3199 (setq indent-val (sh-calculate-indent info))
3200 (if indent-val
3201 (message "Variable: %s Value: %s would indent to: %d"
3202 var (symbol-value var) indent-val)
3203 (message "Variable: %s Value: %s would leave line as is."
3204 var (symbol-value var)))
3205 ;; I'm not sure about this, indenting it now?
3206 ;; No. Because it would give the impression that an undo would
3207 ;; restore thing, but the value has been altered.
3208 ;; (sh-indent-line)
3209 )
3210 (error
3211 (set var old-val)
3212 (message "Bad value for %s, restoring to previous value %s"
3213 var old-val)
3214 (sit-for 1)
3215 nil))
3216 )))
3217
3218
3219 (defun sh-learn-line-indent (arg)
3220 "Learn how to indent a line as it currently is indented.
3221
3222 If there is an indentation variable which controls this line's indentation,
3223 then set it to a value which would indent the line the way it
3224 presently is.
3225
3226 If the value can be represented by one of the symbols then do so
3227 unless optional argument ARG (the prefix when interactive) is non-nil."
3228 (interactive "*P")
3229 (sh-must-support-indent)
3230 ;; I'm not sure if we show allow learning on an empty line.
3231 ;; Though it might occasionally be useful I think it usually
3232 ;; would just be confusing.
3233 (if (save-excursion
3234 (beginning-of-line)
3235 (looking-at "\\s-*$"))
3236 (message "sh-learn-line-indent ignores empty lines.")
3237 (let* ((info (sh-get-indent-info))
3238 (var (sh-get-indent-var-for-line info))
3239 ival sval diff new-val
3240 (no-symbol arg)
3241 (curr-indent (current-indentation)))
3242 (cond
3243 ((stringp var)
3244 (message "Cannot learn line - %s" var))
3245 ((eq var 'sh-indent-comment)
3246 ;; This is arbitrary...
3247 ;; - if curr-indent is 0, set to curr-indent
3248 ;; - else if it has the indentation of a "normal" line,
3249 ;; then set to t
3250 ;; - else set to curr-indent.
3251 (setq sh-indent-comment
3252 (if (= curr-indent 0)
3253 0
3254 (let* ((sh-indent-comment t)
3255 (val2 (sh-calculate-indent info)))
3256 (if (= val2 curr-indent)
3257 t
3258 curr-indent))))
3259 (message "%s set to %s" var (symbol-value var))
3260 )
3261 ((numberp (setq sval (sh-var-value var)))
3262 (setq ival (sh-calculate-indent info))
3263 (setq diff (- curr-indent ival))
3264
3265 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3266 curr-indent ival diff var sval)
3267 (setq new-val (+ sval diff))
3268 ;;; I commented out this because someone might want to replace
3269 ;;; a value of `+' with the current value of sh-basic-offset
3270 ;;; or vice-versa.
3271 ;;; (if (= 0 diff)
3272 ;;; (message "No change needed!")
3273 (sh-set-var-value var new-val no-symbol)
3274 (message "%s set to %s" var (symbol-value var))
3275 )
3276 (t
3277 (debug)
3278 (message "Cannot change %s" var))))))
3279
3280
3281
3282 (defun sh-mark-init (buffer)
3283 "Initialize a BUFFER to be used by `sh-mark-line'."
3284 (with-current-buffer (get-buffer-create buffer)
3285 (erase-buffer)
3286 (occur-mode)))
3287
3288
3289 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
3290 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3291 Buffer BUFFER is in `occur-mode'.
3292 If ADD-LINENUM is non-nil the message is preceded by the line number.
3293 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3294 so that `occur-next' and `occur-prev' will work."
3295 (let ((m1 (make-marker))
3296 start
3297 (line ""))
3298 (when point
3299 (set-marker m1 point (current-buffer))
3300 (if add-linenum
3301 (setq line (format "%d: " (1+ (count-lines 1 point))))))
3302 (save-excursion
3303 (if (get-buffer buffer)
3304 (set-buffer (get-buffer buffer))
3305 (set-buffer (get-buffer-create buffer))
3306 (occur-mode)
3307 )
3308 (goto-char (point-max))
3309 (setq start (point))
3310 (insert line)
3311 (if occur-point
3312 (setq occur-point (point)))
3313 (insert message)
3314 (if point
3315 (add-text-properties
3316 start (point)
3317 '(mouse-face highlight
3318 help-echo "mouse-2: go to the line where I learned this")))
3319 (insert "\n")
3320 (if point
3321 (progn
3322 (put-text-property start (point) 'occur-target m1)
3323 (if occur-point
3324 (put-text-property start occur-point
3325 'occur-match t))
3326 ))
3327 )))
3328
3329
3330
3331 ;; Is this really worth having?
3332 (defvar sh-learned-buffer-hook nil
3333 "An abnormal hook, called with an alist of learned variables.")
3334 ;; Example of how to use sh-learned-buffer-hook
3335 ;;
3336 ;; (defun what-i-learned (list)
3337 ;; (let ((p list))
3338 ;; (with-current-buffer "*scratch*"
3339 ;; (goto-char (point-max))
3340 ;; (insert "(setq\n")
3341 ;; (while p
3342 ;; (insert (format " %s %s \n"
3343 ;; (nth 0 (car p)) (nth 1 (car p))))
3344 ;; (setq p (cdr p)))
3345 ;; (insert ")\n")
3346 ;; )))
3347 ;;
3348 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3349
3350
3351 ;; Originally this was sh-learn-region-indent (beg end)
3352 ;; However, in practice this was awkward so I changed it to
3353 ;; use the whole buffer. Use narrowing if needbe.
3354 (defun sh-learn-buffer-indent (&optional arg)
3355 "Learn how to indent the buffer the way it currently is.
3356
3357 Output in buffer \"*indent*\" shows any lines which have conflicting
3358 values of a variable, and the final value of all variables learned.
3359 When called interactively, pop to this buffer automatically if
3360 there are any discrepancies.
3361
3362 If no prefix ARG is given, then variables are set to numbers.
3363 If a prefix arg is given, then variables are set to symbols when
3364 applicable -- e.g. to symbol `+' if the value is that of the
3365 basic indent.
3366 If a positive numerical prefix is given, then `sh-basic-offset'
3367 is set to the prefix's numerical value.
3368 Otherwise, sh-basic-offset may or may not be changed, according
3369 to the value of variable `sh-learn-basic-offset'.
3370
3371 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3372 function completes. The function is abnormal because it is called
3373 with an alist of variables learned. This feature may be changed or
3374 removed in the future.
3375
3376 This command can often take a long time to run."
3377 (interactive "P")
3378 (sh-must-support-indent)
3379 (save-excursion
3380 (goto-char (point-min))
3381 (let ((learned-var-list nil)
3382 (out-buffer "*indent*")
3383 (num-diffs 0)
3384 previous-set-info
3385 (max 17)
3386 vec
3387 msg
3388 (comment-col nil) ;; number if all same, t if seen diff values
3389 (comments-always-default t) ;; nil if we see one not default
3390 initial-msg
3391 (specified-basic-offset (and arg (numberp arg)
3392 (> arg 0)))
3393 (linenum 0)
3394 suggested)
3395 (setq vec (make-vector max 0))
3396 (sh-mark-init out-buffer)
3397
3398 (if specified-basic-offset
3399 (progn
3400 (setq sh-basic-offset arg)
3401 (setq initial-msg
3402 (format "Using specified sh-basic-offset of %d"
3403 sh-basic-offset)))
3404 (setq initial-msg
3405 (format "Initial value of sh-basic-offset: %s"
3406 sh-basic-offset)))
3407
3408 (while (< (point) (point-max))
3409 (setq linenum (1+ linenum))
3410 ;; (if (zerop (% linenum 10))
3411 (message "line %d" linenum)
3412 ;; )
3413 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3414 (let* ((sh-indent-comment t) ;; info must return default indent
3415 (info (sh-get-indent-info))
3416 (var (sh-get-indent-var-for-line info))
3417 sval ival diff new-val
3418 (curr-indent (current-indentation)))
3419 (cond
3420 ((null var)
3421 nil)
3422 ((stringp var)
3423 nil)
3424 ((numberp (setq sval (sh-var-value var 'no-error)))
3425 ;; the numberp excludes comments since sval will be t.
3426 (setq ival (sh-calculate-indent))
3427 (setq diff (- curr-indent ival))
3428 (setq new-val (+ sval diff))
3429 (sh-set-var-value var new-val 'no-symbol)
3430 (unless (looking-at "\\s-*#") ;; don't learn from comments
3431 (if (setq previous-set-info (assoc var learned-var-list))
3432 (progn
3433 ;; it was already there, is it same value ?
3434 (unless (eq (symbol-value var)
3435 (nth 1 previous-set-info))
3436 (sh-mark-line
3437 (format "Variable %s was set to %s"
3438 var (symbol-value var))
3439 (point) out-buffer t t)
3440 (sh-mark-line
3441 (format " but was previously set to %s"
3442 (nth 1 previous-set-info))
3443 (nth 2 previous-set-info) out-buffer t)
3444 (setq num-diffs (1+ num-diffs))
3445 ;; (delete previous-set-info learned-var-list)
3446 (setcdr previous-set-info
3447 (list (symbol-value var) (point)))
3448 )
3449 )
3450 (setq learned-var-list
3451 (append (list (list var (symbol-value var)
3452 (point)))
3453 learned-var-list)))
3454 (if (numberp new-val)
3455 (progn
3456 (sh-debug
3457 "This line's indent value: %d" new-val)
3458 (if (< new-val 0)
3459 (setq new-val (- new-val)))
3460 (if (< new-val max)
3461 (aset vec new-val (1+ (aref vec new-val))))))
3462 ))
3463 ((eq var 'sh-indent-comment)
3464 (unless (= curr-indent (sh-calculate-indent info))
3465 ;; this is not the default indentation
3466 (setq comments-always-default nil)
3467 (if comment-col ;; then we have see one before
3468 (or (eq comment-col curr-indent)
3469 (setq comment-col t)) ;; seen a different one
3470 (setq comment-col curr-indent))
3471 ))
3472 (t
3473 (sh-debug "Cannot learn this line!!!")
3474 ))
3475 (sh-debug
3476 "at %s learned-var-list is %s" (point) learned-var-list)
3477 ))
3478 (forward-line 1)
3479 ) ;; while
3480 (if sh-debug
3481 (progn
3482 (setq msg (format
3483 "comment-col = %s comments-always-default = %s"
3484 comment-col comments-always-default))
3485 ;; (message msg)
3486 (sh-mark-line msg nil out-buffer)))
3487 (cond
3488 ((eq comment-col 0)
3489 (setq msg "\nComments are all in 1st column.\n"))
3490 (comments-always-default
3491 (setq msg "\nComments follow default indentation.\n")
3492 (setq comment-col t))
3493 ((numberp comment-col)
3494 (setq msg (format "\nComments are in col %d." comment-col)))
3495 (t
3496 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3497 (setq comment-col nil)
3498 ))
3499 (sh-debug msg)
3500 (sh-mark-line msg nil out-buffer)
3501
3502 (sh-mark-line initial-msg nil out-buffer t t)
3503
3504 (setq suggested (sh-guess-basic-offset vec))
3505
3506 (if (and suggested (not specified-basic-offset))
3507 (let ((new-value
3508 (cond
3509 ;; t => set it if we have a single value as a number
3510 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3511 suggested)
3512 ;; other non-nil => set it if only one value was found
3513 (sh-learn-basic-offset
3514 (if (numberp suggested)
3515 suggested
3516 (if (= (length suggested) 1)
3517 (car suggested))))
3518 (t
3519 nil))))
3520 (if new-value
3521 (progn
3522 (setq learned-var-list
3523 (append (list (list 'sh-basic-offset
3524 (setq sh-basic-offset new-value)
3525 (point-max)))
3526 learned-var-list))
3527 ;; Not sure if we need to put this line in, since
3528 ;; it will appear in the "Learned variable settings".
3529 (sh-mark-line
3530 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3531 nil out-buffer))
3532 (sh-mark-line
3533 (if (listp suggested)
3534 (format "Possible value(s) for sh-basic-offset: %s"
3535 (mapconcat 'int-to-string suggested " "))
3536 (format "Suggested sh-basic-offset: %d" suggested))
3537 nil out-buffer))))
3538
3539
3540 (setq learned-var-list
3541 (append (list (list 'sh-indent-comment comment-col (point-max)))
3542 learned-var-list))
3543 (setq sh-indent-comment comment-col)
3544 (let ((name (buffer-name)))
3545 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3546 (if arg
3547 ;; Set learned variables to symbolic rather than numeric
3548 ;; values where possible.
3549 (dolist (learned-var (reverse learned-var-list))
3550 (let ((var (car learned-var))
3551 (val (nth 1 learned-var)))
3552 (when (and (not (eq var 'sh-basic-offset))
3553 (numberp val))
3554 (sh-set-var-value var val)))))
3555 (dolist (learned-var (reverse learned-var-list))
3556 (let ((var (car learned-var)))
3557 (sh-mark-line (format " %s %s" var (symbol-value var))
3558 (nth 2 learned-var) out-buffer)))
3559 (with-current-buffer out-buffer
3560 (goto-char (point-min))
3561 (insert
3562 (format "Indentation values for buffer %s.\n" name)
3563 (format "%d indentation variable%s different values%s\n\n"
3564 num-diffs
3565 (if (= num-diffs 1)
3566 " has" "s have")
3567 (if (zerop num-diffs)
3568 "." ":"))
3569 )))
3570 ;; Are abnormal hooks considered bad form?
3571 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3572 (and (called-interactively-p 'any)
3573 (or sh-popup-occur-buffer (> num-diffs 0))
3574 (pop-to-buffer out-buffer)))))
3575
3576 (defun sh-guess-basic-offset (vec)
3577 "See if we can determine a reasonable value for `sh-basic-offset'.
3578 This is experimental, heuristic and arbitrary!
3579 Argument VEC is a vector of information collected by
3580 `sh-learn-buffer-indent'.
3581 Return values:
3582 number - there appears to be a good single value
3583 list of numbers - no obvious one, here is a list of one or more
3584 reasonable choices
3585 nil - we couldn't find a reasonable one."
3586 (let* ((max (1- (length vec)))
3587 (i 1)
3588 (totals (make-vector max 0)))
3589 (while (< i max)
3590 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
3591 (if (zerop (% i 2))
3592 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3593 (if (< (* i 2) max)
3594 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3595 (setq i (1+ i)))
3596
3597 (let ((x nil)
3598 (result nil)
3599 tot sum p)
3600 (setq i 1)
3601 (while (< i max)
3602 (if (/= (aref totals i) 0)
3603 (setq x (append x (list (cons i (aref totals i))))))
3604 (setq i (1+ i)))
3605
3606 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3607 (setq tot (apply '+ (append totals nil)))
3608 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3609 vec totals tot))
3610 (cond
3611 ((zerop (length x))
3612 (message "no values!")) ;; we return nil
3613 ((= (length x) 1)
3614 (message "only value is %d" (car (car x)))
3615 (setq result (car (car x)))) ;; return single value
3616 ((> (cdr (car x)) (/ tot 2))
3617 ;; 1st is > 50%
3618 (message "basic-offset is probably %d" (car (car x)))
3619 (setq result (car (car x)))) ;; again, return a single value
3620 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3621 ;; 1st is >= 2 * 2nd
3622 (message "basic-offset could be %d" (car (car x)))
3623 (setq result (car (car x))))
3624 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3625 ;; 1st & 2nd together >= 50% - return a list
3626 (setq p x sum 0 result nil)
3627 (while (and p
3628 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3629 (setq result (append result (list (car (car p)))))
3630 (setq p (cdr p)))
3631 (message "Possible choices for sh-basic-offset: %s"
3632 (mapconcat 'int-to-string result " ")))
3633 (t
3634 (message "No obvious value for sh-basic-offset. Perhaps %d"
3635 (car (car x)))
3636 ;; result is nil here
3637 ))
3638 result)))
3639
3640 ;; ========================================================================
3641
3642 ;; Styles -- a quick and dirty way of saving the indentation settings.
3643
3644 (defvar sh-styles-alist nil
3645 "A list of all known shell indentation styles.")
3646
3647 (defun sh-name-style (name &optional confirm-overwrite)
3648 "Name the current indentation settings as a style called NAME.
3649 If this name exists, the command will prompt whether it should be
3650 overwritten if
3651 - - it was called interactively with a prefix argument, or
3652 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3653 ;; (interactive "sName for this style: ")
3654 (interactive
3655 (list
3656 (read-from-minibuffer "Name for this style? " )
3657 (not current-prefix-arg)))
3658 (let ((slist (cons name
3659 (mapcar (lambda (var) (cons var (symbol-value var)))
3660 sh-var-list)))
3661 (style (assoc name sh-styles-alist)))
3662 (if style
3663 (if (and confirm-overwrite
3664 (not (y-or-n-p "This style exists. Overwrite it? ")))
3665 (message "Not changing style %s" name)
3666 (message "Updating style %s" name)
3667 (setcdr style (cdr slist)))
3668 (message "Creating new style %s" name)
3669 (push slist sh-styles-alist))))
3670
3671 (defun sh-load-style (name)
3672 "Set shell indentation values for this buffer from those in style NAME."
3673 (interactive (list (completing-read
3674 "Which style to use for this buffer? "
3675 sh-styles-alist nil t)))
3676 (let ((sl (assoc name sh-styles-alist)))
3677 (if (null sl)
3678 (error "sh-load-style - style %s not known" name)
3679 (dolist (var (cdr sl))
3680 (set (car var) (cdr var))))))
3681
3682 (defun sh-save-styles-to-buffer (buff)
3683 "Save all current styles in elisp to buffer BUFF.
3684 This is always added to the end of the buffer."
3685 (interactive
3686 (list
3687 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3688 (with-current-buffer (get-buffer-create buff)
3689 (goto-char (point-max))
3690 (insert "\n")
3691 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3692
3693
3694 \f
3695 ;; statement syntax-commands for various shells
3696
3697 ;; You are welcome to add the syntax or even completely new statements as
3698 ;; appropriate for your favorite shell.
3699
3700 (defconst sh-non-closing-paren
3701 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3702 ;; that inherits this property, which then confuses the indentation.
3703 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3704
3705 (define-skeleton sh-case
3706 "Insert a case/switch statement. See `sh-feature'."
3707 (csh "expression: "
3708 "switch( " str " )" \n
3709 > "case " (read-string "pattern: ") ?: \n
3710 > _ \n
3711 "breaksw" \n
3712 ( "other pattern, %s: "
3713 < "case " str ?: \n
3714 > _ \n
3715 "breaksw" \n)
3716 < "default:" \n
3717 > _ \n
3718 resume:
3719 < < "endsw" \n)
3720 (es)
3721 (rc "expression: "
3722 > "switch( " str " ) {" \n
3723 > "case " (read-string "pattern: ") \n
3724 > _ \n
3725 ( "other pattern, %s: "
3726 "case " str > \n
3727 > _ \n)
3728 "case *" > \n
3729 > _ \n
3730 resume:
3731 ?\} > \n)
3732 (sh "expression: "
3733 > "case " str " in" \n
3734 ( "pattern, %s: "
3735 > str sh-non-closing-paren \n
3736 > _ \n
3737 ";;" \n)
3738 > "*" sh-non-closing-paren \n
3739 > _ \n
3740 resume:
3741 "esac" > \n))
3742
3743 (define-skeleton sh-for
3744 "Insert a for loop. See `sh-feature'."
3745 (csh sh-modify sh
3746 1 ""
3747 2 "foreach "
3748 4 " ( "
3749 6 " )"
3750 15 '<
3751 16 "end")
3752 (es sh-modify rc
3753 4 " = ")
3754 (rc sh-modify sh
3755 2 "for( "
3756 6 " ) {"
3757 15 ?\} )
3758 (sh "Index variable: "
3759 > "for " str " in " _ "; do" \n
3760 > _ | ?$ & (sh-remember-variable str) \n
3761 "done" > \n))
3762
3763
3764
3765 (define-skeleton sh-indexed-loop
3766 "Insert an indexed loop from 1 to n. See `sh-feature'."
3767 (bash sh-modify posix)
3768 (csh "Index variable: "
3769 "@ " str " = 1" \n
3770 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3771 > _ ?$ str \n
3772 "@ " str "++" \n
3773 < "end" \n)
3774 (es sh-modify rc
3775 4 " =")
3776 (ksh88 "Index variable: "
3777 > "integer " str "=0" \n
3778 > "while (( ( " str " += 1 ) <= "
3779 (read-string "upper limit: ")
3780 " )); do" \n
3781 > _ ?$ (sh-remember-variable str) > \n
3782 "done" > \n)
3783 (posix "Index variable: "
3784 > str "=1" \n
3785 "while [ $" str " -le "
3786 (read-string "upper limit: ")
3787 " ]; do" \n
3788 > _ ?$ str \n
3789 str ?= (sh-add (sh-remember-variable str) 1) \n
3790 "done" > \n)
3791 (rc "Index variable: "
3792 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3793 (read-string "upper limit: ")
3794 "; i++ ) print i }'`}) {" \n
3795 > _ ?$ (sh-remember-variable str) \n
3796 ?\} > \n)
3797 (sh "Index variable: "
3798 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3799 (read-string "upper limit: ")
3800 "; i++ ) print i }'`; do" \n
3801 > _ ?$ (sh-remember-variable str) \n
3802 "done" > \n))
3803
3804
3805 (defun sh-shell-initialize-variables ()
3806 "Scan the buffer for variable assignments.
3807 Add these variables to `sh-shell-variables'."
3808 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3809 (save-excursion
3810 (goto-char (point-min))
3811 (setq sh-shell-variables-initialized t)
3812 (while (search-forward "=" nil t)
3813 (sh-assignment 0)))
3814 (message "Scanning buffer `%s' for variable assignments...done"
3815 (buffer-name)))
3816
3817 (defvar sh-add-buffer)
3818
3819 (defun sh-add-completer (string predicate code)
3820 "Do completion using `sh-shell-variables', but initialize it first.
3821 This function is designed for use as the \"completion table\",
3822 so it takes three arguments:
3823 STRING, the current buffer contents;
3824 PREDICATE, the predicate for filtering possible matches;
3825 CODE, which says what kind of things to do.
3826 CODE can be nil, t or `lambda'.
3827 nil means to return the best completion of STRING, or nil if there is none.
3828 t means to return a list of all possible completions of STRING.
3829 `lambda' means to return t if STRING is a valid completion as it stands."
3830 (let ((vars
3831 (with-current-buffer sh-add-buffer
3832 (or sh-shell-variables-initialized
3833 (sh-shell-initialize-variables))
3834 (nconc (mapcar (lambda (var)
3835 (substring var 0 (string-match "=" var)))
3836 process-environment)
3837 sh-shell-variables))))
3838 (complete-with-action code vars string predicate)))
3839
3840 (defun sh-add (var delta)
3841 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3842 (interactive
3843 (let ((sh-add-buffer (current-buffer)))
3844 (list (completing-read "Variable: " 'sh-add-completer)
3845 (prefix-numeric-value current-prefix-arg))))
3846 (insert (sh-feature '((bash . "$(( ")
3847 (ksh88 . "$(( ")
3848 (posix . "$(( ")
3849 (rc . "`{expr $")
3850 (sh . "`expr $")
3851 (zsh . "$[ ")))
3852 (sh-remember-variable var)
3853 (if (< delta 0) " - " " + ")
3854 (number-to-string (abs delta))
3855 (sh-feature '((bash . " ))")
3856 (ksh88 . " ))")
3857 (posix . " ))")
3858 (rc . "}")
3859 (sh . "`")
3860 (zsh . " ]")))))
3861
3862
3863
3864 (define-skeleton sh-function
3865 "Insert a function definition. See `sh-feature'."
3866 (bash sh-modify ksh88
3867 3 "() {")
3868 (ksh88 "name: "
3869 "function " str " {" \n
3870 > _ \n
3871 < "}" \n)
3872 (rc sh-modify ksh88
3873 1 "fn ")
3874 (sh ()
3875 "() {" \n
3876 > _ \n
3877 < "}" \n))
3878
3879
3880
3881 (define-skeleton sh-if
3882 "Insert an if statement. See `sh-feature'."
3883 (csh "condition: "
3884 "if( " str " ) then" \n
3885 > _ \n
3886 ( "other condition, %s: "
3887 < "else if( " str " ) then" \n
3888 > _ \n)
3889 < "else" \n
3890 > _ \n
3891 resume:
3892 < "endif" \n)
3893 (es "condition: "
3894 > "if { " str " } {" \n
3895 > _ \n
3896 ( "other condition, %s: "
3897 "} { " str " } {" > \n
3898 > _ \n)
3899 "} {" > \n
3900 > _ \n
3901 resume:
3902 ?\} > \n)
3903 (rc "condition: "
3904 > "if( " str " ) {" \n
3905 > _ \n
3906 ( "other condition, %s: "
3907 "} else if( " str " ) {" > \n
3908 > _ \n)
3909 "} else {" > \n
3910 > _ \n
3911 resume:
3912 ?\} > \n)
3913 (sh "condition: "
3914 '(setq input (sh-feature sh-test))
3915 > "if " str "; then" \n
3916 > _ \n
3917 ( "other condition, %s: "
3918 > "elif " str "; then" > \n
3919 > \n)
3920 "else" > \n
3921 > \n
3922 resume:
3923 "fi" > \n))
3924
3925
3926
3927 (define-skeleton sh-repeat
3928 "Insert a repeat loop definition. See `sh-feature'."
3929 (es nil
3930 > "forever {" \n
3931 > _ \n
3932 ?\} > \n)
3933 (zsh "factor: "
3934 > "repeat " str "; do" > \n
3935 > \n
3936 "done" > \n))
3937
3938 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3939
3940
3941
3942 (define-skeleton sh-select
3943 "Insert a select statement. See `sh-feature'."
3944 (ksh88 "Index variable: "
3945 > "select " str " in " _ "; do" \n
3946 > ?$ str \n
3947 "done" > \n)
3948 (bash sh-append ksh88))
3949 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3950
3951
3952
3953 (define-skeleton sh-tmp-file
3954 "Insert code to setup temporary file handling. See `sh-feature'."
3955 (bash sh-append ksh88)
3956 (csh (file-name-nondirectory (buffer-file-name))
3957 "set tmp = `mktemp -t " str ".XXXXXX`" \n
3958 "onintr exit" \n _
3959 (and (goto-char (point-max))
3960 (not (bolp))
3961 ?\n)
3962 "exit:\n"
3963 "rm $tmp* >&/dev/null" > \n)
3964 (es (file-name-nondirectory (buffer-file-name))
3965 > "local( signals = $signals sighup sigint;" \n
3966 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
3967 > "catch @ e {" \n
3968 > "rm $tmp^* >[2]/dev/null" \n
3969 "throw $e" \n
3970 "} {" > \n
3971 _ \n
3972 ?\} > \n
3973 ?\} > \n)
3974 (ksh88 sh-modify sh
3975 7 "EXIT")
3976 (rc (file-name-nondirectory (buffer-file-name))
3977 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
3978 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3979 (sh (file-name-nondirectory (buffer-file-name))
3980 > "TMP=`mktemp -t " str ".XXXXXX`" \n
3981 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
3982
3983
3984
3985 (define-skeleton sh-until
3986 "Insert an until loop. See `sh-feature'."
3987 (sh "condition: "
3988 '(setq input (sh-feature sh-test))
3989 > "until " str "; do" \n
3990 > _ \n
3991 "done" > \n))
3992 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3993
3994
3995
3996 (define-skeleton sh-while
3997 "Insert a while loop. See `sh-feature'."
3998 (csh sh-modify sh
3999 2 ""
4000 3 "while( "
4001 5 " )"
4002 10 '<
4003 11 "end")
4004 (es sh-modify sh
4005 3 "while { "
4006 5 " } {"
4007 10 ?\} )
4008 (rc sh-modify sh
4009 3 "while( "
4010 5 " ) {"
4011 10 ?\} )
4012 (sh "condition: "
4013 '(setq input (sh-feature sh-test))
4014 > "while " str "; do" \n
4015 > _ \n
4016 "done" > \n))
4017
4018
4019
4020 (define-skeleton sh-while-getopts
4021 "Insert a while getopts loop. See `sh-feature'.
4022 Prompts for an options string which consists of letters for each recognized
4023 option followed by a colon `:' if the option accepts an argument."
4024 (bash sh-modify sh
4025 18 "${0##*/}")
4026 (csh nil
4027 "while( 1 )" \n
4028 > "switch( \"$1\" )" \n
4029 '(setq input '("- x" . 2))
4030 > >
4031 ( "option, %s: "
4032 < "case " '(eval str)
4033 '(if (string-match " +" str)
4034 (setq v1 (substring str (match-end 0))
4035 str (substring str 0 (match-beginning 0)))
4036 (setq v1 nil))
4037 str ?: \n
4038 > "set " v1 & " = $2" | -4 & _ \n
4039 (if v1 "shift") & \n
4040 "breaksw" \n)
4041 < "case --:" \n
4042 > "shift" \n
4043 < "default:" \n
4044 > "break" \n
4045 resume:
4046 < < "endsw" \n
4047 "shift" \n
4048 < "end" \n)
4049 (ksh88 sh-modify sh
4050 16 "print"
4051 18 "${0##*/}"
4052 37 "OPTIND-1")
4053 (posix sh-modify sh
4054 18 "$(basename $0)")
4055 (sh "optstring: "
4056 > "while getopts :" str " OPT; do" \n
4057 > "case $OPT in" \n
4058 '(setq v1 (append (vconcat str) nil))
4059 ( (prog1 (if v1 (char-to-string (car v1)))
4060 (if (eq (nth 1 v1) ?:)
4061 (setq v1 (nthcdr 2 v1)
4062 v2 "\"$OPTARG\"")
4063 (setq v1 (cdr v1)
4064 v2 nil)))
4065 > str "|+" str sh-non-closing-paren \n
4066 > _ v2 \n
4067 > ";;" \n)
4068 > "*" sh-non-closing-paren \n
4069 > "echo" " \"usage: " "`basename $0`"
4070 " [+-" '(setq v1 (point)) str
4071 '(save-excursion
4072 (while (search-backward ":" v1 t)
4073 (replace-match " ARG] [+-" t t)))
4074 (if (eq (preceding-char) ?-) -5)
4075 (if (and (sequencep v1) (length v1)) "] " "} ")
4076 "[--] ARGS...\"" \n
4077 "exit 2" > \n
4078 "esac" >
4079 \n "done"
4080 > \n
4081 "shift " (sh-add "OPTIND" -1) \n
4082 "OPTIND=1" \n))
4083
4084
4085
4086 (defun sh-assignment (arg)
4087 "Remember preceding identifier for future completion and do self-insert."
4088 (interactive "p")
4089 (self-insert-command arg)
4090 (if (<= arg 1)
4091 (sh-remember-variable
4092 (save-excursion
4093 (if (re-search-forward (sh-feature sh-assignment-regexp)
4094 (prog1 (point)
4095 (beginning-of-line 1))
4096 t)
4097 (match-string 1))))))
4098
4099
4100 (defun sh-maybe-here-document (arg)
4101 "Insert self. Without prefix, following unquoted `<' inserts here document.
4102 The document is bounded by `sh-here-document-word'."
4103 (declare (obsolete sh-electric-here-document-mode "24.3"))
4104 (interactive "*P")
4105 (self-insert-command (prefix-numeric-value arg))
4106 (or arg (sh--maybe-here-document)))
4107
4108 (defun sh--maybe-here-document ()
4109 (or (not (looking-back "[^<]<<"))
4110 (save-excursion
4111 (backward-char 2)
4112 (sh-quoted-p))
4113 (nth 8 (syntax-ppss))
4114 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
4115 (make-string (/ (current-indentation) tab-width) ?\t)
4116 ""))
4117 (delim (replace-regexp-in-string "['\"]" ""
4118 sh-here-document-word)))
4119 (insert sh-here-document-word)
4120 (or (eolp) (looking-at "[ \t]") (insert ?\s))
4121 (end-of-line 1)
4122 (while
4123 (sh-quoted-p)
4124 (end-of-line 2))
4125 (insert ?\n tabs)
4126 (save-excursion
4127 (insert ?\n tabs (replace-regexp-in-string
4128 "\\`-?[ \t]*" "" delim))))))
4129
4130 (define-minor-mode sh-electric-here-document-mode
4131 "Make << insert a here document skeleton."
4132 nil nil nil
4133 (if sh-electric-here-document-mode
4134 (add-hook 'post-self-insert-hook #'sh--maybe-here-document nil t)
4135 (remove-hook 'post-self-insert-hook #'sh--maybe-here-document t)))
4136 \f
4137 ;; various other commands
4138
4139 (defun sh-beginning-of-command ()
4140 ;; FIXME: Redefine using SMIE.
4141 "Move point to successive beginnings of commands."
4142 (interactive)
4143 (if (re-search-backward sh-beginning-of-command nil t)
4144 (goto-char (match-beginning 2))))
4145
4146 (defun sh-end-of-command ()
4147 ;; FIXME: Redefine using SMIE.
4148 "Move point to successive ends of commands."
4149 (interactive)
4150 (if (re-search-forward sh-end-of-command nil t)
4151 (goto-char (match-end 1))))
4152
4153 ;; Backslashification. Stolen from make-mode.el.
4154
4155 (defun sh-backslash-region (from to delete-flag)
4156 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4157 With no argument, inserts backslashes and aligns existing backslashes.
4158 With an argument, deletes the backslashes.
4159
4160 This function does not modify the last line of the region if the region ends
4161 right at the start of the following line; it does not modify blank lines
4162 at the start of the region. So you can put the region around an entire
4163 shell command and conveniently use this command."
4164 (interactive "r\nP")
4165 (save-excursion
4166 (goto-char from)
4167 (let ((column sh-backslash-column)
4168 (endmark (make-marker)))
4169 (move-marker endmark to)
4170 ;; Compute the smallest column number past the ends of all the lines.
4171 (if sh-backslash-align
4172 (progn
4173 (if (not delete-flag)
4174 (while (< (point) to)
4175 (end-of-line)
4176 (if (= (preceding-char) ?\\)
4177 (progn (forward-char -1)
4178 (skip-chars-backward " \t")))
4179 (setq column (max column (1+ (current-column))))
4180 (forward-line 1)))
4181 ;; Adjust upward to a tab column, if that doesn't push
4182 ;; past the margin.
4183 (if (> (% column tab-width) 0)
4184 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
4185 tab-width)))
4186 (if (< adjusted (window-width))
4187 (setq column adjusted))))))
4188 ;; Don't modify blank lines at start of region.
4189 (goto-char from)
4190 (while (and (< (point) endmark) (eolp))
4191 (forward-line 1))
4192 ;; Add or remove backslashes on all the lines.
4193 (while (and (< (point) endmark)
4194 ;; Don't backslashify the last line
4195 ;; if the region ends right at the start of the next line.
4196 (save-excursion
4197 (forward-line 1)
4198 (< (point) endmark)))
4199 (if (not delete-flag)
4200 (sh-append-backslash column)
4201 (sh-delete-backslash))
4202 (forward-line 1))
4203 (move-marker endmark nil))))
4204
4205 (defun sh-append-backslash (column)
4206 (end-of-line)
4207 ;; Note that "\\\\" is needed to get one backslash.
4208 (if (= (preceding-char) ?\\)
4209 (progn (forward-char -1)
4210 (delete-horizontal-space)
4211 (indent-to column (if sh-backslash-align nil 1)))
4212 (indent-to column (if sh-backslash-align nil 1))
4213 (insert "\\")))
4214
4215 (defun sh-delete-backslash ()
4216 (end-of-line)
4217 (or (bolp)
4218 (progn
4219 (forward-char -1)
4220 (if (looking-at "\\\\")
4221 (delete-region (1+ (point))
4222 (progn (skip-chars-backward " \t") (point)))))))
4223
4224 (provide 'sh-script)
4225
4226 ;;; sh-script.el ends here