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