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