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