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