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