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