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