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