Merge changes from emacs-23 branch
[bpt/emacs.git] / 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, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 ;; Free Software Foundation, Inc.
6
7 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
8 ;; Version: 2.0f
9 ;; Maintainer: FSF
10 ;; Keywords: languages, unix
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30 ;; as various derivatives are supported and easily derived from. Structured
31 ;; statements can be inserted with one command or abbrev. Completion is
32 ;; available for filenames, variables known from the script, the shell and
33 ;; the environment as well as commands.
34
35 ;;; Known Bugs:
36
37 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 ;; - Variables in `"' strings aren't fontified because there's no way of
39 ;; syntactically distinguishing those from `'' strings.
40
41 ;; Indentation
42 ;; ===========
43 ;; Indentation for rc and es modes is very limited, but for Bourne shells
44 ;; and its derivatives it is quite customizable.
45 ;;
46 ;; The following description applies to sh and derived shells (bash,
47 ;; zsh, ...).
48 ;;
49 ;; There are various customization variables which allow tailoring to
50 ;; a wide variety of styles. Most of these variables are named
51 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
52 ;; sh-indent-after-if controls the indenting of a line following
53 ;; an if statement, and sh-indent-for-fi controls the indentation
54 ;; of the line containing the fi.
55 ;;
56 ;; You can set each to a numeric value, but it is often more convenient
57 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
58 ;; By changing this one variable you can increase or decrease how much
59 ;; indentation there is. Valid symbols:
60 ;;
61 ;; + Indent right by sh-basic-offset
62 ;; - Indent left by sh-basic-offset
63 ;; ++ Indent right twice sh-basic-offset
64 ;; -- Indent left twice sh-basic-offset
65 ;; * Indent right half sh-basic-offset
66 ;; / Indent left half sh-basic-offset.
67 ;;
68 ;; There are 4 commands to help set the indentation variables:
69 ;;
70 ;; `sh-show-indent'
71 ;; This shows what variable controls the indentation of the current
72 ;; line and its value.
73 ;;
74 ;; `sh-set-indent'
75 ;; This allows you to set the value of the variable controlling the
76 ;; current line's indentation. You can enter a number or one of a
77 ;; number of special symbols to denote the value of sh-basic-offset,
78 ;; or its negative, or half it, or twice it, etc. If you've used
79 ;; cc-mode this should be familiar. If you forget which symbols are
80 ;; valid simply press C-h at the prompt.
81 ;;
82 ;; `sh-learn-line-indent'
83 ;; Simply make the line look the way you want it, then invoke this
84 ;; command. It will set the variable to the value that makes the line
85 ;; indent like that. If called with a prefix argument then it will set
86 ;; the value to one of the symbols if applicable.
87 ;;
88 ;; `sh-learn-buffer-indent'
89 ;; This is the deluxe function! It "learns" the whole buffer (use
90 ;; narrowing if you want it to process only part). It outputs to a
91 ;; buffer *indent* any conflicts it finds, and all the variables it has
92 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
93 ;; easily find where something was set. It is popped to automatically
94 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
95 ;; non-nil.
96 ;; `sh-indent-comment' will be set if all comments follow the same
97 ;; pattern; if they don't it will be set to nil.
98 ;; Whether `sh-basic-offset' is set is determined by variable
99 ;; `sh-learn-basic-offset'.
100 ;;
101 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
102 ;; (e.g. if there are large case statements). Perhaps it does not make
103 ;; sense to run it on large buffers: if lots of lines have different
104 ;; indentation styles it will produce a lot of diagnostics in the
105 ;; *indent* buffer; if there is a consistent style then running
106 ;; `sh-learn-buffer-indent' on a small region of the buffer should
107 ;; suffice.
108 ;;
109 ;; Saving indentation values
110 ;; -------------------------
111 ;; After you've learned the values in a buffer, how to you remember
112 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
113 ;; would make this unnecessary; simply learn the values when you visit
114 ;; the buffer.
115 ;; You can do this automatically like this:
116 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
117 ;;
118 ;; However... `sh-learn-buffer-indent' is extremely slow,
119 ;; especially on large-ish buffer. Also, if there are conflicts the
120 ;; "last one wins" which may not produce the desired setting.
121 ;;
122 ;; So...There is a minimal way of being able to save indentation values and
123 ;; to reload them in another buffer or at another point in time.
124 ;;
125 ;; Use `sh-name-style' to give a name to the indentation settings of
126 ;; the current buffer.
127 ;; Use `sh-load-style' to load indentation settings for the current
128 ;; buffer from a specific style.
129 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
130 ;; in lisp code. You can then store it in a file and later use
131 ;; `load-file' to load it.
132 ;;
133 ;; Indentation variables - buffer local or global?
134 ;; ----------------------------------------------
135 ;; I think that often having them buffer-local makes sense,
136 ;; especially if one is using `sh-learn-buffer-indent'. However, if
137 ;; a user sets values using customization, these changes won't appear
138 ;; to work if the variables are already local!
139 ;;
140 ;; To get round this, there is a variable `sh-make-vars-local' and 2
141 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
142 ;;
143 ;; If `sh-make-vars-local' is non-nil, then these variables become
144 ;; buffer local when the mode is established.
145 ;; If this is nil, then the variables are global. At any time you
146 ;; can make them local with the command `sh-make-vars-local'.
147 ;; Conversely, to update with the global values you can use the
148 ;; command `sh-reset-indent-vars-to-global-values'.
149 ;;
150 ;; This may be awkward, but the intent is to cover all cases.
151 ;;
152 ;; Awkward things, pitfalls
153 ;; ------------------------
154 ;; Indentation for a sh script is complicated for a number of reasons:
155 ;;
156 ;; 1. You can't format by simply looking at symbols, you need to look
157 ;; at keywords. [This is not the case for rc and es shells.]
158 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
159 ;; as a stand-alone symbol (in a case alternative). This makes
160 ;; things quite tricky!
161 ;; 3. Here-documents in a script should be treated "as is", and when
162 ;; they terminate we want to revert to the indentation of the line
163 ;; containing the "<<" symbol.
164 ;; 4. A line may be continued using the "\".
165 ;; 5. The character "#" (outside a string) normally starts a comment,
166 ;; but it doesn't in the sequence "$#"!
167 ;;
168 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
169 ;; uses, that of a text's syntax property. This, however, has 2
170 ;; disadvantages:
171 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
172 ;; case alternative, to find any here documents, and handle "$#".
173 ;;
174 ;; Bugs
175 ;; ----
176 ;; - Indenting many lines is slow. It currently does each line
177 ;; independently, rather than saving state information.
178 ;;
179 ;; - `sh-learn-buffer-indent' is extremely slow.
180 ;;
181 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
182 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
183 ;; coerce sh-script into doing the right thing.
184 ;;
185 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
186 ;; a case-pattern. You need to put the "in" between quotes to coerce
187 ;; sh-script into doing the right thing.
188 ;;
189 ;; - A line starting with "}>foo" is not indented like "} >foo".
190 ;;
191 ;; Richard Sharman <rsharman@pobox.com> June 1999.
192
193 ;;; Code:
194
195 ;; page 1: variables and settings
196 ;; page 2: indentation stuff
197 ;; page 3: mode-command and utility functions
198 ;; page 4: statement syntax-commands for various shells
199 ;; page 5: various other commands
200
201 (eval-when-compile
202 (require 'skeleton)
203 (require 'cl)
204 (require 'comint))
205 (require 'executable)
206
207 (defvar font-lock-comment-face)
208 (defvar font-lock-set-defaults)
209 (defvar font-lock-string-face)
210
211
212 (defgroup sh nil
213 "Shell programming utilities."
214 :group 'languages)
215
216 (defgroup sh-script nil
217 "Shell script mode."
218 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
219 :group 'sh
220 :prefix "sh-")
221
222
223 (defcustom sh-ancestor-alist
224 '((ash . sh)
225 (bash . jsh)
226 (bash2 . jsh)
227 (dtksh . ksh)
228 (es . rc)
229 (itcsh . tcsh)
230 (jcsh . csh)
231 (jsh . sh)
232 (ksh . ksh88)
233 (ksh88 . jsh)
234 (oash . sh)
235 (pdksh . ksh88)
236 (posix . sh)
237 (tcsh . csh)
238 (wksh . ksh88)
239 (wsh . sh)
240 (zsh . ksh88)
241 (rpm . sh))
242 "Alist showing the direct ancestor of various shells.
243 This is the basis for `sh-feature'. See also `sh-alias-alist'.
244 By default we have the following three hierarchies:
245
246 csh C Shell
247 jcsh C Shell with Job Control
248 tcsh TENEX C Shell
249 itcsh Ian's TENEX C Shell
250 rc Plan 9 Shell
251 es Extensible Shell
252 sh Bourne Shell
253 ash Almquist Shell
254 jsh Bourne Shell with Job Control
255 bash GNU Bourne Again Shell
256 ksh88 Korn Shell '88
257 ksh Korn Shell '93
258 dtksh CDE Desktop Korn Shell
259 pdksh Public Domain Korn Shell
260 wksh Window Korn Shell
261 zsh Z Shell
262 oash SCO OA (curses) Shell
263 posix IEEE 1003.2 Shell Standard
264 wsh ? Shell"
265 :type '(repeat (cons symbol symbol))
266 :group 'sh-script)
267
268
269 (defcustom sh-alias-alist
270 (append (if (eq system-type 'gnu/linux)
271 '((csh . tcsh)
272 (ksh . pdksh)))
273 ;; for the time being
274 '((ksh . ksh88)
275 (bash2 . bash)
276 (sh5 . sh)))
277 "Alist for transforming shell names to what they really are.
278 Use this where the name of the executable doesn't correspond to the type of
279 shell it really is."
280 :type '(repeat (cons symbol symbol))
281 :group 'sh-script)
282
283
284 (defcustom sh-shell-file
285 (or
286 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
287 ;; the executable extension, so comparisons with the list of
288 ;; known shells work.
289 (and (memq system-type '(ms-dos windows-nt))
290 (let* ((shell (getenv "SHELL"))
291 (shell-base
292 (and shell (file-name-nondirectory shell))))
293 ;; shell-script mode doesn't support DOS/Windows shells,
294 ;; so use the default instead.
295 (if (or (null shell)
296 (member (downcase shell-base)
297 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
298 "cmdproxy.exe")))
299 "/bin/sh"
300 (file-name-sans-extension (downcase shell)))))
301 (getenv "SHELL")
302 "/bin/sh")
303 "The executable file name for the shell being programmed."
304 :type 'string
305 :group 'sh-script)
306
307
308 (defcustom sh-shell-arg
309 ;; bash does not need any options when run in a shell script,
310 '((bash)
311 (csh . "-f")
312 (pdksh)
313 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
314 (ksh88)
315 ;; -p means don't initialize functions from the environment.
316 (rc . "-p")
317 ;; Someone proposed -motif, but we don't want to encourage
318 ;; use of a non-free widget set.
319 (wksh)
320 ;; -f means don't run .zshrc.
321 (zsh . "-f"))
322 "Single argument string for the magic number. See `sh-feature'."
323 :type '(repeat (cons (symbol :tag "Shell")
324 (choice (const :tag "No Arguments" nil)
325 (string :tag "Arguments")
326 (sexp :format "Evaluate: %v"))))
327 :group 'sh-script)
328
329 (defcustom sh-imenu-generic-expression
330 `((sh
331 . ((nil "^\\s-*\\(function\\s-+\\)?\\([[:alpha:]_][[:alnum:]_]+\\)\\s-*()" 2))))
332 "Alist of regular expressions for recognizing shell function definitions.
333 See `sh-feature' and `imenu-generic-expression'."
334 :type '(alist :key-type (symbol :tag "Shell")
335 :value-type (alist :key-type (choice :tag "Title"
336 string
337 (const :tag "None" nil))
338 :value-type
339 (repeat :tag "Regexp, index..." sexp)))
340 :group 'sh-script
341 :version "20.4")
342
343 (defvar sh-shell-variables nil
344 "Alist of shell variable names that should be included in completion.
345 These are used for completion in addition to all the variables named
346 in `process-environment'. Each element looks like (VAR . VAR), where
347 the car and cdr are the same symbol.")
348
349 (defvar sh-shell-variables-initialized nil
350 "Non-nil if `sh-shell-variables' is initialized.")
351
352 (defun sh-canonicalize-shell (shell)
353 "Convert a shell name SHELL to the one we should handle it as."
354 (if (string-match "\\.exe\\'" shell)
355 (setq shell (substring shell 0 (match-beginning 0))))
356 (or (symbolp shell)
357 (setq shell (intern shell)))
358 (or (cdr (assq shell sh-alias-alist))
359 shell))
360
361 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
362 "The shell being programmed. This is set by \\[sh-set-shell].")
363 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
364
365 (defvar sh-mode-abbrev-table nil)
366
367 (define-abbrev-table 'sh-mode-abbrev-table ())
368
369
370 ;; I turned off this feature because it doesn't permit typing commands
371 ;; in the usual way without help.
372 ;;(defvar sh-abbrevs
373 ;; '((csh sh-abbrevs shell
374 ;; "switch" 'sh-case
375 ;; "getopts" 'sh-while-getopts)
376
377 ;; (es sh-abbrevs shell
378 ;; "function" 'sh-function)
379
380 ;; (ksh88 sh-abbrevs sh
381 ;; "select" 'sh-select)
382
383 ;; (rc sh-abbrevs shell
384 ;; "case" 'sh-case
385 ;; "function" 'sh-function)
386
387 ;; (sh sh-abbrevs shell
388 ;; "case" 'sh-case
389 ;; "function" 'sh-function
390 ;; "until" 'sh-until
391 ;; "getopts" 'sh-while-getopts)
392
393 ;; ;; The next entry is only used for defining the others
394 ;; (shell "for" sh-for
395 ;; "loop" sh-indexed-loop
396 ;; "if" sh-if
397 ;; "tmpfile" sh-tmp-file
398 ;; "while" sh-while)
399
400 ;; (zsh sh-abbrevs ksh88
401 ;; "repeat" 'sh-repeat))
402 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
403 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
404 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
405
406
407
408 (defun sh-mode-syntax-table (table &rest list)
409 "Copy TABLE and set syntax for successive CHARs according to strings S."
410 (setq table (copy-syntax-table table))
411 (while list
412 (modify-syntax-entry (pop list) (pop list) table))
413 table)
414
415 (defvar sh-mode-syntax-table
416 (sh-mode-syntax-table ()
417 ?\# "<"
418 ?\n ">#"
419 ?\" "\"\""
420 ?\' "\"'"
421 ?\` "\"`"
422 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
423 ;; to work fine. This is needed so that dabbrev-expand
424 ;; $VARNAME works.
425 ?$ "'"
426 ?! "_"
427 ?% "_"
428 ?: "_"
429 ?. "_"
430 ?^ "_"
431 ?~ "_"
432 ?, "_"
433 ?= "."
434 ?< "."
435 ?> ".")
436 "The syntax table to use for Shell-Script mode.
437 This is buffer-local in every such buffer.")
438
439 (defvar sh-mode-syntax-table-input
440 '((sh . nil))
441 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
442
443 (defvar sh-mode-map
444 (let ((map (make-sparse-keymap))
445 (menu-map (make-sparse-keymap)))
446 (define-key map "\C-c(" 'sh-function)
447 (define-key map "\C-c\C-w" 'sh-while)
448 (define-key map "\C-c\C-u" 'sh-until)
449 (define-key map "\C-c\C-t" 'sh-tmp-file)
450 (define-key map "\C-c\C-s" 'sh-select)
451 (define-key map "\C-c\C-r" 'sh-repeat)
452 (define-key map "\C-c\C-o" 'sh-while-getopts)
453 (define-key map "\C-c\C-l" 'sh-indexed-loop)
454 (define-key map "\C-c\C-i" 'sh-if)
455 (define-key map "\C-c\C-f" 'sh-for)
456 (define-key map "\C-c\C-c" 'sh-case)
457 (define-key map "\C-c?" 'sh-show-indent)
458 (define-key map "\C-c=" 'sh-set-indent)
459 (define-key map "\C-c<" 'sh-learn-line-indent)
460 (define-key map "\C-c>" 'sh-learn-buffer-indent)
461 (define-key map "\C-c\C-\\" 'sh-backslash-region)
462
463 (define-key map "=" 'sh-assignment)
464 (define-key map "\C-c+" 'sh-add)
465 (define-key map "\C-\M-x" 'sh-execute-region)
466 (define-key map "\C-c\C-x" 'executable-interpret)
467 (define-key map "<" 'sh-maybe-here-document)
468 (define-key map "(" 'skeleton-pair-insert-maybe)
469 (define-key map "{" 'skeleton-pair-insert-maybe)
470 (define-key map "[" 'skeleton-pair-insert-maybe)
471 (define-key map "'" 'skeleton-pair-insert-maybe)
472 (define-key map "`" 'skeleton-pair-insert-maybe)
473 (define-key map "\"" 'skeleton-pair-insert-maybe)
474
475 (define-key map [remap complete-tag] 'comint-dynamic-complete)
476 (define-key map [remap delete-backward-char]
477 'backward-delete-char-untabify)
478 (define-key map "\C-c:" 'sh-set-shell)
479 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
480 (define-key map [remap forward-sentence] 'sh-end-of-command)
481 (define-key map [menu-bar sh-script] (cons "Sh-Script" menu-map))
482 (define-key menu-map [sh-learn-buffer-indent]
483 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
484 :help "Learn how to indent the buffer the way it currently is."))
485 (define-key menu-map [sh-learn-line-indent]
486 '(menu-item "Learn line indentation" sh-learn-line-indent
487 :help "Learn how to indent a line as it currently is indented"))
488 (define-key menu-map [sh-show-indent]
489 '(menu-item "Show indentation" sh-show-indent
490 :help "Show the how the current line would be indented"))
491 (define-key menu-map [sh-set-indent]
492 '(menu-item "Set indentation" sh-set-indent
493 :help "Set the indentation for the current line"))
494
495 (define-key menu-map [sh-pair]
496 '(menu-item "Insert braces and quotes in pairs"
497 (lambda ()
498 (interactive)
499 (require 'skeleton)
500 (setq skeleton-pair (not skeleton-pair)))
501 :button (:toggle . (and (boundp 'skeleton-pair)
502 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 (make-variable-buffer-local 'sh-header-marker)
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 colors 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 (define-obsolete-face-alias 'sh-heredoc-face 'sh-heredoc "22.1")
891 (defvar sh-heredoc-face 'sh-heredoc)
892
893 (defface sh-escaped-newline '((t :inherit font-lock-string-face))
894 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
895 :group 'sh-script
896 :version "22.1")
897
898 (defvar sh-font-lock-keywords-var
899 '((csh sh-append shell
900 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
901 font-lock-variable-name-face))
902
903 (es sh-append executable-font-lock-keywords
904 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
905 font-lock-variable-name-face))
906
907 (rc sh-append es)
908 (bash sh-append shell ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
909 (sh sh-append shell
910 ;; Variable names.
911 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
912 font-lock-variable-name-face)
913 ;; Function names.
914 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
915 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
916 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
917 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
918 1 font-lock-negation-char-face))
919
920 ;; The next entry is only used for defining the others
921 (shell
922 ;; Using font-lock-string-face here confuses sh-get-indent-info.
923 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
924 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
925 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
926 font-lock-variable-name-face))
927 (rpm sh-append rpm2
928 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
929 (rpm2 sh-append shell
930 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
931 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
932
933 (defvar sh-font-lock-keywords-var-1
934 '((sh "[ \t]in\\>"))
935 "Subdued level highlighting for Shell Script modes.")
936
937 (defvar sh-font-lock-keywords-var-2 ()
938 "Gaudy level highlighting for Shell Script modes.")
939
940 ;; These are used for the syntax table stuff (derived from cperl-mode).
941 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
942 (defconst sh-st-punc (string-to-syntax "."))
943 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
944
945 (defconst sh-escaped-line-re
946 ;; Should match until the real end-of-continued-line, but if that is not
947 ;; possible (because we bump into EOB or the search bound), then we should
948 ;; match until the search bound.
949 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
950
951 (defconst sh-here-doc-open-re
952 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\)+\\)"
953 sh-escaped-line-re "\\(\n\\)"))
954
955 (defvar sh-here-doc-markers nil)
956 (make-variable-buffer-local 'sh-here-doc-markers)
957 (defvar sh-here-doc-re sh-here-doc-open-re)
958 (make-variable-buffer-local 'sh-here-doc-re)
959
960 (defun sh-font-lock-close-heredoc (bol eof indented eol)
961 "Determine the syntax of the \\n after an EOF.
962 If non-nil INDENTED indicates that the EOF was indented."
963 (let* ((eof-re (if eof (regexp-quote eof) ""))
964 ;; A rough regexp that should find the opening <<EOF back.
965 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
966 ;; Use \s| to cheaply check it's an open-heredoc.
967 eof-re "['\"]?\\([ \t|;&)<>]"
968 sh-escaped-line-re
969 "\\)?\\s|"))
970 ;; A regexp that will find other EOFs.
971 (ere (concat "^" (if indented "[ \t]*") eof-re "\n"))
972 (start (save-excursion
973 (goto-char bol)
974 ;; FIXME: will incorrectly find a <<EOF embedded inside
975 ;; the heredoc.
976 (re-search-backward (concat sre "\\|" ere) nil t))))
977 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
978 ;; found a close-heredoc which makes the current close-heredoc inoperant.
979 (cond
980 ((when (and start (match-end 1)
981 (not (and indented (= (match-beginning 1) (match-end 1))))
982 (not (sh-in-comment-or-string (match-beginning 0))))
983 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
984 (save-excursion
985 (goto-char start)
986 (setq start (line-beginning-position 2))
987 (while
988 (progn
989 (re-search-forward "<<") ; Skip ourselves.
990 (and (re-search-forward sh-here-doc-open-re start 'move)
991 (goto-char (match-beginning 0))
992 (sh-in-comment-or-string (point)))))
993 ;; No <<EOF2 found after our <<.
994 (= (point) start)))
995 (put-text-property eol (1+ eol) 'syntax-table sh-here-doc-syntax))
996 ((not (or start (save-excursion (re-search-forward sre nil t))))
997 ;; There's no <<EOF either before or after us,
998 ;; so we should remove ourselves from font-lock's keywords.
999 (setq sh-here-doc-markers (delete eof sh-here-doc-markers))
1000 (setq sh-here-doc-re
1001 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
1002 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))
1003 nil))))
1004
1005 (defun sh-font-lock-open-heredoc (start string eol)
1006 "Determine the syntax of the \\n after a <<EOF.
1007 START is the position of <<.
1008 STRING is the actual word used as delimiter (e.g. \"EOF\").
1009 INDENTED is non-nil if the here document's content (and the EOF mark) can
1010 be indented (i.e. a <<- was used rather than just <<).
1011 Point is at the beginning of the next line."
1012 (unless (or (memq (char-before start) '(?< ?>))
1013 (sh-in-comment-or-string start))
1014 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
1015 ;; font-lock keywords to detect the end of this here document.
1016 (let ((str (replace-regexp-in-string "['\"]" "" string)))
1017 (unless (member str sh-here-doc-markers)
1018 (push str sh-here-doc-markers)
1019 (setq sh-here-doc-re
1020 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
1021 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))))
1022 (let ((ppss (save-excursion (syntax-ppss (1- (point))))))
1023 (if (nth 4 ppss)
1024 ;; The \n not only starts the heredoc but also closes a comment.
1025 ;; Let's close the comment just before the \n.
1026 (put-text-property (1- (point)) (point) 'syntax-table '(12))) ;">"
1027 (if (or (nth 5 ppss) (> (count-lines start (point)) 1))
1028 ;; If the sh-escaped-line-re part of sh-here-doc-re has matched
1029 ;; several lines, make sure we refontify them together.
1030 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
1031 ;; escaped), it means the right \n is actually further down.
1032 ;; Don't bother fixing it now, but place a multiline property so
1033 ;; that when jit-lock-context-* refontifies the rest of the
1034 ;; buffer, it also refontifies the current line with it.
1035 (put-text-property start (point) 'syntax-multiline t)))
1036 (put-text-property eol (1+ eol) 'syntax-table sh-here-doc-syntax)))
1037
1038 (defun sh-font-lock-quoted-subshell (limit)
1039 "Search for a subshell embedded in a string.
1040 Find all the unescaped \" characters within said subshell, remembering that
1041 subshells can nest."
1042 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
1043 ;; effort to handle multiline cases correctly, so it ends up being
1044 ;; rather flakey.
1045 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1046 ;; bingo we have a $( or a ` inside a ""
1047 (let ((char (char-after (point)))
1048 ;; `state' can be: double-quote, backquote, code.
1049 (state (if (eq (char-before) ?`) 'backquote 'code))
1050 ;; Stacked states in the context.
1051 (states '(double-quote)))
1052 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1053 (< (point) limit)))
1054 ;; unescape " inside a $( ... ) construct.
1055 (case (char-after)
1056 (?\' (case state
1057 (double-quote nil)
1058 (t (forward-char 1) (skip-chars-forward "^'" limit))))
1059 (?\\ (forward-char 1))
1060 (?\" (case state
1061 (double-quote (setq state (pop states)))
1062 (t (push state states) (setq state 'double-quote)))
1063 (if state (put-text-property (point) (1+ (point))
1064 'syntax-table '(1))))
1065 (?\` (case state
1066 (backquote (setq state (pop states)))
1067 (t (push state states) (setq state 'backquote))))
1068 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1069 nil
1070 (forward-char 1)
1071 (case state
1072 (t (push state states) (setq state 'code)))))
1073 (?\( (case state
1074 (double-quote nil)
1075 (t (push state states) (setq state 'code))))
1076 (?\) (case state
1077 (double-quote nil)
1078 (t (setq state (pop states)))))
1079 (t (error "Internal error in sh-font-lock-quoted-subshell")))
1080 (forward-char 1)))))
1081
1082
1083 (defun sh-is-quoted-p (pos)
1084 (and (eq (char-before pos) ?\\)
1085 (not (sh-is-quoted-p (1- pos)))))
1086
1087 (defun sh-font-lock-paren (start)
1088 (save-excursion
1089 (goto-char start)
1090 ;; Skip through all patterns
1091 (while
1092 (progn
1093 (forward-comment (- (point-max)))
1094 ;; Skip through one pattern
1095 (while
1096 (or (/= 0 (skip-syntax-backward "w_"))
1097 (/= 0 (skip-chars-backward "?[]*@/\\"))
1098 (and (sh-is-quoted-p (1- (point)))
1099 (goto-char (- (point) 2)))
1100 (when (memq (char-before) '(?\" ?\'))
1101 (condition-case nil (progn (backward-sexp 1) t)
1102 (error nil)))))
1103 ;; Patterns can be preceded by an open-paren (Bug#1320).
1104 (if (eq (char-before (point)) ?\()
1105 (backward-char 1))
1106 (while (progn
1107 (forward-comment (- (point-max)))
1108 ;; Maybe we've bumped into an escaped newline.
1109 (sh-is-quoted-p (point)))
1110 (backward-char 1))
1111 (when (eq (char-before) ?|)
1112 (backward-char 1) t)))
1113 ;; FIXME: ";; esac )" is a case that looks like a case-pattern but it's
1114 ;; really just a close paren after a case statement. I.e. if we skipped
1115 ;; over `esac' just now, we're not looking at a case-pattern.
1116 (when (progn (backward-char 2)
1117 (if (> start (line-end-position))
1118 (put-text-property (point) (1+ start)
1119 'syntax-multiline t))
1120 ;; FIXME: The `in' may just be a random argument to
1121 ;; a normal command rather than the real `in' keyword.
1122 ;; I.e. we should look back to try and find the
1123 ;; corresponding `case'.
1124 (looking-at ";;\\|in"))
1125 sh-st-punc)))
1126
1127 (defun sh-font-lock-backslash-quote ()
1128 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1129 ;; In a '...' the backslash is not escaping.
1130 sh-st-punc
1131 nil))
1132
1133 (defun sh-syntax-propertize-function (start end)
1134 (goto-char start)
1135 (while (prog1
1136 (re-search-forward sh-here-doc-re end 'move)
1137 (save-excursion
1138 (save-match-data
1139 (funcall
1140 (syntax-propertize-rules
1141 ;; A `#' begins a comment when it is unquoted and at the
1142 ;; beginning of a word. In the shell, words are separated by
1143 ;; metacharacters. The list of special chars is taken from
1144 ;; the single-unix spec of the shell command language (under
1145 ;; `quoting') but with `$' removed.
1146 ("[^|&;<>()`\\\"' \t\n]\\(#+\\)" (1 "_"))
1147 ;; In a '...' the backslash is not escaping.
1148 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1149 ;; Make sure $@ and $? are correctly recognized as sexps.
1150 ("\\$\\([?@]\\)" (1 "_"))
1151 ;; Distinguish the special close-paren in `case'.
1152 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1153 ;; Highlight (possibly nested) subshells inside "" quoted
1154 ;; regions correctly.
1155 ("\"\\(?:\\(?:.\\|\n\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)"
1156 (1 (ignore
1157 ;; Save excursion because we want to also apply other
1158 ;; syntax-propertize rules within the affected region.
1159 (save-excursion
1160 (sh-font-lock-quoted-subshell end))))))
1161 (prog1 start (setq start (point))) (point)))))
1162 (if (match-beginning 2)
1163 ;; FIXME: actually, once we see an heredoc opener, we should just
1164 ;; search for its ender without propertizing anything in it.
1165 (sh-font-lock-open-heredoc
1166 (match-beginning 0) (match-string 1) (match-beginning 2))
1167 (sh-font-lock-close-heredoc
1168 (match-beginning 0) (match-string 4)
1169 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3)))
1170 (match-beginning 5)))))
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 non-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 (define-derived-mode sh-mode prog-mode "Shell-script"
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 \\[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 (make-local-variable 'sh-shell-file)
1532 (make-local-variable 'sh-shell)
1533
1534 (set (make-local-variable 'skeleton-pair-default-alist)
1535 sh-skeleton-pair-default-alist)
1536 (set (make-local-variable 'skeleton-end-hook)
1537 (lambda () (or (eolp) (newline) (indent-relative))))
1538
1539 (set (make-local-variable 'paragraph-start) (concat page-delimiter "\\|$"))
1540 (set (make-local-variable 'paragraph-separate) paragraph-start)
1541 (set (make-local-variable 'comment-start) "# ")
1542 (set (make-local-variable 'comment-start-skip) "#+[\t ]*")
1543 (set (make-local-variable 'local-abbrev-table) sh-mode-abbrev-table)
1544 (set (make-local-variable 'comint-dynamic-complete-functions)
1545 sh-dynamic-complete-functions)
1546 ;; we can't look if previous line ended with `\'
1547 (set (make-local-variable 'comint-prompt-regexp) "^[ \t]*")
1548 (set (make-local-variable 'imenu-case-fold-search) nil)
1549 (set (make-local-variable 'font-lock-defaults)
1550 `((sh-font-lock-keywords
1551 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1552 nil nil
1553 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1554 (font-lock-syntactic-face-function
1555 . sh-font-lock-syntactic-face-function)))
1556 (set (make-local-variable 'syntax-propertize-function)
1557 #'sh-syntax-propertize-function)
1558 (add-hook 'syntax-propertize-extend-region-functions
1559 #'syntax-propertize-multiline 'append 'local)
1560 (set (make-local-variable 'skeleton-pair-alist) '((?` _ ?`)))
1561 (set (make-local-variable 'skeleton-pair-filter-function) 'sh-quoted-p)
1562 (set (make-local-variable 'skeleton-further-elements)
1563 '((< '(- (min sh-indentation (current-column))))))
1564 (set (make-local-variable 'skeleton-filter-function) 'sh-feature)
1565 (set (make-local-variable 'skeleton-newline-indent-rigidly) t)
1566 (set (make-local-variable 'sh-indent-supported-here) nil)
1567 (set (make-local-variable 'defun-prompt-regexp)
1568 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1569 ;; Parse or insert magic number for exec, and set all variables depending
1570 ;; on the shell thus determined.
1571 (sh-set-shell
1572 (cond ((save-excursion
1573 (goto-char (point-min))
1574 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1575 (match-string 2))
1576 ((not buffer-file-name)
1577 sh-shell-file)
1578 ;; Checks that use `buffer-file-name' follow.
1579 ((string-match "\\.m?spec\\'" buffer-file-name)
1580 "rpm")
1581 ((string-match "[.]sh\\>" buffer-file-name)
1582 "sh")
1583 ((string-match "[.]bash\\>" buffer-file-name)
1584 "bash")
1585 ((string-match "[.]ksh\\>" buffer-file-name)
1586 "ksh")
1587 ((string-match "[.]csh\\>" buffer-file-name)
1588 "csh")
1589 ((equal (file-name-nondirectory buffer-file-name) ".profile")
1590 "sh")
1591 (t
1592 sh-shell-file))
1593 nil nil))
1594
1595 ;;;###autoload
1596 (defalias 'shell-script-mode 'sh-mode)
1597
1598
1599 (defun sh-font-lock-keywords (&optional keywords)
1600 "Function to get simple fontification based on `sh-font-lock-keywords'.
1601 This adds rules for comments and assignments."
1602 (sh-feature sh-font-lock-keywords-var
1603 (when (stringp (sh-feature sh-assignment-regexp))
1604 (lambda (list)
1605 `((,(sh-feature sh-assignment-regexp)
1606 1 font-lock-variable-name-face)
1607 ,@keywords
1608 ,@list
1609 ,@executable-font-lock-keywords)))))
1610
1611 (defun sh-font-lock-keywords-1 (&optional builtins)
1612 "Function to get better fontification including keywords."
1613 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1614 (regexp-opt (sh-feature sh-leading-keywords) t)
1615 "[ \t]+\\)?"
1616 (regexp-opt (append (sh-feature sh-leading-keywords)
1617 (sh-feature sh-other-keywords))
1618 t))))
1619 (sh-font-lock-keywords
1620 `(,@(if builtins
1621 `((,(concat keywords "[ \t]+\\)?"
1622 (regexp-opt (sh-feature sh-builtins) t)
1623 "\\>")
1624 (2 font-lock-keyword-face nil t)
1625 (6 font-lock-builtin-face))
1626 ,@(sh-feature sh-font-lock-keywords-var-2)))
1627 (,(concat keywords "\\)\\>")
1628 2 font-lock-keyword-face)
1629 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1630
1631 (defun sh-font-lock-keywords-2 ()
1632 "Function to get better fontification including keywords and builtins."
1633 (sh-font-lock-keywords-1 t))
1634
1635
1636 (defvar sh-regexp-for-done nil
1637 "A buffer-local regexp to match opening keyword for done.")
1638
1639 (defvar sh-kw-alist nil
1640 "A buffer-local, since it is shell-type dependent, list of keywords.")
1641
1642 ;; ( key-word first-on-this on-prev-line )
1643 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1644 ;; having 3 elements:
1645 ;; a keyword
1646 ;; a rule to check when the keyword appears on "this" line
1647 ;; a rule to check when the keyword appears on "the previous" line
1648 ;; The keyword is usually a string and is the first word on a line.
1649 ;; If this keyword appears on the line whose indentation is to be
1650 ;; calculated, the rule in element 2 is called. If this returns
1651 ;; non-zero, the resulting point (which may be changed by the rule)
1652 ;; is used as the default indentation.
1653 ;; If it returned false or the keyword was not found in the table,
1654 ;; then the keyword from the previous line is looked up and the rule
1655 ;; in element 3 is called. In this case, however,
1656 ;; `sh-get-indent-info' does not stop but may keep going and test
1657 ;; other keywords against rules in element 3. This is because the
1658 ;; preceding line could have, for example, an opening "if" and an
1659 ;; opening "while" keyword and we need to add the indentation offsets
1660 ;; for both.
1661 ;;
1662 (defconst sh-kw
1663 '((sh
1664 ("if" nil sh-handle-prev-if)
1665 ("elif" sh-handle-this-else sh-handle-prev-else)
1666 ("else" sh-handle-this-else sh-handle-prev-else)
1667 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1668 ("then" sh-handle-this-then sh-handle-prev-then)
1669 ("(" nil sh-handle-prev-open)
1670 ("{" nil sh-handle-prev-open)
1671 ("[" nil sh-handle-prev-open)
1672 ("}" sh-handle-this-close nil)
1673 (")" sh-handle-this-close nil)
1674 ("]" sh-handle-this-close nil)
1675 ("case" nil sh-handle-prev-case)
1676 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1677 (case-label nil sh-handle-after-case-label) ;; ???
1678 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1679 ("done" sh-handle-this-done sh-handle-prev-done)
1680 ("do" sh-handle-this-do sh-handle-prev-do))
1681
1682 ;; Note: we don't need specific stuff for bash and zsh shells;
1683 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1684 ;; these shells use.
1685 (rc
1686 ("{" nil sh-handle-prev-open)
1687 ("}" sh-handle-this-close nil)
1688 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1689
1690
1691
1692 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1693 "Set this buffer's shell to SHELL (a string).
1694 When used interactively, insert the proper starting #!-line,
1695 and make the visited file executable via `executable-set-magic',
1696 perhaps querying depending on the value of `executable-query'.
1697
1698 When this function is called noninteractively, INSERT-FLAG (the third
1699 argument) controls whether to insert a #!-line and think about making
1700 the visited file executable, and NO-QUERY-FLAG (the second argument)
1701 controls whether to query about making the visited file executable.
1702
1703 Calls the value of `sh-set-shell-hook' if set."
1704 (interactive (list (completing-read (format "Shell \(default %s\): "
1705 sh-shell-file)
1706 interpreter-mode-alist
1707 (lambda (x) (eq (cdr x) 'sh-mode))
1708 nil nil nil sh-shell-file)
1709 (eq executable-query 'function)
1710 t))
1711 (if (string-match "\\.exe\\'" shell)
1712 (setq shell (substring shell 0 (match-beginning 0))))
1713 (setq sh-shell (intern (file-name-nondirectory shell))
1714 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1715 sh-shell))
1716 (if insert-flag
1717 (setq sh-shell-file
1718 (executable-set-magic shell (sh-feature sh-shell-arg)
1719 no-query-flag insert-flag)))
1720 (let ((tem (sh-feature sh-require-final-newline)))
1721 (if (eq tem t)
1722 (set (make-local-variable 'require-final-newline)
1723 mode-require-final-newline)))
1724 (setq mode-line-process (format "[%s]" sh-shell))
1725 (set (make-local-variable 'sh-shell-variables) nil)
1726 (set (make-local-variable 'sh-shell-variables-initialized) nil)
1727 (set (make-local-variable 'imenu-generic-expression)
1728 (sh-feature sh-imenu-generic-expression))
1729 (let ((tem (sh-feature sh-mode-syntax-table-input)))
1730 (when tem
1731 (set (make-local-variable 'sh-mode-syntax-table)
1732 (apply 'sh-mode-syntax-table tem))
1733 (set-syntax-table sh-mode-syntax-table)))
1734 (dolist (var (sh-feature sh-variables))
1735 (sh-remember-variable var))
1736 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1737 (progn
1738 (message "Setting up indent for shell type %s" sh-shell)
1739 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1740 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1741 (let ((regexp (sh-feature sh-kws-for-done)))
1742 (if regexp
1743 (set (make-local-variable 'sh-regexp-for-done)
1744 (sh-mkword-regexpr (regexp-opt regexp t)))))
1745 (message "setting up indent stuff")
1746 ;; sh-mode has already made indent-line-function local
1747 ;; but do it in case this is called before that.
1748 (set (make-local-variable 'indent-line-function) 'sh-indent-line)
1749 (if sh-make-vars-local
1750 (sh-make-vars-local))
1751 (message "Indentation setup for shell type %s" sh-shell))
1752 (message "No indentation for this shell type.")
1753 (setq indent-line-function 'sh-basic-indent-line))
1754 (when font-lock-mode
1755 (setq font-lock-set-defaults nil)
1756 (font-lock-set-defaults)
1757 (font-lock-fontify-buffer))
1758 (run-hooks 'sh-set-shell-hook))
1759
1760
1761 (defun sh-feature (alist &optional function)
1762 "Index ALIST by the current shell.
1763 If ALIST isn't a list where every element is a cons, it is returned as is.
1764 Else indexing follows an inheritance logic which works in two ways:
1765
1766 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1767 the alist contains no value for the current shell.
1768 The ultimate default is always `sh'.
1769
1770 - If the value thus looked up is a list starting with `sh-append',
1771 we call the function `sh-append' with the rest of the list as
1772 arguments, and use the value. However, the next element of the
1773 list is not used as-is; instead, we look it up recursively
1774 in ALIST to allow the function called to define the value for
1775 one shell to be derived from another shell.
1776 The value thus determined is physically replaced into the alist.
1777
1778 If FUNCTION is non-nil, it is called with one argument,
1779 the value thus obtained, and the result is used instead."
1780 (or (if (consp alist)
1781 ;; Check for something that isn't a valid alist.
1782 (let ((l alist))
1783 (while (and l (consp (car l)))
1784 (setq l (cdr l)))
1785 (if l alist)))
1786
1787 (let ((orig-sh-shell sh-shell))
1788 (let ((sh-shell sh-shell)
1789 elt val)
1790 (while (and sh-shell
1791 (not (setq elt (assq sh-shell alist))))
1792 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1793 ;; If the shell is not known, treat it as sh.
1794 (unless elt
1795 (setq elt (assq 'sh alist)))
1796 (setq val (cdr elt))
1797 (if (and (consp val)
1798 (memq (car val) '(sh-append sh-modify)))
1799 (setq val
1800 (apply (car val)
1801 ;; Refer to the value for a different shell,
1802 ;; as a kind of inheritance.
1803 (let ((sh-shell (car (cdr val))))
1804 (sh-feature alist))
1805 (cddr val))))
1806 (if function
1807 (setq sh-shell orig-sh-shell
1808 val (funcall function val)))
1809 val))))
1810
1811
1812
1813 ;; I commented this out because nobody calls it -- rms.
1814 ;;(defun sh-abbrevs (ancestor &rest list)
1815 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1816 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1817 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1818 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1819 ;;EXPANSION may be either a string or a skeleton command."
1820 ;; (or (if (boundp sh-shell)
1821 ;; (symbol-value sh-shell))
1822 ;; (progn
1823 ;; (if (listp ancestor)
1824 ;; (nconc list ancestor))
1825 ;; (define-abbrev-table sh-shell ())
1826 ;; (if (vectorp ancestor)
1827 ;; (mapatoms (lambda (atom)
1828 ;; (or (eq atom 0)
1829 ;; (define-abbrev (symbol-value sh-shell)
1830 ;; (symbol-name atom)
1831 ;; (symbol-value atom)
1832 ;; (symbol-function atom))))
1833 ;; ancestor))
1834 ;; (while list
1835 ;; (define-abbrev (symbol-value sh-shell)
1836 ;; (car list)
1837 ;; (if (stringp (car (cdr list)))
1838 ;; (car (cdr list))
1839 ;; "")
1840 ;; (if (symbolp (car (cdr list)))
1841 ;; (car (cdr list))))
1842 ;; (setq list (cdr (cdr list)))))
1843 ;; (symbol-value sh-shell)))
1844
1845
1846 (defun sh-append (ancestor &rest list)
1847 "Return list composed of first argument (a list) physically appended to rest."
1848 (nconc list ancestor))
1849
1850
1851 (defun sh-modify (skeleton &rest list)
1852 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1853 (setq skeleton (copy-sequence skeleton))
1854 (while list
1855 (setcar (or (nthcdr (car list) skeleton)
1856 (error "Index %d out of bounds" (car list)))
1857 (car (cdr list)))
1858 (setq list (nthcdr 2 list)))
1859 skeleton)
1860
1861
1862 (defun sh-basic-indent-line ()
1863 "Indent a line for Sh mode (shell script mode).
1864 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1865 Lines containing only comments are considered empty."
1866 (interactive)
1867 (let ((previous (save-excursion
1868 (while (and (progn (beginning-of-line)
1869 (not (bobp)))
1870 (progn
1871 (forward-line -1)
1872 (back-to-indentation)
1873 (or (eolp)
1874 (eq (following-char) ?#)))))
1875 (current-column)))
1876 current)
1877 (save-excursion
1878 (indent-to (if (eq this-command 'newline-and-indent)
1879 previous
1880 (if (< (current-column)
1881 (setq current (progn (back-to-indentation)
1882 (current-column))))
1883 (if (eolp) previous 0)
1884 (delete-region (point)
1885 (progn (beginning-of-line) (point)))
1886 (if (eolp)
1887 (max previous (* (1+ (/ current sh-indentation))
1888 sh-indentation))
1889 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1890 (if (< (current-column) (current-indentation))
1891 (skip-chars-forward " \t"))))
1892
1893
1894 (defun sh-execute-region (start end &optional flag)
1895 "Pass optional header and region to a subshell for noninteractive execution.
1896 The working directory is that of the buffer, and only environment variables
1897 are already set which is why you can mark a header within the script.
1898
1899 With a positive prefix ARG, instead of sending region, define header from
1900 beginning of buffer to point. With a negative prefix ARG, instead of sending
1901 region, clear header."
1902 (interactive "r\nP")
1903 (if flag
1904 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1905 (point-marker)))
1906 (if sh-header-marker
1907 (save-excursion
1908 (let (buffer-undo-list)
1909 (goto-char sh-header-marker)
1910 (append-to-buffer (current-buffer) start end)
1911 (shell-command-on-region (point-min)
1912 (setq end (+ sh-header-marker
1913 (- end start)))
1914 sh-shell-file)
1915 (delete-region sh-header-marker end)))
1916 (shell-command-on-region start end (concat sh-shell-file " -")))))
1917
1918
1919 (defun sh-remember-variable (var)
1920 "Make VARIABLE available for future completing reads in this buffer."
1921 (or (< (length var) sh-remember-variable-min)
1922 (getenv var)
1923 (assoc var sh-shell-variables)
1924 (push (cons var var) sh-shell-variables))
1925 var)
1926
1927
1928
1929 (defun sh-quoted-p ()
1930 "Is point preceded by an odd number of backslashes?"
1931 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1932 \f
1933 ;; Indentation stuff.
1934 (defun sh-must-support-indent ()
1935 "*Signal an error if the shell type for this buffer is not supported.
1936 Also, the buffer must be in Shell-script mode."
1937 (unless sh-indent-supported-here
1938 (error "This buffer's shell does not support indentation through Emacs")))
1939
1940 (defun sh-make-vars-local ()
1941 "Make the indentation variables local to this buffer.
1942 Normally they already are local. This command is provided in case
1943 variable `sh-make-vars-local' has been set to nil.
1944
1945 To revert all these variables to the global values, use
1946 command `sh-reset-indent-vars-to-global-values'."
1947 (interactive)
1948 (mapc 'make-local-variable sh-var-list)
1949 (message "Indentation variables are now local."))
1950
1951 (defun sh-reset-indent-vars-to-global-values ()
1952 "Reset local indentation variables to the global values.
1953 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1954 (interactive)
1955 (mapc 'kill-local-variable sh-var-list)
1956 (if sh-make-vars-local
1957 (mapcar 'make-local-variable sh-var-list)))
1958
1959
1960 ;; Theoretically these are only needed in shell and derived modes.
1961 ;; However, the routines which use them are only called in those modes.
1962 (defconst sh-special-keywords "then\\|do")
1963
1964 (defun sh-help-string-for-variable (var)
1965 "Construct a string for `sh-read-variable' when changing variable VAR ."
1966 (let ((msg (documentation-property var 'variable-documentation))
1967 (msg2 ""))
1968 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
1969 (setq msg2
1970 (format "\n
1971 You can enter a number (positive to increase indentation,
1972 negative to decrease indentation, zero for no change to indentation).
1973
1974 Or, you can enter one of the following symbols which are relative to
1975 the value of variable `sh-basic-offset'
1976 which in this buffer is currently %s.
1977
1978 \t%s."
1979 sh-basic-offset
1980 (mapconcat (lambda (x)
1981 (nth (1- (length x)) x))
1982 sh-symbol-list "\n\t"))))
1983 (concat
1984 ;; The following shows the global not the local value!
1985 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1986 msg msg2)))
1987
1988 (defun sh-read-variable (var)
1989 "Read a new value for indentation variable VAR."
1990 (interactive "*variable? ") ;; to test
1991 (let ((minibuffer-help-form `(sh-help-string-for-variable
1992 (quote ,var)))
1993 val)
1994 (setq val (read-from-minibuffer
1995 (format "New value for %s (press %s for help): "
1996 var (single-key-description help-char))
1997 (format "%s" (symbol-value var))
1998 nil t))
1999 val))
2000
2001
2002
2003 (defun sh-in-comment-or-string (start)
2004 "Return non-nil if START is in a comment or string."
2005 (save-excursion
2006 (let ((state (syntax-ppss start)))
2007 (or (nth 3 state) (nth 4 state)))))
2008
2009 (defun sh-goto-matching-if ()
2010 "Go to the matching if for a fi.
2011 This handles nested if..fi pairs."
2012 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2013 (if found
2014 (goto-char found))))
2015
2016
2017 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2018 ;; line whose indentation is being handled contain XXX;
2019 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2020
2021 (defun sh-handle-prev-if ()
2022 (list '(+ sh-indent-after-if)))
2023
2024 (defun sh-handle-this-else ()
2025 (if (sh-goto-matching-if)
2026 ;; (list "aligned to if")
2027 (list "aligned to if" '(+ sh-indent-for-else))
2028 nil
2029 ))
2030
2031 (defun sh-handle-prev-else ()
2032 (if (sh-goto-matching-if)
2033 (list '(+ sh-indent-after-if))
2034 ))
2035
2036 (defun sh-handle-this-fi ()
2037 (if (sh-goto-matching-if)
2038 (list "aligned to if" '(+ sh-indent-for-fi))
2039 nil
2040 ))
2041
2042 (defun sh-handle-prev-fi ()
2043 ;; Why do we have this rule? Because we must go back to the if
2044 ;; to get its indent. We may continue back from there.
2045 ;; We return nil because we don't have anything to add to result,
2046 ;; the side affect of setting align-point is all that matters.
2047 ;; we could return a comment (a string) but I can't think of a good one...
2048 (sh-goto-matching-if)
2049 nil)
2050
2051 (defun sh-handle-this-then ()
2052 (let ((p (sh-goto-matching-if)))
2053 (if p
2054 (list '(+ sh-indent-for-then))
2055 )))
2056
2057 (defun sh-handle-prev-then ()
2058 (let ((p (sh-goto-matching-if)))
2059 (if p
2060 (list '(+ sh-indent-after-if))
2061 )))
2062
2063 (defun sh-handle-prev-open ()
2064 (save-excursion
2065 (let ((x (sh-prev-stmt)))
2066 (if (and x
2067 (progn
2068 (goto-char x)
2069 (or
2070 (looking-at "function\\b")
2071 (looking-at "\\s-*\\S-+\\s-*()")
2072 )))
2073 (list '(+ sh-indent-after-function))
2074 (list '(+ sh-indent-after-open)))
2075 )))
2076
2077 (defun sh-handle-this-close ()
2078 (forward-char 1) ;; move over ")"
2079 (if (sh-safe-forward-sexp -1)
2080 (list "aligned to opening paren")))
2081
2082 (defun sh-goto-matching-case ()
2083 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2084 (if found (goto-char found))))
2085
2086 (defun sh-handle-prev-case ()
2087 ;; This is typically called when point is on same line as a case
2088 ;; we shouldn't -- and can't find prev-case
2089 (if (looking-at ".*\\<case\\>")
2090 (list '(+ sh-indent-for-case-label))
2091 (error "We don't seem to be on a line with a case"))) ;; debug
2092
2093 (defun sh-handle-this-esac ()
2094 (if (sh-goto-matching-case)
2095 (list "aligned to matching case")))
2096
2097 (defun sh-handle-prev-esac ()
2098 (if (sh-goto-matching-case)
2099 (list "matching case")))
2100
2101 (defun sh-handle-after-case-label ()
2102 (if (sh-goto-matching-case)
2103 (list '(+ sh-indent-for-case-alt))))
2104
2105 (defun sh-handle-prev-case-alt-end ()
2106 (if (sh-goto-matching-case)
2107 (list '(+ sh-indent-for-case-label))))
2108
2109 (defun sh-safe-forward-sexp (&optional arg)
2110 "Try and do a `forward-sexp', but do not error.
2111 Return new point if successful, nil if an error occurred."
2112 (condition-case nil
2113 (progn
2114 (forward-sexp (or arg 1))
2115 (point)) ;; return point if successful
2116 (error
2117 (sh-debug "oops!(1) %d" (point))
2118 nil))) ;; return nil if fail
2119
2120 (defun sh-goto-match-for-done ()
2121 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2122 (if found
2123 (goto-char found))))
2124
2125 (defun sh-handle-this-done ()
2126 (if (sh-goto-match-for-done)
2127 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2128
2129 (defun sh-handle-prev-done ()
2130 (if (sh-goto-match-for-done)
2131 (list "previous done")))
2132
2133 (defun sh-handle-this-do ()
2134 (if (sh-goto-match-for-done)
2135 (list '(+ sh-indent-for-do))))
2136
2137 (defun sh-handle-prev-do ()
2138 (cond
2139 ((save-restriction
2140 (narrow-to-region (point) (line-beginning-position))
2141 (sh-goto-match-for-done))
2142 (sh-debug "match for done found on THIS line")
2143 (list '(+ sh-indent-after-loop-construct)))
2144 ((sh-goto-match-for-done)
2145 (sh-debug "match for done found on PREV line")
2146 (list '(+ sh-indent-after-do)))
2147 (t
2148 (message "match for done NOT found")
2149 nil)))
2150
2151 ;; for rc:
2152 (defun sh-find-prev-switch ()
2153 "Find the line for the switch keyword matching this line's case keyword."
2154 (re-search-backward "\\<switch\\>" nil t))
2155
2156 (defun sh-handle-this-rc-case ()
2157 (if (sh-find-prev-switch)
2158 (list '(+ sh-indent-after-switch))
2159 ;; (list '(+ sh-indent-for-case-label))
2160 nil))
2161
2162 (defun sh-handle-prev-rc-case ()
2163 (list '(+ sh-indent-after-case)))
2164
2165 (defun sh-check-rule (n thing)
2166 (let ((rule (nth n (assoc thing sh-kw-alist)))
2167 (val nil))
2168 (if rule
2169 (progn
2170 (setq val (funcall rule))
2171 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2172 n thing (point) rule val)))
2173 val))
2174
2175
2176 (defun sh-get-indent-info ()
2177 "Return indent-info for this line.
2178 This is a list. nil means the line is to be left as is.
2179 Otherwise it contains one or more of the following sublists:
2180 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2181 relative to. If present, this is always the first of the
2182 sublists. The indentation of the line in question is
2183 derived from the indentation of this point, possibly
2184 modified by subsequent sublists.
2185 \(+ VAR\)
2186 \(- VAR\) Get the value of variable VAR and add to or subtract from
2187 the indentation calculated so far.
2188 \(= VAR\) Get the value of variable VAR and *replace* the
2189 indentation with its value. This only occurs for
2190 special variables such as `sh-indent-comment'.
2191 STRING This is ignored for the purposes of calculating
2192 indentation, it is printed in certain cases to help show
2193 what the indentation is based on."
2194 ;; See comments before `sh-kw'.
2195 (save-excursion
2196 (let ((have-result nil)
2197 this-kw
2198 start
2199 val
2200 (result nil)
2201 (align-point nil)
2202 prev-line-end x)
2203 (beginning-of-line)
2204 ;; Note: setting result to t means we are done and will return nil.
2205 ;;(This function never returns just t.)
2206 (cond
2207 ((or (nth 3 (syntax-ppss (point)))
2208 (eq (get-text-property (point) 'face) sh-heredoc-face))
2209 ;; String continuation -- don't indent
2210 (setq result t)
2211 (setq have-result t))
2212 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2213 (if (bobp)
2214 (setq result t) ;; return nil if 1st line!
2215 (setq result (list '(= sh-indent-comment)))
2216 ;; we still need to get previous line in case
2217 ;; sh-indent-comment is t (indent as normal)
2218 (setq align-point (sh-prev-line nil))
2219 (setq have-result nil)
2220 ))
2221 ) ;; cond
2222
2223 (unless have-result
2224 ;; Continuation lines are handled specially
2225 (if (sh-this-is-a-continuation)
2226 (progn
2227 (setq result
2228 (if (save-excursion
2229 (beginning-of-line)
2230 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2231 ;; By convention, if the continuation \ is not
2232 ;; preceded by a SPC or a TAB it means that the line
2233 ;; is cut at a place where spaces cannot be freely
2234 ;; added/removed. I.e. do not indent the line.
2235 (list '(= nil))
2236 ;; We assume the line being continued is already
2237 ;; properly indented...
2238 ;; (setq prev-line-end (sh-prev-line))
2239 (setq align-point (sh-prev-line nil))
2240 (list '(+ sh-indent-for-continuation))))
2241 (setq have-result t))
2242 (beginning-of-line)
2243 (skip-chars-forward " \t")
2244 (setq this-kw (sh-get-kw)))
2245
2246 ;; Handle "this" keyword: first word on the line we're
2247 ;; calculating indentation info for.
2248 (if this-kw
2249 (if (setq val (sh-check-rule 1 this-kw))
2250 (progn
2251 (setq align-point (point))
2252 (sh-debug
2253 "this - setting align-point to %d" align-point)
2254 (setq result (append result val))
2255 (setq have-result t)
2256 ;; set prev-line to continue processing remainder
2257 ;; of this line as a previous line
2258 (setq prev-line-end (point))
2259 ))))
2260
2261 (unless have-result
2262 (setq prev-line-end (sh-prev-line 'end)))
2263
2264 (if prev-line-end
2265 (save-excursion
2266 ;; We start off at beginning of this line.
2267 ;; Scan previous statements while this is <=
2268 ;; start of previous line.
2269 (setq start (point)) ;; for debug only
2270 (goto-char prev-line-end)
2271 (setq x t)
2272 (while (and x (setq x (sh-prev-thing)))
2273 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2274 (cond
2275 ((and (equal x ")")
2276 (equal (get-text-property (1- (point)) 'syntax-table)
2277 sh-st-punc))
2278 (sh-debug "Case label) here")
2279 (setq x 'case-label)
2280 (if (setq val (sh-check-rule 2 x))
2281 (progn
2282 (setq result (append result val))
2283 (setq align-point (point))))
2284 (or (bobp)
2285 (forward-char -1))
2286 ;; FIXME: This charset looks too much like a regexp. --Stef
2287 (skip-chars-forward "[a-z0-9]*?")
2288 )
2289 ((string-match "[])}]" x)
2290 (setq x (sh-safe-forward-sexp -1))
2291 (if x
2292 (progn
2293 (setq align-point (point))
2294 (setq result (append result
2295 (list "aligned to opening paren")))
2296 )))
2297 ((string-match "[[({]" x)
2298 (sh-debug "Checking special thing: %s" x)
2299 (if (setq val (sh-check-rule 2 x))
2300 (setq result (append result val)))
2301 (forward-char -1)
2302 (setq align-point (point)))
2303 ((string-match "[\"'`]" x)
2304 (sh-debug "Skipping back for %s" x)
2305 ;; this was oops-2
2306 (setq x (sh-safe-forward-sexp -1)))
2307 ((stringp x)
2308 (sh-debug "Checking string %s at %s" x (point))
2309 (if (setq val (sh-check-rule 2 x))
2310 ;; (or (eq t (car val))
2311 ;; (eq t (car (car val))))
2312 (setq result (append result val)))
2313 ;; not sure about this test Wed Jan 27 23:48:35 1999
2314 (setq align-point (point))
2315 (unless (bolp)
2316 (forward-char -1)))
2317 (t
2318 (error "Don't know what to do with %s" x))
2319 )
2320 ) ;; while
2321 (sh-debug "result is %s" result)
2322 )
2323 (sh-debug "No prev line!")
2324 (sh-debug "result: %s align-point: %s" result align-point)
2325 )
2326
2327 (if align-point
2328 ;; was: (setq result (append result (list (list t align-point))))
2329 (setq result (append (list (list t align-point)) result))
2330 )
2331 (sh-debug "result is now: %s" result)
2332
2333 (or result
2334 (setq result (list (if prev-line-end
2335 (list t prev-line-end)
2336 (list '= 'sh-first-lines-indent)))))
2337
2338 (if (eq result t)
2339 (setq result nil))
2340 (sh-debug "result is: %s" result)
2341 result
2342 ) ;; let
2343 ))
2344
2345
2346 (defun sh-get-indent-var-for-line (&optional info)
2347 "Return the variable controlling indentation for this line.
2348 If there is not [just] one such variable, return a string
2349 indicating the problem.
2350 If INFO is supplied it is used, else it is calculated."
2351 (let ((var nil)
2352 (result nil)
2353 (reason nil)
2354 sym elt)
2355 (or info
2356 (setq info (sh-get-indent-info)))
2357 (if (null info)
2358 (setq result "this line to be left as is")
2359 (while (and info (null result))
2360 (setq elt (car info))
2361 (cond
2362 ((stringp elt)
2363 (setq reason elt)
2364 )
2365 ((not (listp elt))
2366 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2367 ;; so it is a list
2368 ((eq t (car elt))
2369 ) ;; nothing
2370 ((symbolp (setq sym (nth 1 elt)))
2371 ;; A bit of a kludge - when we see the sh-indent-comment
2372 ;; ignore other variables. Otherwise it is tricky to
2373 ;; "learn" the comment indentation.
2374 (if (eq var 'sh-indent-comment)
2375 (setq result var)
2376 (if var
2377 (setq result
2378 "this line is controlled by more than 1 variable.")
2379 (setq var sym))))
2380 (t
2381 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2382 (setq info (cdr info))
2383 ))
2384 (or result
2385 (setq result var))
2386 (or result
2387 (setq result reason))
2388 (if (null result)
2389 ;; e.g. just had (t POS)
2390 (setq result "line has default indentation"))
2391 result))
2392
2393
2394
2395 ;; Finding the previous line isn't trivial.
2396 ;; We must *always* go back one more and see if that is a continuation
2397 ;; line -- it is the PREVIOUS line which is continued, not the one
2398 ;; we are going to!
2399 ;; Also, we want to treat a whole "here document" as one big line,
2400 ;; because we may want to a align to the beginning of it.
2401 ;;
2402 ;; What we do:
2403 ;; - go back to previous non-empty line
2404 ;; - if this is in a here-document, go to the beginning of it
2405 ;; - while previous line is continued, go back one line
2406 (defun sh-prev-line (&optional end)
2407 "Back to end of previous non-comment non-empty line.
2408 Go to beginning of logical line unless END is non-nil, in which case
2409 we go to the end of the previous line and do not check for continuations."
2410 (save-excursion
2411 (beginning-of-line)
2412 (forward-comment (- (point-max)))
2413 (unless end (beginning-of-line))
2414 (when (and (not (bobp))
2415 (equal (get-text-property (1- (point)) 'face)
2416 sh-heredoc-face))
2417 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2418 (when p1
2419 (goto-char p1)
2420 (if end
2421 (end-of-line)
2422 (beginning-of-line)))))
2423 (unless end
2424 ;; we must check previous lines to see if they are continuation lines
2425 ;; if so, we must return position of first of them
2426 (while (and (sh-this-is-a-continuation)
2427 (>= 0 (forward-line -1))))
2428 (beginning-of-line)
2429 (skip-chars-forward " \t"))
2430 (point)))
2431
2432
2433 (defun sh-prev-stmt ()
2434 "Return the address of the previous stmt or nil."
2435 ;; This is used when we are trying to find a matching keyword.
2436 ;; Searching backward for the keyword would certainly be quicker, but
2437 ;; it is hard to remove "false matches" -- such as if the keyword
2438 ;; appears in a string or quote. This way is slower, but (I think) safer.
2439 (interactive)
2440 (save-excursion
2441 (let ((going t)
2442 (start (point))
2443 (found nil)
2444 (prev nil))
2445 (skip-chars-backward " \t;|&({[")
2446 (while (and (not found)
2447 (not (bobp))
2448 going)
2449 ;; Do a backward-sexp if possible, else backup bit by bit...
2450 (if (sh-safe-forward-sexp -1)
2451 (progn
2452 (if (looking-at sh-special-keywords)
2453 (progn
2454 (setq found prev))
2455 (setq prev (point))
2456 ))
2457 ;; backward-sexp failed
2458 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2459 (forward-char -1))
2460 (if (bolp)
2461 (let ((back (sh-prev-line nil)))
2462 (if back
2463 (goto-char back)
2464 (setq going nil)))))
2465 (unless found
2466 (skip-chars-backward " \t")
2467 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2468 (eq (char-before) ?\;)
2469 (looking-at "\\s-*[|&]"))
2470 (setq found (point)))))
2471 (if found
2472 (goto-char found))
2473 (if found
2474 (progn
2475 (skip-chars-forward " \t|&({[")
2476 (setq found (point))))
2477 (if (>= (point) start)
2478 (progn
2479 (debug "We didn't move!")
2480 (setq found nil))
2481 (or found
2482 (sh-debug "Did not find prev stmt.")))
2483 found)))
2484
2485
2486 (defun sh-get-word ()
2487 "Get a shell word skipping whitespace from point."
2488 (interactive)
2489 (skip-chars-forward "\t ")
2490 (let ((start (point)))
2491 (while
2492 (if (looking-at "[\"'`]")
2493 (sh-safe-forward-sexp)
2494 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2495 (> (skip-chars-forward "-_$[:alnum:]") 0)
2496 ))
2497 (buffer-substring start (point))
2498 ))
2499
2500 (defun sh-prev-thing ()
2501 "Return the previous thing this logical line."
2502 ;; This is called when `sh-get-indent-info' is working backwards on
2503 ;; the previous line(s) finding what keywords may be relevant for
2504 ;; indenting. It moves over sexps if possible, and will stop
2505 ;; on a ; and at the beginning of a line if it is not a continuation
2506 ;; line.
2507 ;;
2508 ;; Added a kludge for ";;"
2509 ;; Possible return values:
2510 ;; nil - nothing
2511 ;; a string - possibly a keyword
2512 ;;
2513 (if (bolp)
2514 nil
2515 (let ((start (point))
2516 (min-point (if (sh-this-is-a-continuation)
2517 (sh-prev-line nil)
2518 (line-beginning-position))))
2519 (skip-chars-backward " \t;" min-point)
2520 (if (looking-at "\\s-*;;")
2521 ;; (message "Found ;; !")
2522 ";;"
2523 (skip-chars-backward "^)}];\"'`({[" min-point)
2524 (let ((c (if (> (point) min-point) (char-before))))
2525 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2526 (point) c start min-point)
2527 (if (not (memq c '(?\n nil ?\;)))
2528 ;; c -- return a string
2529 (char-to-string c)
2530 ;; Return the leading keyword of the "command" we supposedly
2531 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
2532 ;; `then' that precedes the actual command), so check whether
2533 ;; we're looking at such a keyword and if so, move back forward.
2534 (let ((boundary (point))
2535 kwd next)
2536 (while
2537 (progn
2538 ;; Skip forward over white space newline and \ at eol.
2539 (skip-chars-forward " \t\n\\\\" start)
2540 (if (>= (point) start)
2541 (progn
2542 (sh-debug "point: %d >= start: %d" (point) start)
2543 nil)
2544 (if next (setq boundary next))
2545 (sh-debug "Now at %d start=%d" (point) start)
2546 (setq kwd (sh-get-word))
2547 (if (member kwd (sh-feature sh-leading-keywords))
2548 (progn
2549 (setq next (point))
2550 t)
2551 nil))))
2552 (goto-char boundary)
2553 kwd)))))))
2554
2555
2556 (defun sh-this-is-a-continuation ()
2557 "Return non-nil if current line is a continuation of previous line."
2558 (save-excursion
2559 (and (zerop (forward-line -1))
2560 (looking-at ".*\\\\$")
2561 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2562 nil nil nil t))))))
2563
2564 (defun sh-get-kw (&optional where and-move)
2565 "Return first word of line from WHERE.
2566 If AND-MOVE is non-nil then move to end of word."
2567 (let ((start (point)))
2568 (if where
2569 (goto-char where))
2570 (prog1
2571 (buffer-substring (point)
2572 (progn (skip-chars-forward "^ \t\n;&|")(point)))
2573 (unless and-move
2574 (goto-char start)))))
2575
2576 (defun sh-find-prev-matching (open close &optional depth)
2577 "Find a matching token for a set of opening and closing keywords.
2578 This takes into account that there may be nested open..close pairings.
2579 OPEN and CLOSE are regexps denoting the tokens to be matched.
2580 Optional parameter DEPTH (usually 1) says how many to look for."
2581 (let ((parse-sexp-ignore-comments t)
2582 prev)
2583 (setq depth (or depth 1))
2584 (save-excursion
2585 (condition-case nil
2586 (while (and
2587 (/= 0 depth)
2588 (not (bobp))
2589 (setq prev (sh-prev-stmt)))
2590 (goto-char prev)
2591 (save-excursion
2592 (if (looking-at "\\\\\n")
2593 (progn
2594 (forward-char 2)
2595 (skip-chars-forward " \t")))
2596 (cond
2597 ((looking-at open)
2598 (setq depth (1- depth))
2599 (sh-debug "found open at %d - depth = %d" (point) depth))
2600 ((looking-at close)
2601 (setq depth (1+ depth))
2602 (sh-debug "found close - depth = %d" depth))
2603 (t
2604 ))))
2605 (error nil))
2606 (if (eq depth 0)
2607 prev ;; (point)
2608 nil)
2609 )))
2610
2611
2612 (defun sh-var-value (var &optional ignore-error)
2613 "Return the value of variable VAR, interpreting symbols.
2614 It can also return t or nil.
2615 If an invalid value is found, throw an error unless Optional argument
2616 IGNORE-ERROR is non-nil."
2617 (let ((val (symbol-value var)))
2618 (cond
2619 ((numberp val)
2620 val)
2621 ((eq val t)
2622 val)
2623 ((null val)
2624 val)
2625 ((eq val '+)
2626 sh-basic-offset)
2627 ((eq val '-)
2628 (- sh-basic-offset))
2629 ((eq val '++)
2630 (* 2 sh-basic-offset))
2631 ((eq val '--)
2632 (* 2 (- sh-basic-offset)))
2633 ((eq val '*)
2634 (/ sh-basic-offset 2))
2635 ((eq val '/)
2636 (/ (- sh-basic-offset) 2))
2637 (t
2638 (if ignore-error
2639 (progn
2640 (message "Don't know how to handle %s's value of %s" var val)
2641 0)
2642 (error "Don't know how to handle %s's value of %s" var val))
2643 ))))
2644
2645 (defun sh-set-var-value (var value &optional no-symbol)
2646 "Set variable VAR to VALUE.
2647 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2648 can be represented by a symbol then do so."
2649 (cond
2650 (no-symbol
2651 (set var value))
2652 ((= value sh-basic-offset)
2653 (set var '+))
2654 ((= value (- sh-basic-offset))
2655 (set var '-))
2656 ((eq value (* 2 sh-basic-offset))
2657 (set var '++))
2658 ((eq value (* 2 (- sh-basic-offset)))
2659 (set var '--))
2660 ((eq value (/ sh-basic-offset 2))
2661 (set var '*))
2662 ((eq value (/ (- sh-basic-offset) 2))
2663 (set var '/))
2664 (t
2665 (set var value)))
2666 )
2667
2668
2669 (defun sh-calculate-indent (&optional info)
2670 "Return the indentation for the current line.
2671 If INFO is supplied it is used, else it is calculated from current line."
2672 (let ((ofs 0)
2673 (base-value 0)
2674 elt a b var val)
2675 (or info
2676 (setq info (sh-get-indent-info)))
2677 (when info
2678 (while info
2679 (sh-debug "info: %s ofs=%s" info ofs)
2680 (setq elt (car info))
2681 (cond
2682 ((stringp elt)) ;; do nothing?
2683 ((listp elt)
2684 (setq a (car (car info)))
2685 (setq b (nth 1 (car info)))
2686 (cond
2687 ((eq a t)
2688 (save-excursion
2689 (goto-char b)
2690 (setq val (current-indentation)))
2691 (setq base-value val))
2692 ((symbolp b)
2693 (setq val (sh-var-value b))
2694 (cond
2695 ((eq a '=)
2696 (cond
2697 ((null val)
2698 ;; no indentation
2699 ;; set info to nil so we stop immediately
2700 (setq base-value nil ofs nil info nil))
2701 ((eq val t) (setq ofs 0)) ;; indent as normal line
2702 (t
2703 ;; The following assume the (t POS) come first!
2704 (setq ofs val base-value 0)
2705 (setq info nil)))) ;; ? stop now
2706 ((eq a '+) (setq ofs (+ ofs val)))
2707 ((eq a '-) (setq ofs (- ofs val)))
2708 (t
2709 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2710 (t
2711 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2712 (t
2713 (error "sh-calculate-indent invalid elt %s" elt)))
2714 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2715 a b val base-value ofs)
2716 (setq info (cdr info)))
2717 ;; return value:
2718 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2719
2720 (cond
2721 ((or (null base-value)(null ofs))
2722 nil)
2723 ((and (numberp base-value)(numberp ofs))
2724 (sh-debug "base (%d) + ofs (%d) = %d"
2725 base-value ofs (+ base-value ofs))
2726 (+ base-value ofs)) ;; return value
2727 (t
2728 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2729 base-value ofs)
2730 nil)))))
2731
2732
2733 (defun sh-indent-line ()
2734 "Indent the current line."
2735 (interactive)
2736 (let ((indent (sh-calculate-indent))
2737 (pos (- (point-max) (point))))
2738 (when indent
2739 (beginning-of-line)
2740 (skip-chars-forward " \t")
2741 (indent-line-to indent)
2742 ;; If initial point was within line's indentation,
2743 ;; position after the indentation. Else stay at same point in text.
2744 (if (> (- (point-max) pos) (point))
2745 (goto-char (- (point-max) pos))))))
2746
2747
2748 (defun sh-blink (blinkpos &optional msg)
2749 "Move cursor momentarily to BLINKPOS and display MSG."
2750 ;; We can get here without it being a number on first line
2751 (if (numberp blinkpos)
2752 (save-excursion
2753 (goto-char blinkpos)
2754 (if msg (message "%s" msg) (message nil))
2755 (sit-for blink-matching-delay))
2756 (if msg (message "%s" msg) (message nil))))
2757
2758 (defun sh-show-indent (arg)
2759 "Show the how the current line would be indented.
2760 This tells you which variable, if any, controls the indentation of
2761 this line.
2762 If optional arg ARG is non-null (called interactively with a prefix),
2763 a pop up window describes this variable.
2764 If variable `sh-blink' is non-nil then momentarily go to the line
2765 we are indenting relative to, if applicable."
2766 (interactive "P")
2767 (sh-must-support-indent)
2768 (let* ((info (sh-get-indent-info))
2769 (var (sh-get-indent-var-for-line info))
2770 (curr-indent (current-indentation))
2771 val msg)
2772 (if (stringp var)
2773 (message "%s" (setq msg var))
2774 (setq val (sh-calculate-indent info))
2775
2776 (if (eq curr-indent val)
2777 (setq msg (format "%s is %s" var (symbol-value var)))
2778 (setq msg
2779 (if val
2780 (format "%s (%s) would change indent from %d to: %d"
2781 var (symbol-value var) curr-indent val)
2782 (format "%s (%s) would leave line as is"
2783 var (symbol-value var)))
2784 ))
2785 (if (and arg var)
2786 (describe-variable var)))
2787 (if sh-blink
2788 (let ((info (sh-get-indent-info)))
2789 (if (and info (listp (car info))
2790 (eq (car (car info)) t))
2791 (sh-blink (nth 1 (car info)) msg)
2792 (message "%s" msg)))
2793 (message "%s" msg))
2794 ))
2795
2796 (defun sh-set-indent ()
2797 "Set the indentation for the current line.
2798 If the current line is controlled by an indentation variable, prompt
2799 for a new value for it."
2800 (interactive)
2801 (sh-must-support-indent)
2802 (let* ((info (sh-get-indent-info))
2803 (var (sh-get-indent-var-for-line info))
2804 val old-val indent-val)
2805 (if (stringp var)
2806 (message "Cannot set indent - %s" var)
2807 (setq old-val (symbol-value var))
2808 (setq val (sh-read-variable var))
2809 (condition-case nil
2810 (progn
2811 (set var val)
2812 (setq indent-val (sh-calculate-indent info))
2813 (if indent-val
2814 (message "Variable: %s Value: %s would indent to: %d"
2815 var (symbol-value var) indent-val)
2816 (message "Variable: %s Value: %s would leave line as is."
2817 var (symbol-value var)))
2818 ;; I'm not sure about this, indenting it now?
2819 ;; No. Because it would give the impression that an undo would
2820 ;; restore thing, but the value has been altered.
2821 ;; (sh-indent-line)
2822 )
2823 (error
2824 (set var old-val)
2825 (message "Bad value for %s, restoring to previous value %s"
2826 var old-val)
2827 (sit-for 1)
2828 nil))
2829 )))
2830
2831
2832 (defun sh-learn-line-indent (arg)
2833 "Learn how to indent a line as it currently is indented.
2834
2835 If there is an indentation variable which controls this line's indentation,
2836 then set it to a value which would indent the line the way it
2837 presently is.
2838
2839 If the value can be represented by one of the symbols then do so
2840 unless optional argument ARG (the prefix when interactive) is non-nil."
2841 (interactive "*P")
2842 (sh-must-support-indent)
2843 ;; I'm not sure if we show allow learning on an empty line.
2844 ;; Though it might occasionally be useful I think it usually
2845 ;; would just be confusing.
2846 (if (save-excursion
2847 (beginning-of-line)
2848 (looking-at "\\s-*$"))
2849 (message "sh-learn-line-indent ignores empty lines.")
2850 (let* ((info (sh-get-indent-info))
2851 (var (sh-get-indent-var-for-line info))
2852 ival sval diff new-val
2853 (no-symbol arg)
2854 (curr-indent (current-indentation)))
2855 (cond
2856 ((stringp var)
2857 (message "Cannot learn line - %s" var))
2858 ((eq var 'sh-indent-comment)
2859 ;; This is arbitrary...
2860 ;; - if curr-indent is 0, set to curr-indent
2861 ;; - else if it has the indentation of a "normal" line,
2862 ;; then set to t
2863 ;; - else set to curr-indent.
2864 (setq sh-indent-comment
2865 (if (= curr-indent 0)
2866 0
2867 (let* ((sh-indent-comment t)
2868 (val2 (sh-calculate-indent info)))
2869 (if (= val2 curr-indent)
2870 t
2871 curr-indent))))
2872 (message "%s set to %s" var (symbol-value var))
2873 )
2874 ((numberp (setq sval (sh-var-value var)))
2875 (setq ival (sh-calculate-indent info))
2876 (setq diff (- curr-indent ival))
2877
2878 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2879 curr-indent ival diff var sval)
2880 (setq new-val (+ sval diff))
2881 ;;; I commented out this because someone might want to replace
2882 ;;; a value of `+' with the current value of sh-basic-offset
2883 ;;; or vice-versa.
2884 ;;; (if (= 0 diff)
2885 ;;; (message "No change needed!")
2886 (sh-set-var-value var new-val no-symbol)
2887 (message "%s set to %s" var (symbol-value var))
2888 )
2889 (t
2890 (debug)
2891 (message "Cannot change %s" var))))))
2892
2893
2894
2895 (defun sh-mark-init (buffer)
2896 "Initialize a BUFFER to be used by `sh-mark-line'."
2897 (with-current-buffer (get-buffer-create buffer)
2898 (erase-buffer)
2899 (occur-mode)))
2900
2901
2902 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2903 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2904 Buffer BUFFER is in `occur-mode'.
2905 If ADD-LINENUM is non-nil the message is preceded by the line number.
2906 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2907 so that `occur-next' and `occur-prev' will work."
2908 (let ((m1 (make-marker))
2909 start
2910 (line ""))
2911 (when point
2912 (set-marker m1 point (current-buffer))
2913 (if add-linenum
2914 (setq line (format "%d: " (1+ (count-lines 1 point))))))
2915 (save-excursion
2916 (if (get-buffer buffer)
2917 (set-buffer (get-buffer buffer))
2918 (set-buffer (get-buffer-create buffer))
2919 (occur-mode)
2920 )
2921 (goto-char (point-max))
2922 (setq start (point))
2923 (insert line)
2924 (if occur-point
2925 (setq occur-point (point)))
2926 (insert message)
2927 (if point
2928 (add-text-properties
2929 start (point)
2930 '(mouse-face highlight
2931 help-echo "mouse-2: go to the line where I learned this")))
2932 (insert "\n")
2933 (if point
2934 (progn
2935 (put-text-property start (point) 'occur-target m1)
2936 (if occur-point
2937 (put-text-property start occur-point
2938 'occur-match t))
2939 ))
2940 )))
2941
2942
2943
2944 ;; Is this really worth having?
2945 (defvar sh-learned-buffer-hook nil
2946 "*An abnormal hook, called with an alist of learned variables.")
2947 ;; Example of how to use sh-learned-buffer-hook
2948 ;;
2949 ;; (defun what-i-learned (list)
2950 ;; (let ((p list))
2951 ;; (with-current-buffer "*scratch*"
2952 ;; (goto-char (point-max))
2953 ;; (insert "(setq\n")
2954 ;; (while p
2955 ;; (insert (format " %s %s \n"
2956 ;; (nth 0 (car p)) (nth 1 (car p))))
2957 ;; (setq p (cdr p)))
2958 ;; (insert ")\n")
2959 ;; )))
2960 ;;
2961 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2962
2963
2964 ;; Originally this was sh-learn-region-indent (beg end)
2965 ;; However, in practice this was awkward so I changed it to
2966 ;; use the whole buffer. Use narrowing if needbe.
2967 (defun sh-learn-buffer-indent (&optional arg)
2968 "Learn how to indent the buffer the way it currently is.
2969
2970 Output in buffer \"*indent*\" shows any lines which have conflicting
2971 values of a variable, and the final value of all variables learned.
2972 When called interactively, pop to this buffer automatically if
2973 there are any discrepancies.
2974
2975 If no prefix ARG is given, then variables are set to numbers.
2976 If a prefix arg is given, then variables are set to symbols when
2977 applicable -- e.g. to symbol `+' if the value is that of the
2978 basic indent.
2979 If a positive numerical prefix is given, then `sh-basic-offset'
2980 is set to the prefix's numerical value.
2981 Otherwise, sh-basic-offset may or may not be changed, according
2982 to the value of variable `sh-learn-basic-offset'.
2983
2984 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2985 function completes. The function is abnormal because it is called
2986 with an alist of variables learned. This feature may be changed or
2987 removed in the future.
2988
2989 This command can often take a long time to run."
2990 (interactive "P")
2991 (sh-must-support-indent)
2992 (save-excursion
2993 (goto-char (point-min))
2994 (let ((learned-var-list nil)
2995 (out-buffer "*indent*")
2996 (num-diffs 0)
2997 previous-set-info
2998 (max 17)
2999 vec
3000 msg
3001 (comment-col nil) ;; number if all same, t if seen diff values
3002 (comments-always-default t) ;; nil if we see one not default
3003 initial-msg
3004 (specified-basic-offset (and arg (numberp arg)
3005 (> arg 0)))
3006 (linenum 0)
3007 suggested)
3008 (setq vec (make-vector max 0))
3009 (sh-mark-init out-buffer)
3010
3011 (if specified-basic-offset
3012 (progn
3013 (setq sh-basic-offset arg)
3014 (setq initial-msg
3015 (format "Using specified sh-basic-offset of %d"
3016 sh-basic-offset)))
3017 (setq initial-msg
3018 (format "Initial value of sh-basic-offset: %s"
3019 sh-basic-offset)))
3020
3021 (while (< (point) (point-max))
3022 (setq linenum (1+ linenum))
3023 ;; (if (zerop (% linenum 10))
3024 (message "line %d" linenum)
3025 ;; )
3026 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3027 (let* ((sh-indent-comment t) ;; info must return default indent
3028 (info (sh-get-indent-info))
3029 (var (sh-get-indent-var-for-line info))
3030 sval ival diff new-val
3031 (curr-indent (current-indentation)))
3032 (cond
3033 ((null var)
3034 nil)
3035 ((stringp var)
3036 nil)
3037 ((numberp (setq sval (sh-var-value var 'no-error)))
3038 ;; the numberp excludes comments since sval will be t.
3039 (setq ival (sh-calculate-indent))
3040 (setq diff (- curr-indent ival))
3041 (setq new-val (+ sval diff))
3042 (sh-set-var-value var new-val 'no-symbol)
3043 (unless (looking-at "\\s-*#") ;; don't learn from comments
3044 (if (setq previous-set-info (assoc var learned-var-list))
3045 (progn
3046 ;; it was already there, is it same value ?
3047 (unless (eq (symbol-value var)
3048 (nth 1 previous-set-info))
3049 (sh-mark-line
3050 (format "Variable %s was set to %s"
3051 var (symbol-value var))
3052 (point) out-buffer t t)
3053 (sh-mark-line
3054 (format " but was previously set to %s"
3055 (nth 1 previous-set-info))
3056 (nth 2 previous-set-info) out-buffer t)
3057 (setq num-diffs (1+ num-diffs))
3058 ;; (delete previous-set-info learned-var-list)
3059 (setcdr previous-set-info
3060 (list (symbol-value var) (point)))
3061 )
3062 )
3063 (setq learned-var-list
3064 (append (list (list var (symbol-value var)
3065 (point)))
3066 learned-var-list)))
3067 (if (numberp new-val)
3068 (progn
3069 (sh-debug
3070 "This line's indent value: %d" new-val)
3071 (if (< new-val 0)
3072 (setq new-val (- new-val)))
3073 (if (< new-val max)
3074 (aset vec new-val (1+ (aref vec new-val))))))
3075 ))
3076 ((eq var 'sh-indent-comment)
3077 (unless (= curr-indent (sh-calculate-indent info))
3078 ;; this is not the default indentation
3079 (setq comments-always-default nil)
3080 (if comment-col ;; then we have see one before
3081 (or (eq comment-col curr-indent)
3082 (setq comment-col t)) ;; seen a different one
3083 (setq comment-col curr-indent))
3084 ))
3085 (t
3086 (sh-debug "Cannot learn this line!!!")
3087 ))
3088 (sh-debug
3089 "at %s learned-var-list is %s" (point) learned-var-list)
3090 ))
3091 (forward-line 1)
3092 ) ;; while
3093 (if sh-debug
3094 (progn
3095 (setq msg (format
3096 "comment-col = %s comments-always-default = %s"
3097 comment-col comments-always-default))
3098 ;; (message msg)
3099 (sh-mark-line msg nil out-buffer)))
3100 (cond
3101 ((eq comment-col 0)
3102 (setq msg "\nComments are all in 1st column.\n"))
3103 (comments-always-default
3104 (setq msg "\nComments follow default indentation.\n")
3105 (setq comment-col t))
3106 ((numberp comment-col)
3107 (setq msg (format "\nComments are in col %d." comment-col)))
3108 (t
3109 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3110 (setq comment-col nil)
3111 ))
3112 (sh-debug msg)
3113 (sh-mark-line msg nil out-buffer)
3114
3115 (sh-mark-line initial-msg nil out-buffer t t)
3116
3117 (setq suggested (sh-guess-basic-offset vec))
3118
3119 (if (and suggested (not specified-basic-offset))
3120 (let ((new-value
3121 (cond
3122 ;; t => set it if we have a single value as a number
3123 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3124 suggested)
3125 ;; other non-nil => set it if only one value was found
3126 (sh-learn-basic-offset
3127 (if (numberp suggested)
3128 suggested
3129 (if (= (length suggested) 1)
3130 (car suggested))))
3131 (t
3132 nil))))
3133 (if new-value
3134 (progn
3135 (setq learned-var-list
3136 (append (list (list 'sh-basic-offset
3137 (setq sh-basic-offset new-value)
3138 (point-max)))
3139 learned-var-list))
3140 ;; Not sure if we need to put this line in, since
3141 ;; it will appear in the "Learned variable settings".
3142 (sh-mark-line
3143 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3144 nil out-buffer))
3145 (sh-mark-line
3146 (if (listp suggested)
3147 (format "Possible value(s) for sh-basic-offset: %s"
3148 (mapconcat 'int-to-string suggested " "))
3149 (format "Suggested sh-basic-offset: %d" suggested))
3150 nil out-buffer))))
3151
3152
3153 (setq learned-var-list
3154 (append (list (list 'sh-indent-comment comment-col (point-max)))
3155 learned-var-list))
3156 (setq sh-indent-comment comment-col)
3157 (let ((name (buffer-name)))
3158 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3159 (if arg
3160 ;; Set learned variables to symbolic rather than numeric
3161 ;; values where possible.
3162 (dolist (learned-var (reverse learned-var-list))
3163 (let ((var (car learned-var))
3164 (val (nth 1 learned-var)))
3165 (when (and (not (eq var 'sh-basic-offset))
3166 (numberp val))
3167 (sh-set-var-value var val)))))
3168 (dolist (learned-var (reverse learned-var-list))
3169 (let ((var (car learned-var)))
3170 (sh-mark-line (format " %s %s" var (symbol-value var))
3171 (nth 2 learned-var) out-buffer)))
3172 (with-current-buffer out-buffer
3173 (goto-char (point-min))
3174 (insert
3175 (format "Indentation values for buffer %s.\n" name)
3176 (format "%d indentation variable%s different values%s\n\n"
3177 num-diffs
3178 (if (= num-diffs 1)
3179 " has" "s have")
3180 (if (zerop num-diffs)
3181 "." ":"))
3182 )))
3183 ;; Are abnormal hooks considered bad form?
3184 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3185 (and (called-interactively-p 'any)
3186 (or sh-popup-occur-buffer (> num-diffs 0))
3187 (pop-to-buffer out-buffer)))))
3188
3189 (defun sh-guess-basic-offset (vec)
3190 "See if we can determine a reasonable value for `sh-basic-offset'.
3191 This is experimental, heuristic and arbitrary!
3192 Argument VEC is a vector of information collected by
3193 `sh-learn-buffer-indent'.
3194 Return values:
3195 number - there appears to be a good single value
3196 list of numbers - no obvious one, here is a list of one or more
3197 reasonable choices
3198 nil - we couldn't find a reasonable one."
3199 (let* ((max (1- (length vec)))
3200 (i 1)
3201 (totals (make-vector max 0)))
3202 (while (< i max)
3203 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
3204 (if (zerop (% i 2))
3205 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3206 (if (< (* i 2) max)
3207 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3208 (setq i (1+ i)))
3209
3210 (let ((x nil)
3211 (result nil)
3212 tot sum p)
3213 (setq i 1)
3214 (while (< i max)
3215 (if (/= (aref totals i) 0)
3216 (setq x (append x (list (cons i (aref totals i))))))
3217 (setq i (1+ i)))
3218
3219 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3220 (setq tot (apply '+ (append totals nil)))
3221 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3222 vec totals tot))
3223 (cond
3224 ((zerop (length x))
3225 (message "no values!")) ;; we return nil
3226 ((= (length x) 1)
3227 (message "only value is %d" (car (car x)))
3228 (setq result (car (car x)))) ;; return single value
3229 ((> (cdr (car x)) (/ tot 2))
3230 ;; 1st is > 50%
3231 (message "basic-offset is probably %d" (car (car x)))
3232 (setq result (car (car x)))) ;; again, return a single value
3233 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3234 ;; 1st is >= 2 * 2nd
3235 (message "basic-offset could be %d" (car (car x)))
3236 (setq result (car (car x))))
3237 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3238 ;; 1st & 2nd together >= 50% - return a list
3239 (setq p x sum 0 result nil)
3240 (while (and p
3241 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3242 (setq result (append result (list (car (car p)))))
3243 (setq p (cdr p)))
3244 (message "Possible choices for sh-basic-offset: %s"
3245 (mapconcat 'int-to-string result " ")))
3246 (t
3247 (message "No obvious value for sh-basic-offset. Perhaps %d"
3248 (car (car x)))
3249 ;; result is nil here
3250 ))
3251 result)))
3252
3253 ;; ========================================================================
3254
3255 ;; Styles -- a quick and dirty way of saving the indentation settings.
3256
3257 (defvar sh-styles-alist nil
3258 "A list of all known shell indentation styles.")
3259
3260 (defun sh-name-style (name &optional confirm-overwrite)
3261 "Name the current indentation settings as a style called NAME.
3262 If this name exists, the command will prompt whether it should be
3263 overwritten if
3264 - - it was called interactively with a prefix argument, or
3265 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3266 ;; (interactive "sName for this style: ")
3267 (interactive
3268 (list
3269 (read-from-minibuffer "Name for this style? " )
3270 (not current-prefix-arg)))
3271 (let ((slist (cons name
3272 (mapcar (lambda (var) (cons var (symbol-value var)))
3273 sh-var-list)))
3274 (style (assoc name sh-styles-alist)))
3275 (if style
3276 (if (and confirm-overwrite
3277 (not (y-or-n-p "This style exists. Overwrite it? ")))
3278 (message "Not changing style %s" name)
3279 (message "Updating style %s" name)
3280 (setcdr style (cdr slist)))
3281 (message "Creating new style %s" name)
3282 (push slist sh-styles-alist))))
3283
3284 (defun sh-load-style (name)
3285 "Set shell indentation values for this buffer from those in style NAME."
3286 (interactive (list (completing-read
3287 "Which style to use for this buffer? "
3288 sh-styles-alist nil t)))
3289 (let ((sl (assoc name sh-styles-alist)))
3290 (if (null sl)
3291 (error "sh-load-style - style %s not known" name)
3292 (dolist (var (cdr sl))
3293 (set (car var) (cdr var))))))
3294
3295 (defun sh-save-styles-to-buffer (buff)
3296 "Save all current styles in elisp to buffer BUFF.
3297 This is always added to the end of the buffer."
3298 (interactive (list
3299 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3300 (with-current-buffer (get-buffer-create buff)
3301 (goto-char (point-max))
3302 (insert "\n")
3303 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3304
3305
3306 \f
3307 ;; statement syntax-commands for various shells
3308
3309 ;; You are welcome to add the syntax or even completely new statements as
3310 ;; appropriate for your favorite shell.
3311
3312 (defconst sh-non-closing-paren
3313 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3314 ;; that inherits this property, which then confuses the indentation.
3315 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3316
3317 (define-skeleton sh-case
3318 "Insert a case/switch statement. See `sh-feature'."
3319 (csh "expression: "
3320 "switch( " str " )" \n
3321 > "case " (read-string "pattern: ") ?: \n
3322 > _ \n
3323 "breaksw" \n
3324 ( "other pattern, %s: "
3325 < "case " str ?: \n
3326 > _ \n
3327 "breaksw" \n)
3328 < "default:" \n
3329 > _ \n
3330 resume:
3331 < < "endsw" \n)
3332 (es)
3333 (rc "expression: "
3334 > "switch( " str " ) {" \n
3335 > "case " (read-string "pattern: ") \n
3336 > _ \n
3337 ( "other pattern, %s: "
3338 "case " str > \n
3339 > _ \n)
3340 "case *" > \n
3341 > _ \n
3342 resume:
3343 ?\} > \n)
3344 (sh "expression: "
3345 > "case " str " in" \n
3346 ( "pattern, %s: "
3347 > str sh-non-closing-paren \n
3348 > _ \n
3349 ";;" \n)
3350 > "*" sh-non-closing-paren \n
3351 > _ \n
3352 resume:
3353 "esac" > \n))
3354
3355 (define-skeleton sh-for
3356 "Insert a for loop. See `sh-feature'."
3357 (csh sh-modify sh
3358 1 ""
3359 2 "foreach "
3360 4 " ( "
3361 6 " )"
3362 15 '<
3363 16 "end")
3364 (es sh-modify rc
3365 4 " = ")
3366 (rc sh-modify sh
3367 2 "for( "
3368 6 " ) {"
3369 15 ?\} )
3370 (sh "Index variable: "
3371 > "for " str " in " _ "; do" \n
3372 > _ | ?$ & (sh-remember-variable str) \n
3373 "done" > \n))
3374
3375
3376
3377 (define-skeleton sh-indexed-loop
3378 "Insert an indexed loop from 1 to n. See `sh-feature'."
3379 (bash sh-modify posix)
3380 (csh "Index variable: "
3381 "@ " str " = 1" \n
3382 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3383 > _ ?$ str \n
3384 "@ " str "++" \n
3385 < "end" \n)
3386 (es sh-modify rc
3387 4 " =")
3388 (ksh88 "Index variable: "
3389 > "integer " str "=0" \n
3390 > "while (( ( " str " += 1 ) <= "
3391 (read-string "upper limit: ")
3392 " )); do" \n
3393 > _ ?$ (sh-remember-variable str) > \n
3394 "done" > \n)
3395 (posix "Index variable: "
3396 > str "=1" \n
3397 "while [ $" str " -le "
3398 (read-string "upper limit: ")
3399 " ]; do" \n
3400 > _ ?$ str \n
3401 str ?= (sh-add (sh-remember-variable str) 1) \n
3402 "done" > \n)
3403 (rc "Index variable: "
3404 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3405 (read-string "upper limit: ")
3406 "; i++ ) print i }'`}) {" \n
3407 > _ ?$ (sh-remember-variable str) \n
3408 ?\} > \n)
3409 (sh "Index variable: "
3410 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3411 (read-string "upper limit: ")
3412 "; i++ ) print i }'`; do" \n
3413 > _ ?$ (sh-remember-variable str) \n
3414 "done" > \n))
3415
3416
3417 (defun sh-shell-initialize-variables ()
3418 "Scan the buffer for variable assignments.
3419 Add these variables to `sh-shell-variables'."
3420 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3421 (save-excursion
3422 (goto-char (point-min))
3423 (setq sh-shell-variables-initialized t)
3424 (while (search-forward "=" nil t)
3425 (sh-assignment 0)))
3426 (message "Scanning buffer `%s' for variable assignments...done"
3427 (buffer-name)))
3428
3429 (defvar sh-add-buffer)
3430
3431 (defun sh-add-completer (string predicate code)
3432 "Do completion using `sh-shell-variables', but initialize it first.
3433 This function is designed for use as the \"completion table\",
3434 so it takes three arguments:
3435 STRING, the current buffer contents;
3436 PREDICATE, the predicate for filtering possible matches;
3437 CODE, which says what kind of things to do.
3438 CODE can be nil, t or `lambda'.
3439 nil means to return the best completion of STRING, or nil if there is none.
3440 t means to return a list of all possible completions of STRING.
3441 `lambda' means to return t if STRING is a valid completion as it stands."
3442 (let ((vars
3443 (with-current-buffer sh-add-buffer
3444 (or sh-shell-variables-initialized
3445 (sh-shell-initialize-variables))
3446 (nconc (mapcar (lambda (var)
3447 (substring var 0 (string-match "=" var)))
3448 process-environment)
3449 sh-shell-variables))))
3450 (complete-with-action code vars string predicate)))
3451
3452 (defun sh-add (var delta)
3453 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3454 (interactive
3455 (let ((sh-add-buffer (current-buffer)))
3456 (list (completing-read "Variable: " 'sh-add-completer)
3457 (prefix-numeric-value current-prefix-arg))))
3458 (insert (sh-feature '((bash . "$(( ")
3459 (ksh88 . "$(( ")
3460 (posix . "$(( ")
3461 (rc . "`{expr $")
3462 (sh . "`expr $")
3463 (zsh . "$[ ")))
3464 (sh-remember-variable var)
3465 (if (< delta 0) " - " " + ")
3466 (number-to-string (abs delta))
3467 (sh-feature '((bash . " ))")
3468 (ksh88 . " ))")
3469 (posix . " ))")
3470 (rc . "}")
3471 (sh . "`")
3472 (zsh . " ]")))))
3473
3474
3475
3476 (define-skeleton sh-function
3477 "Insert a function definition. See `sh-feature'."
3478 (bash sh-modify ksh88
3479 3 "() {")
3480 (ksh88 "name: "
3481 "function " str " {" \n
3482 > _ \n
3483 < "}" \n)
3484 (rc sh-modify ksh88
3485 1 "fn ")
3486 (sh ()
3487 "() {" \n
3488 > _ \n
3489 < "}" \n))
3490
3491
3492
3493 (define-skeleton sh-if
3494 "Insert an if statement. See `sh-feature'."
3495 (csh "condition: "
3496 "if( " str " ) then" \n
3497 > _ \n
3498 ( "other condition, %s: "
3499 < "else if( " str " ) then" \n
3500 > _ \n)
3501 < "else" \n
3502 > _ \n
3503 resume:
3504 < "endif" \n)
3505 (es "condition: "
3506 > "if { " str " } {" \n
3507 > _ \n
3508 ( "other condition, %s: "
3509 "} { " str " } {" > \n
3510 > _ \n)
3511 "} {" > \n
3512 > _ \n
3513 resume:
3514 ?\} > \n)
3515 (rc "condition: "
3516 > "if( " str " ) {" \n
3517 > _ \n
3518 ( "other condition, %s: "
3519 "} else if( " str " ) {" > \n
3520 > _ \n)
3521 "} else {" > \n
3522 > _ \n
3523 resume:
3524 ?\} > \n)
3525 (sh "condition: "
3526 '(setq input (sh-feature sh-test))
3527 > "if " str "; then" \n
3528 > _ \n
3529 ( "other condition, %s: "
3530 > "elif " str "; then" > \n
3531 > \n)
3532 "else" > \n
3533 > \n
3534 resume:
3535 "fi" > \n))
3536
3537
3538
3539 (define-skeleton sh-repeat
3540 "Insert a repeat loop definition. See `sh-feature'."
3541 (es nil
3542 > "forever {" \n
3543 > _ \n
3544 ?\} > \n)
3545 (zsh "factor: "
3546 > "repeat " str "; do" > \n
3547 > \n
3548 "done" > \n))
3549
3550 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3551
3552
3553
3554 (define-skeleton sh-select
3555 "Insert a select statement. See `sh-feature'."
3556 (ksh88 "Index variable: "
3557 > "select " str " in " _ "; do" \n
3558 > ?$ str \n
3559 "done" > \n)
3560 (bash sh-append ksh88))
3561 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3562
3563
3564
3565 (define-skeleton sh-tmp-file
3566 "Insert code to setup temporary file handling. See `sh-feature'."
3567 (bash sh-append ksh88)
3568 (csh (file-name-nondirectory (buffer-file-name))
3569 "set tmp = `mktemp -t " str ".XXXXXX`" \n
3570 "onintr exit" \n _
3571 (and (goto-char (point-max))
3572 (not (bolp))
3573 ?\n)
3574 "exit:\n"
3575 "rm $tmp* >&/dev/null" > \n)
3576 (es (file-name-nondirectory (buffer-file-name))
3577 > "local( signals = $signals sighup sigint;" \n
3578 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
3579 > "catch @ e {" \n
3580 > "rm $tmp^* >[2]/dev/null" \n
3581 "throw $e" \n
3582 "} {" > \n
3583 _ \n
3584 ?\} > \n
3585 ?\} > \n)
3586 (ksh88 sh-modify sh
3587 7 "EXIT")
3588 (rc (file-name-nondirectory (buffer-file-name))
3589 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
3590 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3591 (sh (file-name-nondirectory (buffer-file-name))
3592 > "TMP=`mktemp -t " str ".XXXXXX`" \n
3593 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
3594
3595
3596
3597 (define-skeleton sh-until
3598 "Insert an until loop. See `sh-feature'."
3599 (sh "condition: "
3600 '(setq input (sh-feature sh-test))
3601 > "until " str "; do" \n
3602 > _ \n
3603 "done" > \n))
3604 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3605
3606
3607
3608 (define-skeleton sh-while
3609 "Insert a while loop. See `sh-feature'."
3610 (csh sh-modify sh
3611 2 ""
3612 3 "while( "
3613 5 " )"
3614 10 '<
3615 11 "end")
3616 (es sh-modify sh
3617 3 "while { "
3618 5 " } {"
3619 10 ?\} )
3620 (rc sh-modify sh
3621 3 "while( "
3622 5 " ) {"
3623 10 ?\} )
3624 (sh "condition: "
3625 '(setq input (sh-feature sh-test))
3626 > "while " str "; do" \n
3627 > _ \n
3628 "done" > \n))
3629
3630
3631
3632 (define-skeleton sh-while-getopts
3633 "Insert a while getopts loop. See `sh-feature'.
3634 Prompts for an options string which consists of letters for each recognized
3635 option followed by a colon `:' if the option accepts an argument."
3636 (bash sh-modify sh
3637 18 "${0##*/}")
3638 (csh nil
3639 "while( 1 )" \n
3640 > "switch( \"$1\" )" \n
3641 '(setq input '("- x" . 2))
3642 > >
3643 ( "option, %s: "
3644 < "case " '(eval str)
3645 '(if (string-match " +" str)
3646 (setq v1 (substring str (match-end 0))
3647 str (substring str 0 (match-beginning 0)))
3648 (setq v1 nil))
3649 str ?: \n
3650 > "set " v1 & " = $2" | -4 & _ \n
3651 (if v1 "shift") & \n
3652 "breaksw" \n)
3653 < "case --:" \n
3654 > "shift" \n
3655 < "default:" \n
3656 > "break" \n
3657 resume:
3658 < < "endsw" \n
3659 "shift" \n
3660 < "end" \n)
3661 (ksh88 sh-modify sh
3662 16 "print"
3663 18 "${0##*/}"
3664 37 "OPTIND-1")
3665 (posix sh-modify sh
3666 18 "$(basename $0)")
3667 (sh "optstring: "
3668 > "while getopts :" str " OPT; do" \n
3669 > "case $OPT in" \n
3670 '(setq v1 (append (vconcat str) nil))
3671 ( (prog1 (if v1 (char-to-string (car v1)))
3672 (if (eq (nth 1 v1) ?:)
3673 (setq v1 (nthcdr 2 v1)
3674 v2 "\"$OPTARG\"")
3675 (setq v1 (cdr v1)
3676 v2 nil)))
3677 > str "|+" str sh-non-closing-paren \n
3678 > _ v2 \n
3679 > ";;" \n)
3680 > "*" sh-non-closing-paren \n
3681 > "echo" " \"usage: " "`basename $0`"
3682 " [+-" '(setq v1 (point)) str
3683 '(save-excursion
3684 (while (search-backward ":" v1 t)
3685 (replace-match " ARG] [+-" t t)))
3686 (if (eq (preceding-char) ?-) -5)
3687 (if (and (sequencep v1) (length v1)) "] " "} ")
3688 "[--] ARGS...\"" \n
3689 "exit 2" > \n
3690 "esac" >
3691 \n "done"
3692 > \n
3693 "shift " (sh-add "OPTIND" -1) \n
3694 "OPTIND=1" \n))
3695
3696
3697
3698 (defun sh-assignment (arg)
3699 "Remember preceding identifier for future completion and do self-insert."
3700 (interactive "p")
3701 (self-insert-command arg)
3702 (if (<= arg 1)
3703 (sh-remember-variable
3704 (save-excursion
3705 (if (re-search-forward (sh-feature sh-assignment-regexp)
3706 (prog1 (point)
3707 (beginning-of-line 1))
3708 t)
3709 (match-string 1))))))
3710
3711
3712 (defun sh-maybe-here-document (arg)
3713 "Insert self. Without prefix, following unquoted `<' inserts here document.
3714 The document is bounded by `sh-here-document-word'."
3715 (interactive "*P")
3716 (self-insert-command (prefix-numeric-value arg))
3717 (or arg
3718 (not (looking-back "[^<]<<"))
3719 (save-excursion
3720 (backward-char 2)
3721 (sh-quoted-p))
3722 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
3723 (make-string (/ (current-indentation) tab-width) ?\t)
3724 ""))
3725 (delim (replace-regexp-in-string "['\"]" ""
3726 sh-here-document-word)))
3727 (insert sh-here-document-word)
3728 (or (eolp) (looking-at "[ \t]") (insert ?\s))
3729 (end-of-line 1)
3730 (while
3731 (sh-quoted-p)
3732 (end-of-line 2))
3733 (insert ?\n tabs)
3734 (save-excursion
3735 (insert ?\n tabs (replace-regexp-in-string
3736 "\\`-?[ \t]*" "" delim))))))
3737
3738 \f
3739 ;; various other commands
3740
3741 (autoload 'comint-dynamic-complete "comint"
3742 "Dynamically perform completion at point." t)
3743
3744 (autoload 'shell-dynamic-complete-command "shell"
3745 "Dynamically complete the command at point." t)
3746
3747 (autoload 'comint-dynamic-complete-filename "comint"
3748 "Dynamically complete the filename at point." t)
3749
3750 (autoload 'shell-dynamic-complete-environment-variable "shell"
3751 "Dynamically complete the environment variable at point." t)
3752
3753
3754
3755 (defun sh-beginning-of-command ()
3756 "Move point to successive beginnings of commands."
3757 (interactive)
3758 (if (re-search-backward sh-beginning-of-command nil t)
3759 (goto-char (match-beginning 2))))
3760
3761 (defun sh-end-of-command ()
3762 "Move point to successive ends of commands."
3763 (interactive)
3764 (if (re-search-forward sh-end-of-command nil t)
3765 (goto-char (match-end 1))))
3766
3767 ;; Backslashification. Stolen from make-mode.el.
3768
3769 (defun sh-backslash-region (from to delete-flag)
3770 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3771 With no argument, inserts backslashes and aligns existing backslashes.
3772 With an argument, deletes the backslashes.
3773
3774 This function does not modify the last line of the region if the region ends
3775 right at the start of the following line; it does not modify blank lines
3776 at the start of the region. So you can put the region around an entire
3777 shell command and conveniently use this command."
3778 (interactive "r\nP")
3779 (save-excursion
3780 (goto-char from)
3781 (let ((column sh-backslash-column)
3782 (endmark (make-marker)))
3783 (move-marker endmark to)
3784 ;; Compute the smallest column number past the ends of all the lines.
3785 (if sh-backslash-align
3786 (progn
3787 (if (not delete-flag)
3788 (while (< (point) to)
3789 (end-of-line)
3790 (if (= (preceding-char) ?\\)
3791 (progn (forward-char -1)
3792 (skip-chars-backward " \t")))
3793 (setq column (max column (1+ (current-column))))
3794 (forward-line 1)))
3795 ;; Adjust upward to a tab column, if that doesn't push
3796 ;; past the margin.
3797 (if (> (% column tab-width) 0)
3798 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
3799 tab-width)))
3800 (if (< adjusted (window-width))
3801 (setq column adjusted))))))
3802 ;; Don't modify blank lines at start of region.
3803 (goto-char from)
3804 (while (and (< (point) endmark) (eolp))
3805 (forward-line 1))
3806 ;; Add or remove backslashes on all the lines.
3807 (while (and (< (point) endmark)
3808 ;; Don't backslashify the last line
3809 ;; if the region ends right at the start of the next line.
3810 (save-excursion
3811 (forward-line 1)
3812 (< (point) endmark)))
3813 (if (not delete-flag)
3814 (sh-append-backslash column)
3815 (sh-delete-backslash))
3816 (forward-line 1))
3817 (move-marker endmark nil))))
3818
3819 (defun sh-append-backslash (column)
3820 (end-of-line)
3821 ;; Note that "\\\\" is needed to get one backslash.
3822 (if (= (preceding-char) ?\\)
3823 (progn (forward-char -1)
3824 (delete-horizontal-space)
3825 (indent-to column (if sh-backslash-align nil 1)))
3826 (indent-to column (if sh-backslash-align nil 1))
3827 (insert "\\")))
3828
3829 (defun sh-delete-backslash ()
3830 (end-of-line)
3831 (or (bolp)
3832 (progn
3833 (forward-char -1)
3834 (if (looking-at "\\\\")
3835 (delete-region (1+ (point))
3836 (progn (skip-chars-backward " \t") (point)))))))
3837
3838 (provide 'sh-script)
3839
3840 ;;; sh-script.el ends here