* lisp/progmodes/sh-script.el (sh-smie--sh-keyword-p): Handle variable
[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 (cond
1836 ((looking-at "[[:alnum:]_]+=") nil)
1837 ((equal tok "in") (sh-smie--sh-keyword-in-p))
1838 (t (sh-smie--keyword-p))))
1839
1840 (defun sh-smie-sh-forward-token ()
1841 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1842 (save-excursion
1843 (skip-chars-backward " \t")
1844 (not (bolp))))
1845 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1846 ;; Right before a here-doc.
1847 (let ((forward-sexp-function nil))
1848 (forward-sexp 1)
1849 ;; Pretend the here-document is a "newline representing a
1850 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1851 ";")
1852 (let ((semi (sh-smie--newline-semi-p)))
1853 (forward-line 1)
1854 (if (or semi (eobp)) ";"
1855 (sh-smie-sh-forward-token))))
1856 (forward-comment (point-max))
1857 (cond
1858 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1859 ((looking-at sh-smie--sh-operators-re)
1860 (goto-char (match-end 0))
1861 (let ((tok (match-string-no-properties 0)))
1862 (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1863 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1864 (forward-line 1))
1865 tok))
1866 (t
1867 (let* ((pos (point))
1868 (tok (smie-default-forward-token)))
1869 (cond
1870 ((equal tok ")") "case-)")
1871 ((equal tok "(") "case-(")
1872 ((and tok (string-match "\\`[a-z]" tok)
1873 (assoc tok smie-grammar)
1874 (not
1875 (save-excursion
1876 (goto-char pos)
1877 (sh-smie--sh-keyword-p tok))))
1878 " word ")
1879 (t tok)))))))
1880
1881 (defun sh-smie--looking-back-at-continuation-p ()
1882 (save-excursion
1883 (and (if (eq (char-before) ?\n) (progn (forward-char -1) t) (eolp))
1884 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1885 (line-beginning-position)))))
1886
1887 (defun sh-smie-sh-backward-token ()
1888 (let ((bol (line-beginning-position)))
1889 (forward-comment (- (point)))
1890 (cond
1891 ((and (bolp) (not (bobp))
1892 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1893 (not (nth 3 (syntax-ppss))))
1894 ;; Right after a here-document.
1895 (let ((forward-sexp-function nil))
1896 (forward-sexp -1)
1897 ;; Pretend the here-document is a "newline representing a
1898 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1899 ";"))
1900 ((< (point) bol)
1901 (cond
1902 ((sh-smie--looking-back-at-continuation-p)
1903 (forward-char -1)
1904 (funcall smie-backward-token-function))
1905 ((sh-smie--newline-semi-p) ";")
1906 (t (funcall smie-backward-token-function))))
1907 ((looking-back sh-smie--sh-operators-back-re
1908 (line-beginning-position) 'greedy)
1909 (goto-char (match-beginning 1))
1910 (match-string-no-properties 1))
1911 (t
1912 (let ((tok (smie-default-backward-token)))
1913 (cond
1914 ((equal tok ")") "case-)")
1915 ((equal tok "(") "case-(")
1916 ((and tok (string-match "\\`[a-z]" tok)
1917 (assoc tok smie-grammar)
1918 (not (save-excursion (sh-smie--sh-keyword-p tok))))
1919 " word ")
1920 (t tok)))))))
1921
1922 (defcustom sh-indent-after-continuation t
1923 "If non-nil, try to make sure text is indented after a line continuation."
1924 :version "24.3"
1925 :type 'boolean
1926 :group 'sh-indentation)
1927
1928 (defun sh-smie--continuation-start-indent ()
1929 "Return the initial indentation of a continued line.
1930 May return nil if the line should not be treated as continued."
1931 (save-excursion
1932 (forward-line -1)
1933 (unless (sh-smie--looking-back-at-continuation-p)
1934 (current-indentation))))
1935
1936 (defun sh-smie-sh-rules (kind token)
1937 (pcase (cons kind token)
1938 (`(:elem . basic) sh-indentation)
1939 (`(:after . "case-)") (- (sh-var-value 'sh-indent-for-case-alt)
1940 (sh-var-value 'sh-indent-for-case-label)))
1941 ((and `(:before . ,_)
1942 (guard (when sh-indent-after-continuation
1943 (save-excursion
1944 (ignore-errors
1945 (skip-chars-backward " \t")
1946 (sh-smie--looking-back-at-continuation-p))))))
1947 ;; After a line-continuation, make sure the rest is indented.
1948 (let* ((sh-indent-after-continuation nil)
1949 (indent (smie-indent-calculate))
1950 (initial (sh-smie--continuation-start-indent)))
1951 (when (and (numberp indent) (numberp initial)
1952 (<= indent initial))
1953 `(column . ,(+ initial sh-indentation)))))
1954 (`(:before . ,(or `"(" `"{" `"["))
1955 (if (smie-rule-hanging-p) (smie-rule-parent)))
1956 ;; FIXME: Maybe this handling of ;; should be made into
1957 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
1958 (`(:before . ,(or `";;" `";&" `";;&"))
1959 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
1960 (cons 'column (smie-indent-keyword ";"))
1961 (smie-rule-separator kind)))
1962 (`(:after . ,(or `";;" `";&" `";;&"))
1963 (with-demoted-errors
1964 (smie-backward-sexp token)
1965 (cons 'column
1966 (if (or (smie-rule-bolp)
1967 (save-excursion
1968 (and (member (funcall smie-backward-token-function)
1969 '("in" ";;"))
1970 (smie-rule-bolp))))
1971 (current-column)
1972 (smie-indent-calculate)))))
1973 (`(:after . "|") (if (smie-rule-parent-p "|") nil 4))
1974 ;; Attempt at backward compatibility with the old config variables.
1975 (`(:before . "fi") (sh-var-value 'sh-indent-for-fi))
1976 (`(:before . "done") (sh-var-value 'sh-indent-for-done))
1977 (`(:after . "else") (sh-var-value 'sh-indent-after-else))
1978 (`(:after . "if") (sh-var-value 'sh-indent-after-if))
1979 (`(:before . "then") (sh-var-value 'sh-indent-for-then))
1980 (`(:before . "do") (sh-var-value 'sh-indent-for-do))
1981 (`(:after . "do")
1982 (sh-var-value (if (smie-rule-hanging-p)
1983 'sh-indent-after-loop-construct 'sh-indent-after-do)))
1984 ;; sh-indent-after-done: aligned completely differently.
1985 (`(:after . "in") (sh-var-value 'sh-indent-for-case-label))
1986 ;; sh-indent-for-continuation: Line continuations are handled differently.
1987 (`(:after . ,(or `"(" `"{" `"[")) (sh-var-value 'sh-indent-after-open))
1988 ;; sh-indent-after-function: we don't handle it differently.
1989 ))
1990
1991 ;; (defconst sh-smie-csh-grammar
1992 ;; (smie-prec2->grammar
1993 ;; (smie-bnf->prec2
1994 ;; '((exp) ;A constant, or a $var, or a sequence of them...
1995 ;; (elseifcmd (cmd)
1996 ;; (cmd "else" "else-if" exp "then" elseifcmd))
1997 ;; (cmd ("switch" branches "endsw")
1998 ;; ("if" exp)
1999 ;; ("if" exp "then" cmd "endif")
2000 ;; ("if" exp "then" cmd "else" cmd "endif")
2001 ;; ("if" exp "then" elseifcmd "endif")
2002 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
2003 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2004 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2005 ;; ;; "else" cmd "endif")
2006 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2007 ;; ;; "else" "if" exp "then" cmd "endif")
2008 ;; ("while" cmd "end")
2009 ;; ("foreach" cmd "end")
2010 ;; (cmd "|" cmd) (cmd "|&" cmd)
2011 ;; (cmd "&&" cmd) (cmd "||" cmd)
2012 ;; (cmd ";" cmd) (cmd "&" cmd))
2013 ;; ;; This is a lie, but (combined with the corresponding disambiguation
2014 ;; ;; rule) it makes it more clear that `case' and `default' are the key
2015 ;; ;; separators and the `:' is a secondary tokens.
2016 ;; (branches (branches "case" branches)
2017 ;; (branches "default" branches)
2018 ;; (exp ":" branches)))
2019 ;; '((assoc "else" "then" "endif"))
2020 ;; '((assoc "case" "default") (nonassoc ":"))
2021 ;; '((assoc ";;" ";&" ";;&"))
2022 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2023
2024 ;;;; SMIE support for `rc'.
2025
2026 (defconst sh-smie-rc-grammar
2027 (smie-prec2->grammar
2028 (smie-bnf->prec2
2029 '((exp) ;A constant, or a $var, or a sequence of them...
2030 (cmd (cmd "case" cmd)
2031 ("if" exp)
2032 ("switch" exp)
2033 ("for" exp) ("while" exp)
2034 (cmd "|" cmd) (cmd "|&" cmd)
2035 (cmd "&&" cmd) (cmd "||" cmd)
2036 (cmd ";" cmd) (cmd "&" cmd))
2037 (pattern (pattern "|" pattern))
2038 (branches (branches ";;" branches)
2039 (branches ";&" branches) (branches ";;&" branches) ;bash.
2040 (pattern "case-)" cmd)))
2041 '((assoc ";;" ";&" ";;&"))
2042 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2043
2044 (defun sh-smie--rc-after-special-arg-p ()
2045 "Check if we're after the first arg of an if/while/for/... construct.
2046 Returns the construct's token and moves point before it, if so."
2047 (forward-comment (- (point)))
2048 (when (looking-back ")\\|\\_<not" (- (point) 3))
2049 (ignore-errors
2050 (let ((forward-sexp-function nil))
2051 (forward-sexp -1)
2052 (car (member (funcall smie-backward-token-function)
2053 '("if" "for" "switch" "while")))))))
2054
2055 (defun sh-smie--rc-newline-semi-p ()
2056 "Return non-nil if a newline should be treated as a semi-colon.
2057 Point should be before the newline."
2058 (save-excursion
2059 (let ((tok (funcall smie-backward-token-function)))
2060 (if (or (when (equal tok "not") (forward-word 1) t)
2061 (and (zerop (length tok)) (eq (char-before) ?\))))
2062 (not (sh-smie--rc-after-special-arg-p))
2063 (sh-smie--newline-semi-p tok)))))
2064
2065 (defun sh-smie-rc-forward-token ()
2066 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2067 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2068 (save-excursion
2069 (skip-chars-backward " \t")
2070 (not (bolp))))
2071 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2072 ;; Right before a here-doc.
2073 (let ((forward-sexp-function nil))
2074 (forward-sexp 1)
2075 ;; Pretend the here-document is a "newline representing a
2076 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2077 ";")
2078 (let ((semi (sh-smie--rc-newline-semi-p)))
2079 (forward-line 1)
2080 (if (or semi (eobp)) ";"
2081 (sh-smie-rc-forward-token))))
2082 (forward-comment (point-max))
2083 (cond
2084 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2085 ;; ((looking-at sh-smie--rc-operators-re)
2086 ;; (goto-char (match-end 0))
2087 ;; (let ((tok (match-string-no-properties 0)))
2088 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2089 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2090 ;; (forward-line 1))
2091 ;; tok))
2092 (t
2093 (let* ((pos (point))
2094 (tok (smie-default-forward-token)))
2095 (cond
2096 ;; ((equal tok ")") "case-)")
2097 ((and tok (string-match "\\`[a-z]" tok)
2098 (assoc tok smie-grammar)
2099 (not
2100 (save-excursion
2101 (goto-char pos)
2102 (sh-smie--keyword-p))))
2103 " word ")
2104 (t tok)))))))
2105
2106 (defun sh-smie-rc-backward-token ()
2107 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
2108 (let ((bol (line-beginning-position)))
2109 (forward-comment (- (point)))
2110 (cond
2111 ((and (bolp) (not (bobp))
2112 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2113 (not (nth 3 (syntax-ppss))))
2114 ;; Right after a here-document.
2115 (let ((forward-sexp-function nil))
2116 (forward-sexp -1)
2117 ;; Pretend the here-document is a "newline representing a
2118 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2119 ";"))
2120 ((< (point) bol) ;We skipped over a newline.
2121 (cond
2122 ;; A continued line.
2123 ((and (eolp)
2124 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2125 (line-beginning-position)))
2126 (forward-char -1)
2127 (funcall smie-backward-token-function))
2128 ((sh-smie--rc-newline-semi-p) ";")
2129 (t (funcall smie-backward-token-function))))
2130 ;; ((looking-back sh-smie--sh-operators-back-re
2131 ;; (line-beginning-position) 'greedy)
2132 ;; (goto-char (match-beginning 1))
2133 ;; (match-string-no-properties 1))
2134 (t
2135 (let ((tok (smie-default-backward-token)))
2136 (cond
2137 ;; ((equal tok ")") "case-)")
2138 ((and tok (string-match "\\`[a-z]" tok)
2139 (assoc tok smie-grammar)
2140 (not (save-excursion (sh-smie--keyword-p))))
2141 " word ")
2142 (t tok)))))))
2143
2144 (defun sh-smie-rc-rules (kind token)
2145 (pcase (cons kind token)
2146 (`(:elem . basic) sh-indentation)
2147 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
2148 (`(:after . ";")
2149 (if (smie-rule-parent-p "case")
2150 (smie-rule-parent (sh-var-value 'sh-indent-after-case))))
2151 (`(:before . "{")
2152 (save-excursion
2153 (when (sh-smie--rc-after-special-arg-p)
2154 `(column . ,(current-column)))))
2155 (`(:before . ,(or `"(" `"{" `"["))
2156 (if (smie-rule-hanging-p) (smie-rule-parent)))
2157 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2158 ;; treated as an arg to (exp) by default, which indents it all wrong.
2159 ;; To handle it right, we should extend smie-indent-exps so that the
2160 ;; preceding keyword can give special rules. Currently the only special
2161 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2162 ;; with "(exp)", which is rarely the right thing to do, but is better
2163 ;; than nothing.
2164 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
2165 ;; sh-indent-after-switch: handled implicitly by the default { rule.
2166 ))
2167
2168 ;;; End of SMIE code.
2169
2170 (defvar sh-regexp-for-done nil
2171 "A buffer-local regexp to match opening keyword for done.")
2172
2173 (defvar sh-kw-alist nil
2174 "A buffer-local, since it is shell-type dependent, list of keywords.")
2175
2176 ;; ( key-word first-on-this on-prev-line )
2177 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2178 ;; having 3 elements:
2179 ;; a keyword
2180 ;; a rule to check when the keyword appears on "this" line
2181 ;; a rule to check when the keyword appears on "the previous" line
2182 ;; The keyword is usually a string and is the first word on a line.
2183 ;; If this keyword appears on the line whose indentation is to be
2184 ;; calculated, the rule in element 2 is called. If this returns
2185 ;; non-zero, the resulting point (which may be changed by the rule)
2186 ;; is used as the default indentation.
2187 ;; If it returned false or the keyword was not found in the table,
2188 ;; then the keyword from the previous line is looked up and the rule
2189 ;; in element 3 is called. In this case, however,
2190 ;; `sh-get-indent-info' does not stop but may keep going and test
2191 ;; other keywords against rules in element 3. This is because the
2192 ;; preceding line could have, for example, an opening "if" and an
2193 ;; opening "while" keyword and we need to add the indentation offsets
2194 ;; for both.
2195 ;;
2196 (defconst sh-kw
2197 '((sh
2198 ("if" nil sh-handle-prev-if)
2199 ("elif" sh-handle-this-else sh-handle-prev-else)
2200 ("else" sh-handle-this-else sh-handle-prev-else)
2201 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2202 ("then" sh-handle-this-then sh-handle-prev-then)
2203 ("(" nil sh-handle-prev-open)
2204 ("{" nil sh-handle-prev-open)
2205 ("[" nil sh-handle-prev-open)
2206 ("}" sh-handle-this-close nil)
2207 (")" sh-handle-this-close nil)
2208 ("]" sh-handle-this-close nil)
2209 ("case" nil sh-handle-prev-case)
2210 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2211 (case-label nil sh-handle-after-case-label) ;; ???
2212 (";;" nil sh-handle-prev-case-alt-end) ;; ???
2213 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2214 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2215 ("done" sh-handle-this-done sh-handle-prev-done)
2216 ("do" sh-handle-this-do sh-handle-prev-do))
2217
2218 ;; Note: we don't need specific stuff for bash and zsh shells;
2219 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2220 ;; these shells use.
2221 (rc
2222 ("{" nil sh-handle-prev-open)
2223 ("}" sh-handle-this-close nil)
2224 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
2225
2226
2227
2228 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
2229 "Set this buffer's shell to SHELL (a string).
2230 When used interactively, insert the proper starting #!-line,
2231 and make the visited file executable via `executable-set-magic',
2232 perhaps querying depending on the value of `executable-query'.
2233
2234 When this function is called noninteractively, INSERT-FLAG (the third
2235 argument) controls whether to insert a #!-line and think about making
2236 the visited file executable, and NO-QUERY-FLAG (the second argument)
2237 controls whether to query about making the visited file executable.
2238
2239 Calls the value of `sh-set-shell-hook' if set."
2240 (interactive (list (completing-read
2241 (format "Shell \(default %s\): "
2242 sh-shell-file)
2243 ;; This used to use interpreter-mode-alist, but that is
2244 ;; no longer appropriate now that uses regexps.
2245 ;; Maybe there could be a separate variable that lists
2246 ;; the shells, used here and to construct i-mode-alist.
2247 ;; But the following is probably good enough:
2248 (append (mapcar (lambda (e) (symbol-name (car e)))
2249 sh-ancestor-alist)
2250 '("csh" "rc" "sh"))
2251 nil nil nil nil sh-shell-file)
2252 (eq executable-query 'function)
2253 t))
2254 (if (string-match "\\.exe\\'" shell)
2255 (setq shell (substring shell 0 (match-beginning 0))))
2256 (setq sh-shell (intern (file-name-nondirectory shell))
2257 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
2258 sh-shell))
2259 (if insert-flag
2260 (setq sh-shell-file
2261 (executable-set-magic shell (sh-feature sh-shell-arg)
2262 no-query-flag insert-flag)))
2263 (setq mode-line-process (format "[%s]" sh-shell))
2264 (setq-local sh-shell-variables nil)
2265 (setq-local sh-shell-variables-initialized nil)
2266 (setq-local imenu-generic-expression
2267 (sh-feature sh-imenu-generic-expression))
2268 (let ((tem (sh-feature sh-mode-syntax-table-input)))
2269 (when tem
2270 (setq-local sh-mode-syntax-table
2271 (apply 'sh-mode-syntax-table tem))
2272 (set-syntax-table sh-mode-syntax-table)))
2273 (dolist (var (sh-feature sh-variables))
2274 (sh-remember-variable var))
2275 (if (setq-local sh-indent-supported-here
2276 (sh-feature sh-indent-supported))
2277 (progn
2278 (message "Setting up indent for shell type %s" sh-shell)
2279 (let ((mksym (lambda (name)
2280 (intern (format "sh-smie-%s-%s"
2281 sh-indent-supported-here name)))))
2282 (smie-setup (symbol-value (funcall mksym "grammar"))
2283 (funcall mksym "rules")
2284 :forward-token (funcall mksym "forward-token")
2285 :backward-token (funcall mksym "backward-token")))
2286 (unless sh-use-smie
2287 (setq-local parse-sexp-lookup-properties t)
2288 (setq-local sh-kw-alist (sh-feature sh-kw))
2289 (let ((regexp (sh-feature sh-kws-for-done)))
2290 (if regexp
2291 (setq-local sh-regexp-for-done
2292 (sh-mkword-regexpr (regexp-opt regexp t)))))
2293 (message "setting up indent stuff")
2294 ;; sh-mode has already made indent-line-function local
2295 ;; but do it in case this is called before that.
2296 (setq-local indent-line-function 'sh-indent-line))
2297 (if sh-make-vars-local
2298 (sh-make-vars-local))
2299 (message "Indentation setup for shell type %s" sh-shell))
2300 (message "No indentation for this shell type.")
2301 (setq indent-line-function 'sh-basic-indent-line))
2302 (when font-lock-mode
2303 (setq font-lock-set-defaults nil)
2304 (font-lock-set-defaults)
2305 (font-lock-fontify-buffer))
2306 (setq sh-shell-process nil)
2307 (run-hooks 'sh-set-shell-hook))
2308
2309
2310 (defun sh-feature (alist &optional function)
2311 "Index ALIST by the current shell.
2312 If ALIST isn't a list where every element is a cons, it is returned as is.
2313 Else indexing follows an inheritance logic which works in two ways:
2314
2315 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2316 the alist contains no value for the current shell.
2317 The ultimate default is always `sh'.
2318
2319 - If the value thus looked up is a list starting with `sh-append',
2320 we call the function `sh-append' with the rest of the list as
2321 arguments, and use the value. However, the next element of the
2322 list is not used as-is; instead, we look it up recursively
2323 in ALIST to allow the function called to define the value for
2324 one shell to be derived from another shell.
2325 The value thus determined is physically replaced into the alist.
2326
2327 If FUNCTION is non-nil, it is called with one argument,
2328 the value thus obtained, and the result is used instead."
2329 (or (if (consp alist)
2330 ;; Check for something that isn't a valid alist.
2331 (let ((l alist))
2332 (while (and l (consp (car l)))
2333 (setq l (cdr l)))
2334 (if l alist)))
2335
2336 (let ((orig-sh-shell sh-shell))
2337 (let ((sh-shell sh-shell)
2338 elt val)
2339 (while (and sh-shell
2340 (not (setq elt (assq sh-shell alist))))
2341 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2342 ;; If the shell is not known, treat it as sh.
2343 (unless elt
2344 (setq elt (assq 'sh alist)))
2345 (setq val (cdr elt))
2346 (if (and (consp val)
2347 (memq (car val) '(sh-append sh-modify)))
2348 (setq val
2349 (apply (car val)
2350 ;; Refer to the value for a different shell,
2351 ;; as a kind of inheritance.
2352 (let ((sh-shell (car (cdr val))))
2353 (sh-feature alist))
2354 (cddr val))))
2355 (if function
2356 (setq sh-shell orig-sh-shell
2357 val (funcall function val)))
2358 val))))
2359
2360
2361
2362 ;; I commented this out because nobody calls it -- rms.
2363 ;;(defun sh-abbrevs (ancestor &rest list)
2364 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
2365 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2366 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2367 ;;according to the remaining arguments NAMEi EXPANSIONi ...
2368 ;;EXPANSION may be either a string or a skeleton command."
2369 ;; (or (if (boundp sh-shell)
2370 ;; (symbol-value sh-shell))
2371 ;; (progn
2372 ;; (if (listp ancestor)
2373 ;; (nconc list ancestor))
2374 ;; (define-abbrev-table sh-shell ())
2375 ;; (if (vectorp ancestor)
2376 ;; (mapatoms (lambda (atom)
2377 ;; (or (eq atom 0)
2378 ;; (define-abbrev (symbol-value sh-shell)
2379 ;; (symbol-name atom)
2380 ;; (symbol-value atom)
2381 ;; (symbol-function atom))))
2382 ;; ancestor))
2383 ;; (while list
2384 ;; (define-abbrev (symbol-value sh-shell)
2385 ;; (car list)
2386 ;; (if (stringp (car (cdr list)))
2387 ;; (car (cdr list))
2388 ;; "")
2389 ;; (if (symbolp (car (cdr list)))
2390 ;; (car (cdr list))))
2391 ;; (setq list (cdr (cdr list)))))
2392 ;; (symbol-value sh-shell)))
2393
2394
2395 (defun sh-append (ancestor &rest list)
2396 "Return list composed of first argument (a list) physically appended to rest."
2397 (nconc list ancestor))
2398
2399
2400 (defun sh-modify (skeleton &rest list)
2401 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2402 (setq skeleton (copy-sequence skeleton))
2403 (while list
2404 (setcar (or (nthcdr (car list) skeleton)
2405 (error "Index %d out of bounds" (car list)))
2406 (car (cdr list)))
2407 (setq list (nthcdr 2 list)))
2408 skeleton)
2409
2410
2411 (defun sh-basic-indent-line ()
2412 "Indent a line for Sh mode (shell script mode).
2413 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2414 Lines containing only comments are considered empty."
2415 (interactive)
2416 (let ((previous (save-excursion
2417 (while (and (progn (beginning-of-line)
2418 (not (bobp)))
2419 (progn
2420 (forward-line -1)
2421 (back-to-indentation)
2422 (or (eolp)
2423 (eq (following-char) ?#)))))
2424 (current-column)))
2425 current)
2426 (save-excursion
2427 (indent-to (if (eq this-command 'newline-and-indent)
2428 previous
2429 (if (< (current-column)
2430 (setq current (progn (back-to-indentation)
2431 (current-column))))
2432 (if (eolp) previous 0)
2433 (delete-region (point)
2434 (progn (beginning-of-line) (point)))
2435 (if (eolp)
2436 (max previous (* (1+ (/ current sh-indentation))
2437 sh-indentation))
2438 (* (1+ (/ current sh-indentation)) sh-indentation))))))
2439 (if (< (current-column) (current-indentation))
2440 (skip-chars-forward " \t"))))
2441
2442
2443 (defun sh-execute-region (start end &optional flag)
2444 "Pass optional header and region to a subshell for noninteractive execution.
2445 The working directory is that of the buffer, and only environment variables
2446 are already set which is why you can mark a header within the script.
2447
2448 With a positive prefix ARG, instead of sending region, define header from
2449 beginning of buffer to point. With a negative prefix ARG, instead of sending
2450 region, clear header."
2451 (interactive "r\nP")
2452 (if flag
2453 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2454 (point-marker)))
2455 (if sh-header-marker
2456 (save-excursion
2457 (let (buffer-undo-list)
2458 (goto-char sh-header-marker)
2459 (append-to-buffer (current-buffer) start end)
2460 (shell-command-on-region (point-min)
2461 (setq end (+ sh-header-marker
2462 (- end start)))
2463 sh-shell-file)
2464 (delete-region sh-header-marker end)))
2465 (shell-command-on-region start end (concat sh-shell-file " -")))))
2466
2467
2468 (defun sh-remember-variable (var)
2469 "Make VARIABLE available for future completing reads in this buffer."
2470 (or (< (length var) sh-remember-variable-min)
2471 (getenv var)
2472 (assoc var sh-shell-variables)
2473 (push (cons var var) sh-shell-variables))
2474 var)
2475
2476
2477
2478 (defun sh-quoted-p ()
2479 "Is point preceded by an odd number of backslashes?"
2480 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
2481 \f
2482 ;; Indentation stuff.
2483 (defun sh-must-support-indent ()
2484 "Signal an error if the shell type for this buffer is not supported.
2485 Also, the buffer must be in Shell-script mode."
2486 (unless sh-indent-supported-here
2487 (error "This buffer's shell does not support indentation through Emacs")))
2488
2489 (defun sh-make-vars-local ()
2490 "Make the indentation variables local to this buffer.
2491 Normally they already are local. This command is provided in case
2492 variable `sh-make-vars-local' has been set to nil.
2493
2494 To revert all these variables to the global values, use
2495 command `sh-reset-indent-vars-to-global-values'."
2496 (interactive)
2497 (mapc 'make-local-variable sh-var-list)
2498 (message "Indentation variables are now local."))
2499
2500 (defun sh-reset-indent-vars-to-global-values ()
2501 "Reset local indentation variables to the global values.
2502 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2503 (interactive)
2504 (mapc 'kill-local-variable sh-var-list)
2505 (if sh-make-vars-local
2506 (mapcar 'make-local-variable sh-var-list)))
2507
2508
2509 ;; Theoretically these are only needed in shell and derived modes.
2510 ;; However, the routines which use them are only called in those modes.
2511 (defconst sh-special-keywords "then\\|do")
2512
2513 (defun sh-help-string-for-variable (var)
2514 "Construct a string for `sh-read-variable' when changing variable VAR ."
2515 (let ((msg (documentation-property var 'variable-documentation))
2516 (msg2 ""))
2517 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
2518 (setq msg2
2519 (format "\n
2520 You can enter a number (positive to increase indentation,
2521 negative to decrease indentation, zero for no change to indentation).
2522
2523 Or, you can enter one of the following symbols which are relative to
2524 the value of variable `sh-basic-offset'
2525 which in this buffer is currently %s.
2526
2527 \t%s."
2528 sh-basic-offset
2529 (mapconcat (lambda (x)
2530 (nth (1- (length x)) x))
2531 sh-symbol-list "\n\t"))))
2532 (concat
2533 ;; The following shows the global not the local value!
2534 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2535 msg msg2)))
2536
2537 (defun sh-read-variable (var)
2538 "Read a new value for indentation variable VAR."
2539 (let ((minibuffer-help-form `(sh-help-string-for-variable
2540 (quote ,var)))
2541 val)
2542 (setq val (read-from-minibuffer
2543 (format "New value for %s (press %s for help): "
2544 var (single-key-description help-char))
2545 (format "%s" (symbol-value var))
2546 nil t))
2547 val))
2548
2549
2550
2551 (defun sh-in-comment-or-string (start)
2552 "Return non-nil if START is in a comment or string."
2553 (save-excursion
2554 (let ((state (syntax-ppss start)))
2555 (or (nth 3 state) (nth 4 state)))))
2556
2557 (defun sh-goto-matching-if ()
2558 "Go to the matching if for a fi.
2559 This handles nested if..fi pairs."
2560 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2561 (if found
2562 (goto-char found))))
2563
2564
2565 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2566 ;; line whose indentation is being handled contain XXX;
2567 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2568
2569 (defun sh-handle-prev-if ()
2570 (list '(+ sh-indent-after-if)))
2571
2572 (defun sh-handle-this-else ()
2573 (if (sh-goto-matching-if)
2574 ;; (list "aligned to if")
2575 (list "aligned to if" '(+ sh-indent-for-else))
2576 nil
2577 ))
2578
2579 (defun sh-handle-prev-else ()
2580 (if (sh-goto-matching-if)
2581 (list '(+ sh-indent-after-if))
2582 ))
2583
2584 (defun sh-handle-this-fi ()
2585 (if (sh-goto-matching-if)
2586 (list "aligned to if" '(+ sh-indent-for-fi))
2587 nil
2588 ))
2589
2590 (defun sh-handle-prev-fi ()
2591 ;; Why do we have this rule? Because we must go back to the if
2592 ;; to get its indent. We may continue back from there.
2593 ;; We return nil because we don't have anything to add to result,
2594 ;; the side affect of setting align-point is all that matters.
2595 ;; we could return a comment (a string) but I can't think of a good one...
2596 (sh-goto-matching-if)
2597 nil)
2598
2599 (defun sh-handle-this-then ()
2600 (let ((p (sh-goto-matching-if)))
2601 (if p
2602 (list '(+ sh-indent-for-then))
2603 )))
2604
2605 (defun sh-handle-prev-then ()
2606 (let ((p (sh-goto-matching-if)))
2607 (if p
2608 (list '(+ sh-indent-after-if))
2609 )))
2610
2611 (defun sh-handle-prev-open ()
2612 (save-excursion
2613 (let ((x (sh-prev-stmt)))
2614 (if (and x
2615 (progn
2616 (goto-char x)
2617 (or
2618 (looking-at "function\\b")
2619 (looking-at "\\s-*\\S-+\\s-*()")
2620 )))
2621 (list '(+ sh-indent-after-function))
2622 (list '(+ sh-indent-after-open)))
2623 )))
2624
2625 (defun sh-handle-this-close ()
2626 (forward-char 1) ;; move over ")"
2627 (if (sh-safe-forward-sexp -1)
2628 (list "aligned to opening paren")))
2629
2630 (defun sh-goto-matching-case ()
2631 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2632 (if found (goto-char found))))
2633
2634 (defun sh-handle-prev-case ()
2635 ;; This is typically called when point is on same line as a case
2636 ;; we shouldn't -- and can't find prev-case
2637 (if (looking-at ".*\\<case\\>")
2638 (list '(+ sh-indent-for-case-label))
2639 (error "We don't seem to be on a line with a case"))) ;; debug
2640
2641 (defun sh-handle-this-esac ()
2642 (if (sh-goto-matching-case)
2643 (list "aligned to matching case")))
2644
2645 (defun sh-handle-prev-esac ()
2646 (if (sh-goto-matching-case)
2647 (list "matching case")))
2648
2649 (defun sh-handle-after-case-label ()
2650 (if (sh-goto-matching-case)
2651 (list '(+ sh-indent-for-case-alt))))
2652
2653 (defun sh-handle-prev-case-alt-end ()
2654 (if (sh-goto-matching-case)
2655 (list '(+ sh-indent-for-case-label))))
2656
2657 (defun sh-safe-forward-sexp (&optional arg)
2658 "Try and do a `forward-sexp', but do not error.
2659 Return new point if successful, nil if an error occurred."
2660 (condition-case nil
2661 (progn
2662 (forward-sexp (or arg 1))
2663 (point)) ;; return point if successful
2664 (error
2665 (sh-debug "oops!(1) %d" (point))
2666 nil))) ;; return nil if fail
2667
2668 (defun sh-goto-match-for-done ()
2669 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2670 (if found
2671 (goto-char found))))
2672
2673 (defun sh-handle-this-done ()
2674 (if (sh-goto-match-for-done)
2675 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2676
2677 (defun sh-handle-prev-done ()
2678 (if (sh-goto-match-for-done)
2679 (list "previous done")))
2680
2681 (defun sh-handle-this-do ()
2682 (if (sh-goto-match-for-done)
2683 (list '(+ sh-indent-for-do))))
2684
2685 (defun sh-handle-prev-do ()
2686 (cond
2687 ((save-restriction
2688 (narrow-to-region (point) (line-beginning-position))
2689 (sh-goto-match-for-done))
2690 (sh-debug "match for done found on THIS line")
2691 (list '(+ sh-indent-after-loop-construct)))
2692 ((sh-goto-match-for-done)
2693 (sh-debug "match for done found on PREV line")
2694 (list '(+ sh-indent-after-do)))
2695 (t
2696 (message "match for done NOT found")
2697 nil)))
2698
2699 ;; for rc:
2700 (defun sh-find-prev-switch ()
2701 "Find the line for the switch keyword matching this line's case keyword."
2702 (re-search-backward "\\<switch\\>" nil t))
2703
2704 (defun sh-handle-this-rc-case ()
2705 (if (sh-find-prev-switch)
2706 (list '(+ sh-indent-after-switch))
2707 ;; (list '(+ sh-indent-for-case-label))
2708 nil))
2709
2710 (defun sh-handle-prev-rc-case ()
2711 (list '(+ sh-indent-after-case)))
2712
2713 (defun sh-check-rule (n thing)
2714 (let ((rule (nth n (assoc thing sh-kw-alist)))
2715 (val nil))
2716 (if rule
2717 (progn
2718 (setq val (funcall rule))
2719 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2720 n thing (point) rule val)))
2721 val))
2722
2723
2724 (defun sh-get-indent-info ()
2725 "Return indent-info for this line.
2726 This is a list. nil means the line is to be left as is.
2727 Otherwise it contains one or more of the following sublists:
2728 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2729 relative to. If present, this is always the first of the
2730 sublists. The indentation of the line in question is
2731 derived from the indentation of this point, possibly
2732 modified by subsequent sublists.
2733 \(+ VAR\)
2734 \(- VAR\) Get the value of variable VAR and add to or subtract from
2735 the indentation calculated so far.
2736 \(= VAR\) Get the value of variable VAR and *replace* the
2737 indentation with its value. This only occurs for
2738 special variables such as `sh-indent-comment'.
2739 STRING This is ignored for the purposes of calculating
2740 indentation, it is printed in certain cases to help show
2741 what the indentation is based on."
2742 ;; See comments before `sh-kw'.
2743 (save-excursion
2744 (let ((have-result nil)
2745 this-kw
2746 val
2747 (result nil)
2748 (align-point nil)
2749 prev-line-end x)
2750 (beginning-of-line)
2751 ;; Note: setting result to t means we are done and will return nil.
2752 ;;(This function never returns just t.)
2753 (cond
2754 ((or (nth 3 (syntax-ppss (point)))
2755 (eq (get-text-property (point) 'face) sh-heredoc-face))
2756 ;; String continuation -- don't indent
2757 (setq result t)
2758 (setq have-result t))
2759 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2760 (if (bobp)
2761 (setq result t) ;; return nil if 1st line!
2762 (setq result (list '(= sh-indent-comment)))
2763 ;; we still need to get previous line in case
2764 ;; sh-indent-comment is t (indent as normal)
2765 (setq align-point (sh-prev-line nil))
2766 (setq have-result nil)
2767 ))
2768 ) ;; cond
2769
2770 (unless have-result
2771 ;; Continuation lines are handled specially
2772 (if (sh-this-is-a-continuation)
2773 (progn
2774 (setq result
2775 (if (save-excursion
2776 (beginning-of-line)
2777 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2778 ;; By convention, if the continuation \ is not
2779 ;; preceded by a SPC or a TAB it means that the line
2780 ;; is cut at a place where spaces cannot be freely
2781 ;; added/removed. I.e. do not indent the line.
2782 (list '(= nil))
2783 ;; We assume the line being continued is already
2784 ;; properly indented...
2785 ;; (setq prev-line-end (sh-prev-line))
2786 (setq align-point (sh-prev-line nil))
2787 (list '(+ sh-indent-for-continuation))))
2788 (setq have-result t))
2789 (beginning-of-line)
2790 (skip-chars-forward " \t")
2791 (setq this-kw (sh-get-kw)))
2792
2793 ;; Handle "this" keyword: first word on the line we're
2794 ;; calculating indentation info for.
2795 (if this-kw
2796 (if (setq val (sh-check-rule 1 this-kw))
2797 (progn
2798 (setq align-point (point))
2799 (sh-debug
2800 "this - setting align-point to %d" align-point)
2801 (setq result (append result val))
2802 (setq have-result t)
2803 ;; set prev-line to continue processing remainder
2804 ;; of this line as a previous line
2805 (setq prev-line-end (point))
2806 ))))
2807
2808 (unless have-result
2809 (setq prev-line-end (sh-prev-line 'end)))
2810
2811 (if prev-line-end
2812 (save-excursion
2813 ;; We start off at beginning of this line.
2814 ;; Scan previous statements while this is <=
2815 ;; start of previous line.
2816 (goto-char prev-line-end)
2817 (setq x t)
2818 (while (and x (setq x (sh-prev-thing)))
2819 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2820 (cond
2821 ((and (equal x ")")
2822 (equal (get-text-property (1- (point)) 'syntax-table)
2823 sh-st-punc))
2824 (sh-debug "Case label) here")
2825 (setq x 'case-label)
2826 (if (setq val (sh-check-rule 2 x))
2827 (progn
2828 (setq result (append result val))
2829 (setq align-point (point))))
2830 (or (bobp)
2831 (forward-char -1))
2832 ;; FIXME: This charset looks too much like a regexp. --Stef
2833 (skip-chars-forward "[a-z0-9]*?")
2834 )
2835 ((string-match "[])}]" x)
2836 (setq x (sh-safe-forward-sexp -1))
2837 (if x
2838 (progn
2839 (setq align-point (point))
2840 (setq result (append result
2841 (list "aligned to opening paren")))
2842 )))
2843 ((string-match "[[({]" x)
2844 (sh-debug "Checking special thing: %s" x)
2845 (if (setq val (sh-check-rule 2 x))
2846 (setq result (append result val)))
2847 (forward-char -1)
2848 (setq align-point (point)))
2849 ((string-match "[\"'`]" x)
2850 (sh-debug "Skipping back for %s" x)
2851 ;; this was oops-2
2852 (setq x (sh-safe-forward-sexp -1)))
2853 ((stringp x)
2854 (sh-debug "Checking string %s at %s" x (point))
2855 (if (setq val (sh-check-rule 2 x))
2856 ;; (or (eq t (car val))
2857 ;; (eq t (car (car val))))
2858 (setq result (append result val)))
2859 ;; not sure about this test Wed Jan 27 23:48:35 1999
2860 (setq align-point (point))
2861 (unless (bolp)
2862 (forward-char -1)))
2863 (t
2864 (error "Don't know what to do with %s" x))
2865 )
2866 ) ;; while
2867 (sh-debug "result is %s" result)
2868 )
2869 (sh-debug "No prev line!")
2870 (sh-debug "result: %s align-point: %s" result align-point)
2871 )
2872
2873 (if align-point
2874 ;; was: (setq result (append result (list (list t align-point))))
2875 (setq result (append (list (list t align-point)) result))
2876 )
2877 (sh-debug "result is now: %s" result)
2878
2879 (or result
2880 (setq result (list (if prev-line-end
2881 (list t prev-line-end)
2882 (list '= 'sh-first-lines-indent)))))
2883
2884 (if (eq result t)
2885 (setq result nil))
2886 (sh-debug "result is: %s" result)
2887 result
2888 ) ;; let
2889 ))
2890
2891
2892 (defun sh-get-indent-var-for-line (&optional info)
2893 "Return the variable controlling indentation for this line.
2894 If there is not [just] one such variable, return a string
2895 indicating the problem.
2896 If INFO is supplied it is used, else it is calculated."
2897 (let ((var nil)
2898 (result nil)
2899 (reason nil)
2900 sym elt)
2901 (or info
2902 (setq info (sh-get-indent-info)))
2903 (if (null info)
2904 (setq result "this line to be left as is")
2905 (while (and info (null result))
2906 (setq elt (car info))
2907 (cond
2908 ((stringp elt)
2909 (setq reason elt)
2910 )
2911 ((not (listp elt))
2912 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2913 ;; so it is a list
2914 ((eq t (car elt))
2915 ) ;; nothing
2916 ((symbolp (setq sym (nth 1 elt)))
2917 ;; A bit of a kludge - when we see the sh-indent-comment
2918 ;; ignore other variables. Otherwise it is tricky to
2919 ;; "learn" the comment indentation.
2920 (if (eq var 'sh-indent-comment)
2921 (setq result var)
2922 (if var
2923 (setq result
2924 "this line is controlled by more than 1 variable.")
2925 (setq var sym))))
2926 (t
2927 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2928 (setq info (cdr info))
2929 ))
2930 (or result
2931 (setq result var))
2932 (or result
2933 (setq result reason))
2934 (if (null result)
2935 ;; e.g. just had (t POS)
2936 (setq result "line has default indentation"))
2937 result))
2938
2939
2940
2941 ;; Finding the previous line isn't trivial.
2942 ;; We must *always* go back one more and see if that is a continuation
2943 ;; line -- it is the PREVIOUS line which is continued, not the one
2944 ;; we are going to!
2945 ;; Also, we want to treat a whole "here document" as one big line,
2946 ;; because we may want to a align to the beginning of it.
2947 ;;
2948 ;; What we do:
2949 ;; - go back to previous non-empty line
2950 ;; - if this is in a here-document, go to the beginning of it
2951 ;; - while previous line is continued, go back one line
2952 (defun sh-prev-line (&optional end)
2953 "Back to end of previous non-comment non-empty line.
2954 Go to beginning of logical line unless END is non-nil, in which case
2955 we go to the end of the previous line and do not check for continuations."
2956 (save-excursion
2957 (beginning-of-line)
2958 (forward-comment (- (point-max)))
2959 (unless end (beginning-of-line))
2960 (when (and (not (bobp))
2961 (equal (get-text-property (1- (point)) 'face)
2962 sh-heredoc-face))
2963 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2964 (when p1
2965 (goto-char p1)
2966 (if end
2967 (end-of-line)
2968 (beginning-of-line)))))
2969 (unless end
2970 ;; we must check previous lines to see if they are continuation lines
2971 ;; if so, we must return position of first of them
2972 (while (and (sh-this-is-a-continuation)
2973 (>= 0 (forward-line -1))))
2974 (beginning-of-line)
2975 (skip-chars-forward " \t"))
2976 (point)))
2977
2978
2979 (defun sh-prev-stmt ()
2980 "Return the address of the previous stmt or nil."
2981 ;; This is used when we are trying to find a matching keyword.
2982 ;; Searching backward for the keyword would certainly be quicker, but
2983 ;; it is hard to remove "false matches" -- such as if the keyword
2984 ;; appears in a string or quote. This way is slower, but (I think) safer.
2985 (interactive)
2986 (save-excursion
2987 (let ((going t)
2988 (start (point))
2989 (found nil)
2990 (prev nil))
2991 (skip-chars-backward " \t;|&({[")
2992 (while (and (not found)
2993 (not (bobp))
2994 going)
2995 ;; Do a backward-sexp if possible, else backup bit by bit...
2996 (if (sh-safe-forward-sexp -1)
2997 (progn
2998 (if (looking-at sh-special-keywords)
2999 (progn
3000 (setq found prev))
3001 (setq prev (point))
3002 ))
3003 ;; backward-sexp failed
3004 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
3005 (forward-char -1))
3006 (if (bolp)
3007 (let ((back (sh-prev-line nil)))
3008 (if back
3009 (goto-char back)
3010 (setq going nil)))))
3011 (unless found
3012 (skip-chars-backward " \t")
3013 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
3014 (eq (char-before) ?\;)
3015 (looking-at "\\s-*[|&]"))
3016 (setq found (point)))))
3017 (if found
3018 (goto-char found))
3019 (if found
3020 (progn
3021 (skip-chars-forward " \t|&({[")
3022 (setq found (point))))
3023 (if (>= (point) start)
3024 (progn
3025 (debug "We didn't move!")
3026 (setq found nil))
3027 (or found
3028 (sh-debug "Did not find prev stmt.")))
3029 found)))
3030
3031
3032 (defun sh-get-word ()
3033 "Get a shell word skipping whitespace from point."
3034 (interactive)
3035 (skip-chars-forward "\t ")
3036 (let ((start (point)))
3037 (while
3038 (if (looking-at "[\"'`]")
3039 (sh-safe-forward-sexp)
3040 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
3041 (> (skip-chars-forward "-_$[:alnum:]") 0)
3042 ))
3043 (buffer-substring start (point))
3044 ))
3045
3046 (defun sh-prev-thing ()
3047 "Return the previous thing this logical line."
3048 ;; This is called when `sh-get-indent-info' is working backwards on
3049 ;; the previous line(s) finding what keywords may be relevant for
3050 ;; indenting. It moves over sexps if possible, and will stop
3051 ;; on a ; and at the beginning of a line if it is not a continuation
3052 ;; line.
3053 ;;
3054 ;; Added a kludge for ";;"
3055 ;; Possible return values:
3056 ;; nil - nothing
3057 ;; a string - possibly a keyword
3058 ;;
3059 (if (bolp)
3060 nil
3061 (let ((start (point))
3062 (min-point (if (sh-this-is-a-continuation)
3063 (sh-prev-line nil)
3064 (line-beginning-position))))
3065 (skip-chars-backward " \t;" min-point)
3066 (if (looking-at "\\s-*;[;&]")
3067 ;; (message "Found ;; !")
3068 ";;"
3069 (skip-chars-backward "^)}];\"'`({[" min-point)
3070 (let ((c (if (> (point) min-point) (char-before))))
3071 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
3072 (point) c start min-point)
3073 (if (not (memq c '(?\n nil ?\;)))
3074 ;; c -- return a string
3075 (char-to-string c)
3076 ;; Return the leading keyword of the "command" we supposedly
3077 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
3078 ;; `then' that precedes the actual command), so check whether
3079 ;; we're looking at such a keyword and if so, move back forward.
3080 (let ((boundary (point))
3081 kwd next)
3082 (while
3083 (progn
3084 ;; Skip forward over white space newline and \ at eol.
3085 (skip-chars-forward " \t\n\\\\" start)
3086 (if (>= (point) start)
3087 (progn
3088 (sh-debug "point: %d >= start: %d" (point) start)
3089 nil)
3090 (if next (setq boundary next))
3091 (sh-debug "Now at %d start=%d" (point) start)
3092 (setq kwd (sh-get-word))
3093 (if (member kwd (sh-feature sh-leading-keywords))
3094 (progn
3095 (setq next (point))
3096 t)
3097 nil))))
3098 (goto-char boundary)
3099 kwd)))))))
3100
3101
3102 (defun sh-this-is-a-continuation ()
3103 "Return non-nil if current line is a continuation of previous line."
3104 (save-excursion
3105 (and (zerop (forward-line -1))
3106 (looking-at ".*\\\\$")
3107 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
3108 nil nil nil t))))))
3109
3110 (defun sh-get-kw (&optional where and-move)
3111 "Return first word of line from WHERE.
3112 If AND-MOVE is non-nil then move to end of word."
3113 (let ((start (point)))
3114 (if where
3115 (goto-char where))
3116 (prog1
3117 (buffer-substring (point)
3118 (progn (skip-chars-forward "^ \t\n;&|")(point)))
3119 (unless and-move
3120 (goto-char start)))))
3121
3122 (defun sh-find-prev-matching (open close &optional depth)
3123 "Find a matching token for a set of opening and closing keywords.
3124 This takes into account that there may be nested open..close pairings.
3125 OPEN and CLOSE are regexps denoting the tokens to be matched.
3126 Optional parameter DEPTH (usually 1) says how many to look for."
3127 (let ((parse-sexp-ignore-comments t)
3128 (forward-sexp-function nil)
3129 prev)
3130 (setq depth (or depth 1))
3131 (save-excursion
3132 (condition-case nil
3133 (while (and
3134 (/= 0 depth)
3135 (not (bobp))
3136 (setq prev (sh-prev-stmt)))
3137 (goto-char prev)
3138 (save-excursion
3139 (if (looking-at "\\\\\n")
3140 (progn
3141 (forward-char 2)
3142 (skip-chars-forward " \t")))
3143 (cond
3144 ((looking-at open)
3145 (setq depth (1- depth))
3146 (sh-debug "found open at %d - depth = %d" (point) depth))
3147 ((looking-at close)
3148 (setq depth (1+ depth))
3149 (sh-debug "found close - depth = %d" depth))
3150 (t
3151 ))))
3152 (error nil))
3153 (if (eq depth 0)
3154 prev ;; (point)
3155 nil)
3156 )))
3157
3158
3159 (defun sh-var-value (var &optional ignore-error)
3160 "Return the value of variable VAR, interpreting symbols.
3161 It can also return t or nil.
3162 If an invalid value is found, throw an error unless Optional argument
3163 IGNORE-ERROR is non-nil."
3164 (let ((val (symbol-value var)))
3165 (cond
3166 ((numberp val)
3167 val)
3168 ((eq val t)
3169 val)
3170 ((null val)
3171 val)
3172 ((eq val '+)
3173 sh-basic-offset)
3174 ((eq val '-)
3175 (- sh-basic-offset))
3176 ((eq val '++)
3177 (* 2 sh-basic-offset))
3178 ((eq val '--)
3179 (* 2 (- sh-basic-offset)))
3180 ((eq val '*)
3181 (/ sh-basic-offset 2))
3182 ((eq val '/)
3183 (/ (- sh-basic-offset) 2))
3184 (t
3185 (funcall (if ignore-error #'message #'error)
3186 "Don't know how to handle %s's value of %s" var val)
3187 0))))
3188
3189 (defun sh-set-var-value (var value &optional no-symbol)
3190 "Set variable VAR to VALUE.
3191 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3192 can be represented by a symbol then do so."
3193 (cond
3194 (no-symbol
3195 (set var value))
3196 ((= value sh-basic-offset)
3197 (set var '+))
3198 ((= value (- sh-basic-offset))
3199 (set var '-))
3200 ((eq value (* 2 sh-basic-offset))
3201 (set var '++))
3202 ((eq value (* 2 (- sh-basic-offset)))
3203 (set var '--))
3204 ((eq value (/ sh-basic-offset 2))
3205 (set var '*))
3206 ((eq value (/ (- sh-basic-offset) 2))
3207 (set var '/))
3208 (t
3209 (set var value)))
3210 )
3211
3212
3213 (defun sh-calculate-indent (&optional info)
3214 "Return the indentation for the current line.
3215 If INFO is supplied it is used, else it is calculated from current line."
3216 (let ((ofs 0)
3217 (base-value 0)
3218 elt a b val)
3219 (or info
3220 (setq info (sh-get-indent-info)))
3221 (when info
3222 (while info
3223 (sh-debug "info: %s ofs=%s" info ofs)
3224 (setq elt (car info))
3225 (cond
3226 ((stringp elt)) ;; do nothing?
3227 ((listp elt)
3228 (setq a (car (car info)))
3229 (setq b (nth 1 (car info)))
3230 (cond
3231 ((eq a t)
3232 (save-excursion
3233 (goto-char b)
3234 (setq val (current-indentation)))
3235 (setq base-value val))
3236 ((symbolp b)
3237 (setq val (sh-var-value b))
3238 (cond
3239 ((eq a '=)
3240 (cond
3241 ((null val)
3242 ;; no indentation
3243 ;; set info to nil so we stop immediately
3244 (setq base-value nil ofs nil info nil))
3245 ((eq val t) (setq ofs 0)) ;; indent as normal line
3246 (t
3247 ;; The following assume the (t POS) come first!
3248 (setq ofs val base-value 0)
3249 (setq info nil)))) ;; ? stop now
3250 ((eq a '+) (setq ofs (+ ofs val)))
3251 ((eq a '-) (setq ofs (- ofs val)))
3252 (t
3253 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3254 (t
3255 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
3256 (t
3257 (error "sh-calculate-indent invalid elt %s" elt)))
3258 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3259 a b val base-value ofs)
3260 (setq info (cdr info)))
3261 ;; return value:
3262 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
3263
3264 (cond
3265 ((or (null base-value)(null ofs))
3266 nil)
3267 ((and (numberp base-value)(numberp ofs))
3268 (sh-debug "base (%d) + ofs (%d) = %d"
3269 base-value ofs (+ base-value ofs))
3270 (+ base-value ofs)) ;; return value
3271 (t
3272 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3273 base-value ofs)
3274 nil)))))
3275
3276
3277 (defun sh-indent-line ()
3278 "Indent the current line."
3279 (interactive)
3280 (let ((indent (sh-calculate-indent))
3281 (pos (- (point-max) (point))))
3282 (when indent
3283 (beginning-of-line)
3284 (skip-chars-forward " \t")
3285 (indent-line-to indent)
3286 ;; If initial point was within line's indentation,
3287 ;; position after the indentation. Else stay at same point in text.
3288 (if (> (- (point-max) pos) (point))
3289 (goto-char (- (point-max) pos))))))
3290
3291
3292 (defun sh-blink (blinkpos &optional msg)
3293 "Move cursor momentarily to BLINKPOS and display MSG."
3294 ;; We can get here without it being a number on first line
3295 (if (numberp blinkpos)
3296 (save-excursion
3297 (goto-char blinkpos)
3298 (if msg (message "%s" msg) (message nil))
3299 (sit-for blink-matching-delay))
3300 (if msg (message "%s" msg) (message nil))))
3301
3302 (defun sh-show-indent (arg)
3303 "Show the how the current line would be indented.
3304 This tells you which variable, if any, controls the indentation of
3305 this line.
3306 If optional arg ARG is non-null (called interactively with a prefix),
3307 a pop up window describes this variable.
3308 If variable `sh-blink' is non-nil then momentarily go to the line
3309 we are indenting relative to, if applicable."
3310 (interactive "P")
3311 (sh-must-support-indent)
3312 (if sh-use-smie
3313 (smie-config-show-indent)
3314 (let* ((info (sh-get-indent-info))
3315 (var (sh-get-indent-var-for-line info))
3316 (curr-indent (current-indentation))
3317 val msg)
3318 (if (stringp var)
3319 (message "%s" (setq msg var))
3320 (setq val (sh-calculate-indent info))
3321
3322 (if (eq curr-indent val)
3323 (setq msg (format "%s is %s" var (symbol-value var)))
3324 (setq msg
3325 (if val
3326 (format "%s (%s) would change indent from %d to: %d"
3327 var (symbol-value var) curr-indent val)
3328 (format "%s (%s) would leave line as is"
3329 var (symbol-value var)))
3330 ))
3331 (if (and arg var)
3332 (describe-variable var)))
3333 (if sh-blink
3334 (let ((info (sh-get-indent-info)))
3335 (if (and info (listp (car info))
3336 (eq (car (car info)) t))
3337 (sh-blink (nth 1 (car info)) msg)
3338 (message "%s" msg)))
3339 (message "%s" msg))
3340 )))
3341
3342 (defun sh-set-indent ()
3343 "Set the indentation for the current line.
3344 If the current line is controlled by an indentation variable, prompt
3345 for a new value for it."
3346 (interactive)
3347 (sh-must-support-indent)
3348 (if sh-use-smie
3349 (smie-config-set-indent)
3350 (let* ((info (sh-get-indent-info))
3351 (var (sh-get-indent-var-for-line info))
3352 val old-val indent-val)
3353 (if (stringp var)
3354 (message "Cannot set indent - %s" var)
3355 (setq old-val (symbol-value var))
3356 (setq val (sh-read-variable var))
3357 (condition-case nil
3358 (progn
3359 (set var val)
3360 (setq indent-val (sh-calculate-indent info))
3361 (if indent-val
3362 (message "Variable: %s Value: %s would indent to: %d"
3363 var (symbol-value var) indent-val)
3364 (message "Variable: %s Value: %s would leave line as is."
3365 var (symbol-value var)))
3366 ;; I'm not sure about this, indenting it now?
3367 ;; No. Because it would give the impression that an undo would
3368 ;; restore thing, but the value has been altered.
3369 ;; (sh-indent-line)
3370 )
3371 (error
3372 (set var old-val)
3373 (message "Bad value for %s, restoring to previous value %s"
3374 var old-val)
3375 (sit-for 1)
3376 nil))
3377 ))))
3378
3379
3380 (defun sh-learn-line-indent (arg)
3381 "Learn how to indent a line as it currently is indented.
3382
3383 If there is an indentation variable which controls this line's indentation,
3384 then set it to a value which would indent the line the way it
3385 presently is.
3386
3387 If the value can be represented by one of the symbols then do so
3388 unless optional argument ARG (the prefix when interactive) is non-nil."
3389 (interactive "*P")
3390 (sh-must-support-indent)
3391 (if sh-use-smie
3392 (smie-config-set-indent)
3393 ;; I'm not sure if we show allow learning on an empty line.
3394 ;; Though it might occasionally be useful I think it usually
3395 ;; would just be confusing.
3396 (if (save-excursion
3397 (beginning-of-line)
3398 (looking-at "\\s-*$"))
3399 (message "sh-learn-line-indent ignores empty lines.")
3400 (let* ((info (sh-get-indent-info))
3401 (var (sh-get-indent-var-for-line info))
3402 ival sval diff new-val
3403 (no-symbol arg)
3404 (curr-indent (current-indentation)))
3405 (cond
3406 ((stringp var)
3407 (message "Cannot learn line - %s" var))
3408 ((eq var 'sh-indent-comment)
3409 ;; This is arbitrary...
3410 ;; - if curr-indent is 0, set to curr-indent
3411 ;; - else if it has the indentation of a "normal" line,
3412 ;; then set to t
3413 ;; - else set to curr-indent.
3414 (setq sh-indent-comment
3415 (if (= curr-indent 0)
3416 0
3417 (let* ((sh-indent-comment t)
3418 (val2 (sh-calculate-indent info)))
3419 (if (= val2 curr-indent)
3420 t
3421 curr-indent))))
3422 (message "%s set to %s" var (symbol-value var))
3423 )
3424 ((numberp (setq sval (sh-var-value var)))
3425 (setq ival (sh-calculate-indent info))
3426 (setq diff (- curr-indent ival))
3427
3428 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3429 curr-indent ival diff var sval)
3430 (setq new-val (+ sval diff))
3431 ;; I commented out this because someone might want to replace
3432 ;; a value of `+' with the current value of sh-basic-offset
3433 ;; or vice-versa.
3434 ;;(if (= 0 diff)
3435 ;; (message "No change needed!")
3436 (sh-set-var-value var new-val no-symbol)
3437 (message "%s set to %s" var (symbol-value var))
3438 )
3439 (t
3440 (debug)
3441 (message "Cannot change %s" var)))))))
3442
3443
3444
3445 (defun sh-mark-init (buffer)
3446 "Initialize a BUFFER to be used by `sh-mark-line'."
3447 (with-current-buffer (get-buffer-create buffer)
3448 (erase-buffer)
3449 (occur-mode)))
3450
3451
3452 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
3453 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3454 Buffer BUFFER is in `occur-mode'.
3455 If ADD-LINENUM is non-nil the message is preceded by the line number.
3456 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3457 so that `occur-next' and `occur-prev' will work."
3458 (let ((m1 (make-marker))
3459 start
3460 (line ""))
3461 (when point
3462 (set-marker m1 point (current-buffer))
3463 (if add-linenum
3464 (setq line (format "%d: " (1+ (count-lines 1 point))))))
3465 (save-excursion
3466 (if (get-buffer buffer)
3467 (set-buffer (get-buffer buffer))
3468 (set-buffer (get-buffer-create buffer))
3469 (occur-mode)
3470 )
3471 (goto-char (point-max))
3472 (setq start (point))
3473 (let ((inhibit-read-only t))
3474 (insert line)
3475 (if occur-point
3476 (setq occur-point (point)))
3477 (insert message)
3478 (if point
3479 (add-text-properties
3480 start (point)
3481 '(mouse-face highlight
3482 help-echo "mouse-2: go to the line where I learned this")))
3483 (insert "\n")
3484 (when point
3485 (put-text-property start (point) 'occur-target m1)
3486 (if occur-point
3487 (put-text-property start occur-point
3488 'occur-match t))
3489 )))))
3490
3491 ;; Is this really worth having?
3492 (defvar sh-learned-buffer-hook nil
3493 "An abnormal hook, called with an alist of learned variables.")
3494 ;; Example of how to use sh-learned-buffer-hook
3495 ;;
3496 ;; (defun what-i-learned (list)
3497 ;; (let ((p list))
3498 ;; (with-current-buffer "*scratch*"
3499 ;; (goto-char (point-max))
3500 ;; (insert "(setq\n")
3501 ;; (while p
3502 ;; (insert (format " %s %s \n"
3503 ;; (nth 0 (car p)) (nth 1 (car p))))
3504 ;; (setq p (cdr p)))
3505 ;; (insert ")\n")
3506 ;; )))
3507 ;;
3508 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3509
3510
3511 ;; Originally this was sh-learn-region-indent (beg end)
3512 ;; However, in practice this was awkward so I changed it to
3513 ;; use the whole buffer. Use narrowing if need be.
3514 (defun sh-learn-buffer-indent (&optional arg)
3515 "Learn how to indent the buffer the way it currently is.
3516
3517 Output in buffer \"*indent*\" shows any lines which have conflicting
3518 values of a variable, and the final value of all variables learned.
3519 When called interactively, pop to this buffer automatically if
3520 there are any discrepancies.
3521
3522 If no prefix ARG is given, then variables are set to numbers.
3523 If a prefix arg is given, then variables are set to symbols when
3524 applicable -- e.g. to symbol `+' if the value is that of the
3525 basic indent.
3526 If a positive numerical prefix is given, then `sh-basic-offset'
3527 is set to the prefix's numerical value.
3528 Otherwise, sh-basic-offset may or may not be changed, according
3529 to the value of variable `sh-learn-basic-offset'.
3530
3531 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3532 function completes. The function is abnormal because it is called
3533 with an alist of variables learned. This feature may be changed or
3534 removed in the future.
3535
3536 This command can often take a long time to run."
3537 (interactive "P")
3538 (sh-must-support-indent)
3539 (if sh-use-smie
3540 (smie-config-guess)
3541 (save-excursion
3542 (goto-char (point-min))
3543 (let ((learned-var-list nil)
3544 (out-buffer "*indent*")
3545 (num-diffs 0)
3546 previous-set-info
3547 (max 17)
3548 vec
3549 msg
3550 (comment-col nil) ;; number if all same, t if seen diff values
3551 (comments-always-default t) ;; nil if we see one not default
3552 initial-msg
3553 (specified-basic-offset (and arg (numberp arg)
3554 (> arg 0)))
3555 (linenum 0)
3556 suggested)
3557 (setq vec (make-vector max 0))
3558 (sh-mark-init out-buffer)
3559
3560 (if specified-basic-offset
3561 (progn
3562 (setq sh-basic-offset arg)
3563 (setq initial-msg
3564 (format "Using specified sh-basic-offset of %d"
3565 sh-basic-offset)))
3566 (setq initial-msg
3567 (format "Initial value of sh-basic-offset: %s"
3568 sh-basic-offset)))
3569
3570 (while (< (point) (point-max))
3571 (setq linenum (1+ linenum))
3572 ;; (if (zerop (% linenum 10))
3573 (message "line %d" linenum)
3574 ;; )
3575 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3576 (let* ((sh-indent-comment t) ;; info must return default indent
3577 (info (sh-get-indent-info))
3578 (var (sh-get-indent-var-for-line info))
3579 sval ival diff new-val
3580 (curr-indent (current-indentation)))
3581 (cond
3582 ((null var)
3583 nil)
3584 ((stringp var)
3585 nil)
3586 ((numberp (setq sval (sh-var-value var 'no-error)))
3587 ;; the numberp excludes comments since sval will be t.
3588 (setq ival (sh-calculate-indent))
3589 (setq diff (- curr-indent ival))
3590 (setq new-val (+ sval diff))
3591 (sh-set-var-value var new-val 'no-symbol)
3592 (unless (looking-at "\\s-*#") ;; don't learn from comments
3593 (if (setq previous-set-info (assoc var learned-var-list))
3594 (progn
3595 ;; it was already there, is it same value ?
3596 (unless (eq (symbol-value var)
3597 (nth 1 previous-set-info))
3598 (sh-mark-line
3599 (format "Variable %s was set to %s"
3600 var (symbol-value var))
3601 (point) out-buffer t t)
3602 (sh-mark-line
3603 (format " but was previously set to %s"
3604 (nth 1 previous-set-info))
3605 (nth 2 previous-set-info) out-buffer t)
3606 (setq num-diffs (1+ num-diffs))
3607 ;; (delete previous-set-info learned-var-list)
3608 (setcdr previous-set-info
3609 (list (symbol-value var) (point)))
3610 )
3611 )
3612 (setq learned-var-list
3613 (append (list (list var (symbol-value var)
3614 (point)))
3615 learned-var-list)))
3616 (if (numberp new-val)
3617 (progn
3618 (sh-debug
3619 "This line's indent value: %d" new-val)
3620 (if (< new-val 0)
3621 (setq new-val (- new-val)))
3622 (if (< new-val max)
3623 (aset vec new-val (1+ (aref vec new-val))))))
3624 ))
3625 ((eq var 'sh-indent-comment)
3626 (unless (= curr-indent (sh-calculate-indent info))
3627 ;; this is not the default indentation
3628 (setq comments-always-default nil)
3629 (if comment-col ;; then we have see one before
3630 (or (eq comment-col curr-indent)
3631 (setq comment-col t)) ;; seen a different one
3632 (setq comment-col curr-indent))
3633 ))
3634 (t
3635 (sh-debug "Cannot learn this line!!!")
3636 ))
3637 (sh-debug
3638 "at %s learned-var-list is %s" (point) learned-var-list)
3639 ))
3640 (forward-line 1)
3641 ) ;; while
3642 (if sh-debug
3643 (progn
3644 (setq msg (format
3645 "comment-col = %s comments-always-default = %s"
3646 comment-col comments-always-default))
3647 ;; (message msg)
3648 (sh-mark-line msg nil out-buffer)))
3649 (cond
3650 ((eq comment-col 0)
3651 (setq msg "\nComments are all in 1st column.\n"))
3652 (comments-always-default
3653 (setq msg "\nComments follow default indentation.\n")
3654 (setq comment-col t))
3655 ((numberp comment-col)
3656 (setq msg (format "\nComments are in col %d." comment-col)))
3657 (t
3658 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3659 (setq comment-col nil)
3660 ))
3661 (sh-debug msg)
3662 (sh-mark-line msg nil out-buffer)
3663
3664 (sh-mark-line initial-msg nil out-buffer t t)
3665
3666 (setq suggested (sh-guess-basic-offset vec))
3667
3668 (if (and suggested (not specified-basic-offset))
3669 (let ((new-value
3670 (cond
3671 ;; t => set it if we have a single value as a number
3672 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3673 suggested)
3674 ;; other non-nil => set it if only one value was found
3675 (sh-learn-basic-offset
3676 (if (numberp suggested)
3677 suggested
3678 (if (= (length suggested) 1)
3679 (car suggested))))
3680 (t
3681 nil))))
3682 (if new-value
3683 (progn
3684 (setq learned-var-list
3685 (append (list (list 'sh-basic-offset
3686 (setq sh-basic-offset new-value)
3687 (point-max)))
3688 learned-var-list))
3689 ;; Not sure if we need to put this line in, since
3690 ;; it will appear in the "Learned variable settings".
3691 (sh-mark-line
3692 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3693 nil out-buffer))
3694 (sh-mark-line
3695 (if (listp suggested)
3696 (format "Possible value(s) for sh-basic-offset: %s"
3697 (mapconcat 'int-to-string suggested " "))
3698 (format "Suggested sh-basic-offset: %d" suggested))
3699 nil out-buffer))))
3700
3701
3702 (setq learned-var-list
3703 (append (list (list 'sh-indent-comment comment-col (point-max)))
3704 learned-var-list))
3705 (setq sh-indent-comment comment-col)
3706 (let ((name (buffer-name)))
3707 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3708 (if arg
3709 ;; Set learned variables to symbolic rather than numeric
3710 ;; values where possible.
3711 (dolist (learned-var (reverse learned-var-list))
3712 (let ((var (car learned-var))
3713 (val (nth 1 learned-var)))
3714 (when (and (not (eq var 'sh-basic-offset))
3715 (numberp val))
3716 (sh-set-var-value var val)))))
3717 (dolist (learned-var (reverse learned-var-list))
3718 (let ((var (car learned-var)))
3719 (sh-mark-line (format " %s %s" var (symbol-value var))
3720 (nth 2 learned-var) out-buffer)))
3721 (with-current-buffer out-buffer
3722 (goto-char (point-min))
3723 (let ((inhibit-read-only t))
3724 (insert
3725 (format "Indentation values for buffer %s.\n" name)
3726 (format "%d indentation variable%s different values%s\n\n"
3727 num-diffs
3728 (if (= num-diffs 1)
3729 " has" "s have")
3730 (if (zerop num-diffs)
3731 "." ":"))))))
3732 ;; Are abnormal hooks considered bad form?
3733 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3734 (and (called-interactively-p 'any)
3735 (or sh-popup-occur-buffer (> num-diffs 0))
3736 (pop-to-buffer out-buffer))))))
3737
3738 (defun sh-guess-basic-offset (vec)
3739 "See if we can determine a reasonable value for `sh-basic-offset'.
3740 This is experimental, heuristic and arbitrary!
3741 Argument VEC is a vector of information collected by
3742 `sh-learn-buffer-indent'.
3743 Return values:
3744 number - there appears to be a good single value
3745 list of numbers - no obvious one, here is a list of one or more
3746 reasonable choices
3747 nil - we couldn't find a reasonable one."
3748 (let* ((max (1- (length vec)))
3749 (i 1)
3750 (totals (make-vector max 0)))
3751 (while (< i max)
3752 (cl-incf (aref totals i) (* 4 (aref vec i)))
3753 (if (zerop (% i 2))
3754 (cl-incf (aref totals i) (aref vec (/ i 2))))
3755 (if (< (* i 2) max)
3756 (cl-incf (aref totals i) (aref vec (* i 2))))
3757 (setq i (1+ i)))
3758
3759 (let ((x nil)
3760 (result nil)
3761 tot sum p)
3762 (setq i 1)
3763 (while (< i max)
3764 (if (/= (aref totals i) 0)
3765 (push (cons i (aref totals i)) x))
3766 (setq i (1+ i)))
3767
3768 (setq x (sort (nreverse x) (lambda (a b) (> (cdr a) (cdr b)))))
3769 (setq tot (apply '+ (append totals nil)))
3770 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3771 vec totals tot))
3772 (cond
3773 ((zerop (length x))
3774 (message "no values!")) ;; we return nil
3775 ((= (length x) 1)
3776 (message "only value is %d" (car (car x)))
3777 (setq result (car (car x)))) ;; return single value
3778 ((> (cdr (car x)) (/ tot 2))
3779 ;; 1st is > 50%
3780 (message "basic-offset is probably %d" (car (car x)))
3781 (setq result (car (car x)))) ;; again, return a single value
3782 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3783 ;; 1st is >= 2 * 2nd
3784 (message "basic-offset could be %d" (car (car x)))
3785 (setq result (car (car x))))
3786 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3787 ;; 1st & 2nd together >= 50% - return a list
3788 (setq p x sum 0 result nil)
3789 (while (and p
3790 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3791 (setq result (append result (list (car (car p)))))
3792 (setq p (cdr p)))
3793 (message "Possible choices for sh-basic-offset: %s"
3794 (mapconcat 'int-to-string result " ")))
3795 (t
3796 (message "No obvious value for sh-basic-offset. Perhaps %d"
3797 (car (car x)))
3798 ;; result is nil here
3799 ))
3800 result)))
3801
3802 ;; ========================================================================
3803
3804 ;; Styles -- a quick and dirty way of saving the indentation settings.
3805
3806 (defvar sh-styles-alist nil
3807 "A list of all known shell indentation styles.")
3808
3809 (defun sh-name-style (name &optional confirm-overwrite)
3810 "Name the current indentation settings as a style called NAME.
3811 If this name exists, the command will prompt whether it should be
3812 overwritten if
3813 - - it was called interactively with a prefix argument, or
3814 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3815 ;; (interactive "sName for this style: ")
3816 (interactive
3817 (list
3818 (read-from-minibuffer "Name for this style? " )
3819 (not current-prefix-arg)))
3820 (let ((slist (cons name
3821 (mapcar (lambda (var) (cons var (symbol-value var)))
3822 sh-var-list)))
3823 (style (assoc name sh-styles-alist)))
3824 (if style
3825 (if (and confirm-overwrite
3826 (not (y-or-n-p "This style exists. Overwrite it? ")))
3827 (message "Not changing style %s" name)
3828 (message "Updating style %s" name)
3829 (setcdr style (cdr slist)))
3830 (message "Creating new style %s" name)
3831 (push slist sh-styles-alist))))
3832
3833 (defun sh-load-style (name)
3834 "Set shell indentation values for this buffer from those in style NAME."
3835 (interactive (list (completing-read
3836 "Which style to use for this buffer? "
3837 sh-styles-alist nil t)))
3838 (let ((sl (assoc name sh-styles-alist)))
3839 (if (null sl)
3840 (error "sh-load-style - style %s not known" name)
3841 (dolist (var (cdr sl))
3842 (set (car var) (cdr var))))))
3843
3844 (defun sh-save-styles-to-buffer (buff)
3845 "Save all current styles in elisp to buffer BUFF.
3846 This is always added to the end of the buffer."
3847 (interactive
3848 (list
3849 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3850 (with-current-buffer (get-buffer-create buff)
3851 (goto-char (point-max))
3852 (insert "\n")
3853 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3854
3855
3856 \f
3857 ;; statement syntax-commands for various shells
3858
3859 ;; You are welcome to add the syntax or even completely new statements as
3860 ;; appropriate for your favorite shell.
3861
3862 (defconst sh-non-closing-paren
3863 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3864 ;; that inherits this property, which then confuses the indentation.
3865 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3866
3867 (define-skeleton sh-case
3868 "Insert a case/switch statement. See `sh-feature'."
3869 (csh "expression: "
3870 "switch( " str " )" \n
3871 > "case " (read-string "pattern: ") ?: \n
3872 > _ \n
3873 "breaksw" \n
3874 ( "other pattern, %s: "
3875 < "case " str ?: \n
3876 > _ \n
3877 "breaksw" \n)
3878 < "default:" \n
3879 > _ \n
3880 resume:
3881 < < "endsw" \n)
3882 (es)
3883 (rc "expression: "
3884 > "switch( " str " ) {" \n
3885 > "case " (read-string "pattern: ") \n
3886 > _ \n
3887 ( "other pattern, %s: "
3888 "case " str > \n
3889 > _ \n)
3890 "case *" > \n
3891 > _ \n
3892 resume:
3893 ?\} > \n)
3894 (sh "expression: "
3895 > "case " str " in" \n
3896 ( "pattern, %s: "
3897 > str sh-non-closing-paren \n
3898 > _ \n
3899 ";;" \n)
3900 > "*" sh-non-closing-paren \n
3901 > _ \n
3902 resume:
3903 "esac" > \n))
3904
3905 (define-skeleton sh-for
3906 "Insert a for loop. See `sh-feature'."
3907 (csh sh-modify sh
3908 1 ""
3909 2 "foreach "
3910 4 " ( "
3911 6 " )"
3912 15 '<
3913 16 "end")
3914 (es sh-modify rc
3915 4 " = ")
3916 (rc sh-modify sh
3917 2 "for( "
3918 6 " ) {"
3919 15 ?\} )
3920 (sh "Index variable: "
3921 > "for " str " in " _ "; do" \n
3922 > _ | ?$ & (sh-remember-variable str) \n
3923 "done" > \n))
3924
3925
3926
3927 (define-skeleton sh-indexed-loop
3928 "Insert an indexed loop from 1 to n. See `sh-feature'."
3929 (bash sh-modify posix)
3930 (csh "Index variable: "
3931 "@ " str " = 1" \n
3932 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3933 > _ ?$ str \n
3934 "@ " str "++" \n
3935 < "end" \n)
3936 (es sh-modify rc
3937 4 " =")
3938 (ksh88 "Index variable: "
3939 > "integer " str "=0" \n
3940 > "while (( ( " str " += 1 ) <= "
3941 (read-string "upper limit: ")
3942 " )); do" \n
3943 > _ ?$ (sh-remember-variable str) > \n
3944 "done" > \n)
3945 (posix "Index variable: "
3946 > str "=1" \n
3947 "while [ $" str " -le "
3948 (read-string "upper limit: ")
3949 " ]; do" \n
3950 > _ ?$ str \n
3951 str ?= (sh-add (sh-remember-variable str) 1) \n
3952 "done" > \n)
3953 (rc "Index variable: "
3954 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3955 (read-string "upper limit: ")
3956 "; i++ ) print i }'`}) {" \n
3957 > _ ?$ (sh-remember-variable str) \n
3958 ?\} > \n)
3959 (sh "Index variable: "
3960 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3961 (read-string "upper limit: ")
3962 "; i++ ) print i }'`; do" \n
3963 > _ ?$ (sh-remember-variable str) \n
3964 "done" > \n))
3965
3966
3967 (defun sh-shell-initialize-variables ()
3968 "Scan the buffer for variable assignments.
3969 Add these variables to `sh-shell-variables'."
3970 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3971 (save-excursion
3972 (goto-char (point-min))
3973 (setq sh-shell-variables-initialized t)
3974 (while (search-forward "=" nil t)
3975 (sh-assignment 0)))
3976 (message "Scanning buffer `%s' for variable assignments...done"
3977 (buffer-name)))
3978
3979 (defvar sh-add-buffer)
3980
3981 (defun sh-add-completer (string predicate code)
3982 "Do completion using `sh-shell-variables', but initialize it first.
3983 This function is designed for use as the \"completion table\",
3984 so it takes three arguments:
3985 STRING, the current buffer contents;
3986 PREDICATE, the predicate for filtering possible matches;
3987 CODE, which says what kind of things to do.
3988 CODE can be nil, t or `lambda'.
3989 nil means to return the best completion of STRING, or nil if there is none.
3990 t means to return a list of all possible completions of STRING.
3991 `lambda' means to return t if STRING is a valid completion as it stands."
3992 (let ((vars
3993 (with-current-buffer sh-add-buffer
3994 (or sh-shell-variables-initialized
3995 (sh-shell-initialize-variables))
3996 (nconc (mapcar (lambda (var)
3997 (substring var 0 (string-match "=" var)))
3998 process-environment)
3999 sh-shell-variables))))
4000 (complete-with-action code vars string predicate)))
4001
4002 (defun sh-add (var delta)
4003 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
4004 (interactive
4005 (let ((sh-add-buffer (current-buffer)))
4006 (list (completing-read "Variable: " 'sh-add-completer)
4007 (prefix-numeric-value current-prefix-arg))))
4008 (insert (sh-feature '((bash . "$(( ")
4009 (ksh88 . "$(( ")
4010 (posix . "$(( ")
4011 (rc . "`{expr $")
4012 (sh . "`expr $")
4013 (zsh . "$[ ")))
4014 (sh-remember-variable var)
4015 (if (< delta 0) " - " " + ")
4016 (number-to-string (abs delta))
4017 (sh-feature '((bash . " ))")
4018 (ksh88 . " ))")
4019 (posix . " ))")
4020 (rc . "}")
4021 (sh . "`")
4022 (zsh . " ]")))))
4023
4024
4025
4026 (define-skeleton sh-function
4027 "Insert a function definition. See `sh-feature'."
4028 (bash sh-modify ksh88
4029 3 "() {")
4030 (ksh88 "name: "
4031 "function " str " {" \n
4032 > _ \n
4033 < "}" \n)
4034 (rc sh-modify ksh88
4035 1 "fn ")
4036 (sh ()
4037 "() {" \n
4038 > _ \n
4039 < "}" \n))
4040
4041
4042
4043 (define-skeleton sh-if
4044 "Insert an if statement. See `sh-feature'."
4045 (csh "condition: "
4046 "if( " str " ) then" \n
4047 > _ \n
4048 ( "other condition, %s: "
4049 < "else if( " str " ) then" \n
4050 > _ \n)
4051 < "else" \n
4052 > _ \n
4053 resume:
4054 < "endif" \n)
4055 (es "condition: "
4056 > "if { " str " } {" \n
4057 > _ \n
4058 ( "other condition, %s: "
4059 "} { " str " } {" > \n
4060 > _ \n)
4061 "} {" > \n
4062 > _ \n
4063 resume:
4064 ?\} > \n)
4065 (rc "condition: "
4066 > "if( " str " ) {" \n
4067 > _ \n
4068 ( "other condition, %s: "
4069 "} else if( " str " ) {" > \n
4070 > _ \n)
4071 "} else {" > \n
4072 > _ \n
4073 resume:
4074 ?\} > \n)
4075 (sh "condition: "
4076 '(setq input (sh-feature sh-test))
4077 > "if " str "; then" \n
4078 > _ \n
4079 ( "other condition, %s: "
4080 > "elif " str "; then" > \n
4081 > \n)
4082 "else" > \n
4083 > \n
4084 resume:
4085 "fi" > \n))
4086
4087
4088
4089 (define-skeleton sh-repeat
4090 "Insert a repeat loop definition. See `sh-feature'."
4091 (es nil
4092 > "forever {" \n
4093 > _ \n
4094 ?\} > \n)
4095 (zsh "factor: "
4096 > "repeat " str "; do" > \n
4097 > \n
4098 "done" > \n))
4099
4100 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
4101
4102
4103
4104 (define-skeleton sh-select
4105 "Insert a select statement. See `sh-feature'."
4106 (ksh88 "Index variable: "
4107 > "select " str " in " _ "; do" \n
4108 > ?$ str \n
4109 "done" > \n)
4110 (bash sh-append ksh88))
4111 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
4112
4113
4114
4115 (define-skeleton sh-tmp-file
4116 "Insert code to setup temporary file handling. See `sh-feature'."
4117 (bash sh-append ksh88)
4118 (csh (file-name-nondirectory (buffer-file-name))
4119 "set tmp = `mktemp -t " str ".XXXXXX`" \n
4120 "onintr exit" \n _
4121 (and (goto-char (point-max))
4122 (not (bolp))
4123 ?\n)
4124 "exit:\n"
4125 "rm $tmp* >&/dev/null" > \n)
4126 (es (file-name-nondirectory (buffer-file-name))
4127 > "local( signals = $signals sighup sigint;" \n
4128 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
4129 > "catch @ e {" \n
4130 > "rm $tmp^* >[2]/dev/null" \n
4131 "throw $e" \n
4132 "} {" > \n
4133 _ \n
4134 ?\} > \n
4135 ?\} > \n)
4136 (ksh88 sh-modify sh
4137 7 "EXIT")
4138 (rc (file-name-nondirectory (buffer-file-name))
4139 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
4140 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
4141 (sh (file-name-nondirectory (buffer-file-name))
4142 > "TMP=`mktemp -t " str ".XXXXXX`" \n
4143 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
4144
4145
4146
4147 (define-skeleton sh-until
4148 "Insert an until loop. See `sh-feature'."
4149 (sh "condition: "
4150 '(setq input (sh-feature sh-test))
4151 > "until " str "; do" \n
4152 > _ \n
4153 "done" > \n))
4154 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
4155
4156
4157
4158 (define-skeleton sh-while
4159 "Insert a while loop. See `sh-feature'."
4160 (csh sh-modify sh
4161 2 ""
4162 3 "while( "
4163 5 " )"
4164 10 '<
4165 11 "end")
4166 (es sh-modify sh
4167 3 "while { "
4168 5 " } {"
4169 10 ?\} )
4170 (rc sh-modify sh
4171 3 "while( "
4172 5 " ) {"
4173 10 ?\} )
4174 (sh "condition: "
4175 '(setq input (sh-feature sh-test))
4176 > "while " str "; do" \n
4177 > _ \n
4178 "done" > \n))
4179
4180
4181
4182 (define-skeleton sh-while-getopts
4183 "Insert a while getopts loop. See `sh-feature'.
4184 Prompts for an options string which consists of letters for each recognized
4185 option followed by a colon `:' if the option accepts an argument."
4186 (bash sh-modify sh
4187 18 "${0##*/}")
4188 (csh nil
4189 "while( 1 )" \n
4190 > "switch( \"$1\" )" \n
4191 '(setq input '("- x" . 2))
4192 > >
4193 ( "option, %s: "
4194 < "case " '(eval str)
4195 '(if (string-match " +" str)
4196 (setq v1 (substring str (match-end 0))
4197 str (substring str 0 (match-beginning 0)))
4198 (setq v1 nil))
4199 str ?: \n
4200 > "set " v1 & " = $2" | -4 & _ \n
4201 (if v1 "shift") & \n
4202 "breaksw" \n)
4203 < "case --:" \n
4204 > "shift" \n
4205 < "default:" \n
4206 > "break" \n
4207 resume:
4208 < < "endsw" \n
4209 "shift" \n
4210 < "end" \n)
4211 (ksh88 sh-modify sh
4212 16 "print"
4213 18 "${0##*/}"
4214 37 "OPTIND-1")
4215 (posix sh-modify sh
4216 18 "$(basename $0)")
4217 (sh "optstring: "
4218 > "while getopts :" str " OPT; do" \n
4219 > "case $OPT in" \n
4220 '(setq v1 (append (vconcat str) nil))
4221 ( (prog1 (if v1 (char-to-string (car v1)))
4222 (if (eq (nth 1 v1) ?:)
4223 (setq v1 (nthcdr 2 v1)
4224 v2 "\"$OPTARG\"")
4225 (setq v1 (cdr v1)
4226 v2 nil)))
4227 > str "|+" str sh-non-closing-paren \n
4228 > _ v2 \n
4229 > ";;" \n)
4230 > "*" sh-non-closing-paren \n
4231 > "echo" " \"usage: " "`basename $0`"
4232 " [+-" '(setq v1 (point)) str
4233 '(save-excursion
4234 (while (search-backward ":" v1 t)
4235 (replace-match " ARG] [+-" t t)))
4236 (if (eq (preceding-char) ?-) -5)
4237 (if (and (sequencep v1) (length v1)) "] " "} ")
4238 "[--] ARGS...\"" \n
4239 "exit 2" > \n
4240 "esac" >
4241 \n "done"
4242 > \n
4243 "shift " (sh-add "OPTIND" -1) \n
4244 "OPTIND=1" \n))
4245
4246
4247
4248 (defun sh-assignment (arg)
4249 "Remember preceding identifier for future completion and do self-insert."
4250 (interactive "p")
4251 (self-insert-command arg)
4252 (if (<= arg 1)
4253 (sh-remember-variable
4254 (save-excursion
4255 (if (re-search-forward (sh-feature sh-assignment-regexp)
4256 (prog1 (point)
4257 (beginning-of-line 1))
4258 t)
4259 (match-string 1))))))
4260
4261
4262 (defun sh-maybe-here-document (arg)
4263 "Insert self. Without prefix, following unquoted `<' inserts here document.
4264 The document is bounded by `sh-here-document-word'."
4265 (declare (obsolete sh-electric-here-document-mode "24.3"))
4266 (interactive "*P")
4267 (self-insert-command (prefix-numeric-value arg))
4268 (or arg (sh--maybe-here-document)))
4269
4270 (defun sh--maybe-here-document ()
4271 (or (not (looking-back "[^<]<<"))
4272 (save-excursion
4273 (backward-char 2)
4274 (or (sh-quoted-p)
4275 (sh--inside-noncommand-expression (point))))
4276 (nth 8 (syntax-ppss))
4277 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
4278 (make-string (/ (current-indentation) tab-width) ?\t)
4279 ""))
4280 (delim (replace-regexp-in-string "['\"]" ""
4281 sh-here-document-word)))
4282 (insert sh-here-document-word)
4283 (or (eolp) (looking-at "[ \t]") (insert ?\s))
4284 (end-of-line 1)
4285 (while
4286 (sh-quoted-p)
4287 (end-of-line 2))
4288 (insert ?\n tabs)
4289 (save-excursion
4290 (insert ?\n tabs (replace-regexp-in-string
4291 "\\`-?[ \t]*" "" delim))))))
4292
4293 (define-minor-mode sh-electric-here-document-mode
4294 "Make << insert a here document skeleton."
4295 nil nil nil
4296 (if sh-electric-here-document-mode
4297 (add-hook 'post-self-insert-hook #'sh--maybe-here-document nil t)
4298 (remove-hook 'post-self-insert-hook #'sh--maybe-here-document t)))
4299 \f
4300 ;; various other commands
4301
4302 (defun sh-beginning-of-command ()
4303 ;; FIXME: Redefine using SMIE.
4304 "Move point to successive beginnings of commands."
4305 (interactive)
4306 (if (re-search-backward sh-beginning-of-command nil t)
4307 (goto-char (match-beginning 2))))
4308
4309 (defun sh-end-of-command ()
4310 ;; FIXME: Redefine using SMIE.
4311 "Move point to successive ends of commands."
4312 (interactive)
4313 (if (re-search-forward sh-end-of-command nil t)
4314 (goto-char (match-end 1))))
4315
4316 ;; Backslashification. Stolen from make-mode.el.
4317
4318 (defun sh-backslash-region (from to delete-flag)
4319 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4320 With no argument, inserts backslashes and aligns existing backslashes.
4321 With an argument, deletes the backslashes.
4322
4323 This function does not modify the last line of the region if the region ends
4324 right at the start of the following line; it does not modify blank lines
4325 at the start of the region. So you can put the region around an entire
4326 shell command and conveniently use this command."
4327 (interactive "r\nP")
4328 (save-excursion
4329 (goto-char from)
4330 (let ((column sh-backslash-column)
4331 (endmark (make-marker)))
4332 (move-marker endmark to)
4333 ;; Compute the smallest column number past the ends of all the lines.
4334 (if sh-backslash-align
4335 (progn
4336 (if (not delete-flag)
4337 (while (< (point) to)
4338 (end-of-line)
4339 (if (= (preceding-char) ?\\)
4340 (progn (forward-char -1)
4341 (skip-chars-backward " \t")))
4342 (setq column (max column (1+ (current-column))))
4343 (forward-line 1)))
4344 ;; Adjust upward to a tab column, if that doesn't push
4345 ;; past the margin.
4346 (if (> (% column tab-width) 0)
4347 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
4348 tab-width)))
4349 (if (< adjusted (window-width))
4350 (setq column adjusted))))))
4351 ;; Don't modify blank lines at start of region.
4352 (goto-char from)
4353 (while (and (< (point) endmark) (eolp))
4354 (forward-line 1))
4355 ;; Add or remove backslashes on all the lines.
4356 (while (and (< (point) endmark)
4357 ;; Don't backslashify the last line
4358 ;; if the region ends right at the start of the next line.
4359 (save-excursion
4360 (forward-line 1)
4361 (< (point) endmark)))
4362 (if (not delete-flag)
4363 (sh-append-backslash column)
4364 (sh-delete-backslash))
4365 (forward-line 1))
4366 (move-marker endmark nil))))
4367
4368 (defun sh-append-backslash (column)
4369 (end-of-line)
4370 ;; Note that "\\\\" is needed to get one backslash.
4371 (if (= (preceding-char) ?\\)
4372 (progn (forward-char -1)
4373 (delete-horizontal-space)
4374 (indent-to column (if sh-backslash-align nil 1)))
4375 (indent-to column (if sh-backslash-align nil 1))
4376 (insert "\\")))
4377
4378 (defun sh-delete-backslash ()
4379 (end-of-line)
4380 (or (bolp)
4381 (progn
4382 (forward-char -1)
4383 (if (looking-at "\\\\")
4384 (delete-region (1+ (point))
4385 (progn (skip-chars-backward " \t") (point)))))))
4386
4387 (provide 'sh-script)
4388
4389 ;;; sh-script.el ends here