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