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