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