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