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