File:  [gforth] / gforth / gforth.el
Revision 1.65: download - view: text, annotated - select for diffs
Sat Feb 8 15:28:39 2003 UTC (21 years, 2 months ago) by dvdkhlng
Branches: MAIN
CVS tags: HEAD
Fixed `uncomment-region' (C-u C-x C-\) which didn't work, since
regexp `comment-start-skip' was buggy.

    1: ;;; gforth.el --- major mode for editing (G)Forth sources
    2: 
    3: ;; Copyright (C) 1995,1996,1997,1998,2000,2001 Free Software Foundation, Inc.
    4: 
    5: ;; This file is part of Gforth.
    6: 
    7: ;; GForth is distributed in the hope that it will be useful,
    8: ;; but WITHOUT ANY WARRANTY.  No author or distributor
    9: ;; accepts responsibility to anyone for the consequences of using it
   10: ;; or for whether it serves any particular purpose or works at all,
   11: ;; unless he says so in writing.  Refer to the GNU Emacs General Public
   12: ;; License for full details.
   13: 
   14: ;; Everyone is granted permission to copy, modify and redistribute
   15: ;; GNU Emacs, but only under the conditions described in the
   16: ;; GNU Emacs General Public License.   A copy of this license is
   17: ;; supposed to have been given to you along with Gforth so you
   18: ;; can know your rights and responsibilities.  It should be in a
   19: ;; file named COPYING.  Among other things, the copyright notice
   20: ;; and this notice must be preserved on all copies.
   21: 
   22: ;; Author: Goran Rydqvist <gorry@ida.liu.se>
   23: ;; Maintainer: David Kühling <dvdkhlng@gmx.de>
   24: ;; Created: 16 July 88 by Goran Rydqvist
   25: ;; Keywords: forth, gforth
   26: 
   27: ;; Changes by anton
   28: ;; This is a variant of forth.el that came with TILE.
   29: ;; I left most of this stuff untouched and made just a few changes for 
   30: ;; the things I use (mainly indentation and syntax tables).
   31: ;; So there is still a lot of work to do to adapt this to gforth.
   32: 
   33: ;; Changes by David
   34: ;; Added a syntax-hilighting engine, rewrote auto-indentation engine.
   35: ;; Added support for block files.
   36: ;; Tested with Emacs 19.34, 20.5, 21.1 and XEmacs 21.1
   37:  
   38: ;;-------------------------------------------------------------------
   39: ;; A Forth indentation, documentation search and interaction library
   40: ;;-------------------------------------------------------------------
   41: ;;
   42: ;; Written by Goran Rydqvist, gorry@ida.liu.se, Summer 1988
   43: ;; Started:	16 July 88
   44: ;; Version:	2.10
   45: ;; Last update:	5 December 1989 by Mikael Patel, mip@ida.liu.se
   46: ;; Last update:	25 June 1990 by Goran Rydqvist, gorry@ida.liu.se
   47: ;;
   48: ;; Documentation: See forth-mode (^HF forth-mode)
   49: ;;-------------------------------------------------------------------
   50: 
   51: ;;; Code:
   52: 
   53: ;(setq debug-on-error t)
   54: 
   55: ;; Code ripped from `version.el' for compatability with Emacs versions
   56: ;; prior to 19.23.
   57: (if (not (boundp 'emacs-major-version))
   58:     (defconst emacs-major-version
   59:       (progn (string-match "^[0-9]+" emacs-version)
   60: 	     (string-to-int (match-string 0 emacs-version)))))
   61: 
   62: (defun forth-emacs-older (major minor)
   63:   (or (< emacs-major-version major)
   64:       (and (= emacs-major-version major) (< emacs-minor-version minor))))
   65: 
   66: ;; Code ripped from `subr.el' for compatability with Emacs versions
   67: ;; prior to 20.1
   68: (eval-when-compile 
   69:   (if (forth-emacs-older 20 1)
   70:       (progn
   71: 	(defmacro when (cond &rest body)
   72: 	  "If COND yields non-nil, do BODY, else return nil."
   73: 	  (list 'if cond (cons 'progn body)))
   74: 	(defmacro unless (cond &rest body)
   75: 	  "If COND yields nil, do BODY, else return nil."
   76: 	  (cons 'if (cons cond (cons nil body)))))))
   77: 
   78: ;; `no-error' argument of require not supported in Emacs versions
   79: ;; prior to 20.4 :-(
   80: (defun forth-require (feature)
   81:   (condition-case err (require feature) (error nil)))
   82: 
   83: (require 'font-lock)
   84: 
   85: ;; define `font-lock-warning-face' in emacs-versions prior to 20.1
   86: ;; (ripped from `font-lock.el')
   87: (unless (boundp 'font-lock-warning-face)
   88:   (message "defining font-lock-warning-face")
   89:   (make-face 'font-lock-warning-face)
   90:   (defvar font-lock-warning-face 'font-lock-warning-face)
   91:   (set-face-foreground font-lock-warning-face "red")
   92:   (make-face-bold font-lock-warning-face))
   93: 
   94: ;; define `font-lock-constant-face' in XEmacs (just copy
   95: ;; `font-lock-preprocessor-face')
   96: (unless (boundp 'font-lock-constant-face)
   97:   (copy-face font-lock-preprocessor-face 'font-lock-constant-face))
   98: 
   99: 
  100: ;; define `regexp-opt' in emacs versions prior to 20.1 
  101: ;; (this implementation is extremely inefficient, though)
  102: (eval-and-compile (forth-require 'regexp-opt))
  103: (unless (memq 'regexp-opt features)
  104:   (message (concat 
  105: 	    "Warning: your Emacs version doesn't support `regexp-opt'. "
  106:             "Hilighting will be slow."))
  107:   (defun regexp-opt (STRINGS &optional PAREN)
  108:     (let ((open (if PAREN "\\(" "")) (close (if PAREN "\\)" "")))
  109:       (concat open (mapconcat 'regexp-quote STRINGS "\\|") close)))
  110:   (defun regexp-opt-depth (re)
  111:     (if (string= (substring re 0 2) "\\(") 1 0)))
  112: 
  113: ; todo:
  114: ;
  115: 
  116: ; Wörter ordentlich hilighten, die nicht auf Whitespace beginnen ( ..)IF
  117: ; -- mit aktueller Konzeption nicht möglich??
  118: ;
  119: ; Konfiguration über customization groups
  120: ;
  121: ; Bereich nur auf Wortanfang/ende ausweiten, wenn Anfang bzw Ende in einem 
  122: ; Wort liegen (?) -- speed!
  123: ;
  124: ; 'forth-word' property muss eindeutig sein!
  125: ;
  126: ; Forth-Menu 
  127: ;
  128: ; Interface zu GForth Prozessen (Patches von Michael Scholz)
  129: ;
  130: ; Byte-compile-Code rausschmeißen, Compilieren im Makefile über Emacs
  131: ; batch-Modus
  132: ;
  133: ; forth-help Kram rausschmeißen
  134: ;
  135: ; XEmacs Kompatibilität? imenu/speedbar -> fume?
  136: ; 
  137: ; Folding neuschreiben (neue Parser-Informationen benutzen)
  138: 
  139: ;;; Motion-hooking (dk)
  140: ;;;
  141: (defun forth-idle-function ()
  142:   "Function that is called when Emacs is idle to detect cursor motion
  143: in forth-block-mode buffers (which is mainly used for screen number
  144: display in).  Currently ignores forth-mode buffers but that may change
  145: in the future."
  146:   (if (eq major-mode 'forth-block-mode)
  147:       (forth-check-motion)))
  148: 
  149: (defvar forth-idle-function-timer nil 
  150:   "Timer that runs `forth-idle-function' or nil if no timer installed.")
  151: 
  152: (defun forth-install-motion-hook ()
  153:   "Install the motion-hooking mechanism.  Currently uses idle timers
  154: but might be transparently changed in the future."
  155:   (unless forth-idle-function-timer
  156:     ;; install idle function only once (first time forth-mode is used)
  157:     (setq forth-idle-function-timer 
  158: 	  (run-with-idle-timer .05 t 'forth-idle-function))))
  159: 
  160: (defvar forth-was-point nil)
  161: 
  162: (defun forth-check-motion ()
  163:   "Run `forth-motion-hooks', if `point' changed since last call.  This
  164: used to be called via `post-command-hook' but uses idle timers now as
  165: users complaint about lagging performance."
  166:   (when (or (eq forth-was-point nil) (/= forth-was-point (point)))
  167:     (setq forth-was-point (point))
  168:     (run-hooks 'forth-motion-hooks)))
  169: 
  170: 
  171: ;;; Hilighting and indentation engine (dk)
  172: ;;;
  173: (defvar forth-disable-parser nil
  174:   "*Non-nil means to disable on-the-fly parsing of Forth-code.
  175: 
  176: This will disable hilighting of forth-mode buffers and will decrease
  177: the smartness of the indentation engine. Only set it to non-nil, if
  178: your computer is very slow. To disable hilighting, set
  179: `forth-hilight-level' to zero.")
  180: 
  181: (defvar forth-jit-parser nil
  182:   "*Non-nil means to parse Forth-code just-in-time.
  183: 
  184: This eliminates the need for initially parsing forth-mode buffers and
  185: thus speeds up loading of Forth files. That feature is only available
  186: in Emacs21 (and newer versions).")
  187: 
  188: (defvar forth-words nil 
  189:   "List of words for hilighting and recognition of parsed text areas. 
  190: 
  191: Hilighting of object-oriented Forth code is achieved, by appending either
  192: `forth-objects-words' or `forth-oof-words' to the list, depending on the values of `forth-use-objects' or `forth-use-oof'.
  193: 
  194: After `forth-words' changed, `forth-compile-words' must be called to
  195: make the changes take effect.
  196: 
  197: Each item of `forth-words' has the form 
  198:    (MATCHER TYPE HILIGHT . &optional PARSED-TEXT ...)
  199: 
  200: MATCHER is either a list of strings to match, or a REGEXP.
  201:    If it's a REGEXP, it should not be surrounded by '\\<' or '\\>', since 
  202:    that'll be done automatically by the search routines.
  203: 
  204: TYPE should be one of 'definiton-starter', 'definition-ender', 'compile-only',
  205:    'immediate' or 'non-immediate'. Those information are required to determine
  206:    whether a word actually parses (and whether that parsed text needs to be
  207:    hilighted).
  208: 
  209: HILIGHT is a cons cell of the form (FACE . MINIMUM-LEVEL)
  210:    Where MINIMUM-LEVEL specifies the minimum value of `forth-hilight-level',
  211:    that's required for matching text to be hilighted.
  212: 
  213: PARSED-TEXT specifies whether and how a word parses following text. You can
  214:    specify as many subsequent PARSED-TEXT as you wish, but that shouldn't be
  215:    necessary very often. It has the following form:
  216:    (DELIM-REGEXP SKIP-LEADING-FLAG PARSED-TYPE HILIGHT)
  217: 
  218: DELIM-REGEXP is a regular expression that should match strings of length 1,
  219:    which are delimiters for the parsed text.
  220: 
  221: A non-nil value for PARSE-LEADING-FLAG means, that leading delimiter strings
  222:    before parsed text should be skipped. This is the parsing behaviour of the
  223:    Forth word WORD. Set it to t for name-parsing words, nil for comments and
  224:    strings.
  225: 
  226: PARSED-TYPE specifies what kind of text is parsed. It should be on of 'name',
  227:    'string' or 'comment'.")
  228: (setq forth-words
  229:       '(
  230: 	(("[") definition-ender (font-lock-keyword-face . 1))
  231: 	(("]" "]l") definition-starter (font-lock-keyword-face . 1))
  232: 	((":") definition-starter (font-lock-keyword-face . 1)
  233: 	 "[ \t\n]" t name (font-lock-function-name-face . 3))
  234: 	(("immediate" "compile-only" "restrict")
  235: 	 immediate (font-lock-keyword-face . 1))
  236: 	(("does>") compile-only (font-lock-keyword-face . 1))
  237: 	((":noname") definition-starter (font-lock-keyword-face . 1))
  238: 	((";" ";code") definition-ender (font-lock-keyword-face . 1))
  239: 	(("include" "require" "needs" "use") 
  240: 	 non-immediate (font-lock-keyword-face . 1) 
  241: 	 "[\n\t ]" t string (font-lock-string-face . 1))
  242: 	(("included" "required" "thru" "load")
  243: 	 non-immediate (font-lock-keyword-face . 1))
  244: 	(("[char]") compile-only (font-lock-keyword-face . 1)
  245: 	 "[ \t\n]" t string (font-lock-string-face . 1))
  246: 	(("char") non-immediate (font-lock-keyword-face . 1)
  247: 	 "[ \t\n]" t string (font-lock-string-face . 1))
  248: 	(("s\"" "c\"") immediate (font-lock-string-face . 1)
  249: 	 "[\"\n]" nil string (font-lock-string-face . 1))
  250: 	((".\"") compile-only (font-lock-string-face . 1)
  251: 	 "[\"\n]" nil string (font-lock-string-face . 1))
  252: 	(("abort\"") compile-only (font-lock-keyword-face . 1)
  253: 	 "[\"\n]" nil string (font-lock-string-face . 1))
  254: 	(("{") compile-only (font-lock-variable-name-face . 1)
  255: 	 "[\n}]" nil name (font-lock-variable-name-face . 1))
  256: 	((".(" "(") immediate (font-lock-comment-face . 1)
  257: 	  ")" nil comment (font-lock-comment-face . 1))
  258: 	(("\\" "\\G") immediate (font-lock-comment-face . 1)
  259: 	 "[\n]" nil comment (font-lock-comment-face . 1))
  260: 	  
  261: 	(("[if]" "[?do]" "[do]" "[for]" "[begin]" 
  262: 	  "[endif]" "[then]" "[loop]" "[+loop]" "[next]" "[until]" "[repeat]"
  263: 	  "[again]" "[while]" "[else]")
  264: 	 immediate (font-lock-keyword-face . 2))
  265: 	(("[ifdef]" "[ifundef]") immediate (font-lock-keyword-face . 2)
  266: 	 "[ \t\n]" t name (font-lock-function-name-face . 3))
  267: 	(("if" "begin" "ahead" "do" "?do" "+do" "u+do" "-do" "u-do" "for" 
  268: 	  "case" "of" "?dup-if" "?dup-0=-if" "then" "endif" "until"
  269: 	  "repeat" "again" "leave" "?leave"
  270: 	  "loop" "+loop" "-loop" "next" "endcase" "endof" "else" "while" "try"
  271: 	  "recover" "endtry" "assert(" "assert0(" "assert1(" "assert2(" 
  272: 	  "assert3(" ")" "<interpretation" "<compilation" "interpretation>" 
  273: 	  "compilation>")
  274: 	 compile-only (font-lock-keyword-face . 2))
  275: 
  276: 	(("true" "false" "c/l" "bl" "cell" "pi" "w/o" "r/o" "r/w") 
  277: 	 non-immediate (font-lock-constant-face . 2))
  278: 	(("~~" "break:" "dbg") compile-only (font-lock-warning-face . 2))
  279: 	(("break\"") compile-only (font-lock-warning-face . 1)
  280: 	 "[\"\n]" nil string (font-lock-string-face . 1))
  281: 	(("postpone" "[is]" "defers" "[']" "[compile]") 
  282: 	 compile-only (font-lock-keyword-face . 2)
  283: 	 "[ \t\n]" t name (font-lock-function-name-face . 3))
  284: 	(("is" "what's") immediate (font-lock-keyword-face . 2)
  285: 	 "[ \t\n]" t name (font-lock-function-name-face . 3))
  286: 	(("<is>" "'" "see") non-immediate (font-lock-keyword-face . 2)
  287: 	 "[ \t\n]" t name (font-lock-function-name-face . 3))
  288: 	(("[to]") compile-only (font-lock-keyword-face . 2)
  289: 	 "[ \t\n]" t name (font-lock-variable-name-face . 3))
  290: 	(("to") immediate (font-lock-keyword-face . 2)
  291: 	 "[ \t\n]" t name (font-lock-variable-name-face . 3))
  292: 	(("<to>") non-immediate (font-lock-keyword-face . 2)
  293: 	 "[ \t\n]" t name (font-lock-variable-name-face . 3))
  294: 
  295: 	(("create" "variable" "constant" "2variable" "2constant" "fvariable"
  296: 	  "fconstant" "value" "field" "user" "vocabulary" 
  297: 	  "create-interpret/compile")
  298: 	 non-immediate (font-lock-type-face . 2)
  299: 	 "[ \t\n]" t name (font-lock-variable-name-face . 3))
  300: 	("\\S-+%" non-immediate (font-lock-type-face . 2))
  301: 	(("defer" "alias" "create-interpret/compile:") 
  302: 	 non-immediate (font-lock-type-face . 1)
  303: 	 "[ \t\n]" t name (font-lock-function-name-face . 3))
  304: 	(("end-struct") non-immediate (font-lock-keyword-face . 2)
  305: 	 "[ \t\n]" t name (font-lock-type-face . 3))
  306: 	(("struct") non-immediate (font-lock-keyword-face . 2))
  307: 	("-?[0-9]+\\(\\.[0-9]*e\\(-?[0-9]+\\)?\\|\\.?[0-9a-f]*\\)" 
  308: 	 immediate (font-lock-constant-face . 3))
  309: 	))
  310: 
  311: (defvar forth-use-objects nil 
  312:   "*Non-nil makes forth-mode also hilight words from the \"Objects\" package.")
  313: (defvar forth-objects-words
  314:   '(((":m") definition-starter (font-lock-keyword-face . 1)
  315:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  316:     (("m:") definition-starter (font-lock-keyword-face . 1))
  317:     ((";m") definition-ender (font-lock-keyword-face . 1))
  318:     (("[current]" "[parent]") compile-only (font-lock-keyword-face . 1)
  319:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  320:     (("current" "overrides") non-immediate (font-lock-keyword-face . 2)
  321:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  322:     (("[to-inst]") compile-only (font-lock-keyword-face . 2)
  323:      "[ \t\n]" t name (font-lock-variable-name-face . 3))
  324:     (("[bind]") compile-only (font-lock-keyword-face . 2)
  325:      "[ \t\n]" t name (font-lock-type-face . 3)
  326:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  327:     (("bind") non-immediate (font-lock-keyword-face . 2)
  328:      "[ \t\n]" t name (font-lock-type-face . 3)
  329:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  330:     (("inst-var" "inst-value") non-immediate (font-lock-type-face . 2)
  331:      "[ \t\n]" t name (font-lock-variable-name-face . 3))
  332:     (("method" "selector")
  333:      non-immediate (font-lock-type-face . 1)
  334:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  335:     (("end-class" "end-interface")
  336:      non-immediate (font-lock-keyword-face . 2)
  337:      "[ \t\n]" t name (font-lock-type-face . 3))
  338:     (("public" "protected" "class" "exitm" "implementation" "interface"
  339:       "methods" "end-methods" "this") 
  340:      non-immediate (font-lock-keyword-face . 2))
  341:     (("object") non-immediate (font-lock-type-face . 2)))
  342:   "Hilighting description for words of the \"Objects\" package")
  343: 
  344: 
  345: (defvar forth-use-oof nil 
  346:   "*Non-nil makes forth-mode also hilight words from the \"OOF\" package.")
  347: (defvar forth-oof-words 
  348:   '((("class") non-immediate (font-lock-keyword-face . 2)
  349:      "[ \t\n]" t name (font-lock-type-face . 3))
  350:     (("var") non-immediate (font-lock-type-face . 2)
  351:      "[ \t\n]" t name (font-lock-variable-name-face . 3))
  352:     (("method" "early") non-immediate (font-lock-type-face . 2)
  353:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  354:     (("::" "super" "bind" "bound" "link") 
  355:      immediate (font-lock-keyword-face . 2)
  356:      "[ \t\n]" t name (font-lock-function-name-face . 3))
  357:     (("ptr" "asptr" "[]") 
  358:      immediate (font-lock-keyword-face . 2)
  359:      "[ \t\n]" t name (font-lock-variable-name-face . 3))
  360:     (("class;" "how:" "self" "new" "new[]" "definitions" "class?" "with"
  361:       "endwith")
  362:      non-immediate (font-lock-keyword-face . 2))
  363:     (("object") non-immediate (font-lock-type-face . 2)))
  364:   "Hilighting description for words of the \"OOF\" package")
  365: 
  366: (defvar forth-local-words nil 
  367:   "List of Forth words to prepend to `forth-words'. Should be set by a 
  368:  forth source, using a local variables list at the end of the file 
  369:  (\"Local Variables: ... forth-local-words: ... End:\" construct).") 
  370: 
  371: (defvar forth-custom-words nil
  372:   "List of Forth words to prepend to `forth-words'. Should be set in your
  373:  .emacs.")
  374: 
  375: (defvar forth-hilight-level 3 "*Level of hilighting of Forth code.")
  376: 
  377: (defvar forth-compiled-words nil "Compiled representation of `forth-words'.")
  378: 
  379: (defvar forth-indent-words nil 
  380:   "List of words that have indentation behaviour.
  381: Each element of `forth-indent-words' should have the form
  382:    (MATCHER INDENT1 INDENT2 &optional TYPE) 
  383:   
  384: MATCHER is either a list of strings to match, or a REGEXP.
  385:    If it's a REGEXP, it should not be surrounded by `\\<` or `\\>`, since 
  386:    that'll be done automatically by the search routines.
  387: 
  388: TYPE might be omitted. If it's specified, the only allowed value is 
  389:    currently the symbol `non-immediate', meaning that the word will not 
  390:    have any effect on indentation inside definitions. (:NONAME is a good 
  391:    example for this kind of word).
  392: 
  393: INDENT1 specifies how to indent a word that's located at the beginning
  394:    of a line, following any number of whitespaces.
  395: 
  396: INDENT2 specifies how to indent words that are not located at the
  397:    beginning of a line.
  398: 
  399: INDENT1 and INDENT2 are indentation specifications of the form
  400:    (SELF-INDENT . NEXT-INDENT), where SELF-INDENT is a numerical value, 
  401:    specifying how the matching line and all following lines are to be 
  402:    indented, relative to previous lines. NEXT-INDENT specifies how to indent 
  403:    following lines, relative to the matching line.
  404:   
  405:    Even values of SELF-INDENT and NEXT-INDENT correspond to multiples of
  406:    `forth-indent-level'. Odd values get an additional 
  407:    `forth-minor-indent-level' added/substracted. Eg a value of -2 indents
  408:    1 * forth-indent-level  to the left, wheras 3 indents 
  409:    1 * forth-indent-level + forth-minor-indent-level  columns to the right.")
  410: 
  411: (setq forth-indent-words
  412:       '((("if" "begin" "do" "?do" "+do" "-do" "u+do"
  413: 	  "u-do" "?dup-if" "?dup-0=-if" "case" "of" "try" 
  414: 	  "[if]" "[ifdef]" "[ifundef]" "[begin]" "[for]" "[do]" "[?do]")
  415: 	 (0 . 2) (0 . 2))
  416: 	((":" ":noname" "code" "struct" "m:" ":m" "class" "interface")
  417: 	 (0 . 2) (0 . 2) non-immediate)
  418: 	("\\S-+%$" (0 . 2) (0 . 0) non-immediate)
  419: 	((";" ";m") (-2 . 0) (0 . -2))
  420: 	(("again" "then" "endif" "endtry" "endcase" "endof" 
  421: 	  "[then]" "[endif]" "[loop]" "[+loop]" "[next]" 
  422: 	  "[until]" "[again]" "loop")
  423: 	 (-2 . 0) (0 . -2))
  424: 	(("end-code" "end-class" "end-interface" "end-class-noname" 
  425: 	  "end-interface-noname" "end-struct" "class;")
  426: 	 (-2 . 0) (0 . -2) non-immediate)
  427: 	(("protected" "public" "how:") (-1 . 1) (0 . 0) non-immediate)
  428: 	(("+loop" "-loop" "until") (-2 . 0) (-2 . 0))
  429: 	(("else" "recover" "[else]") (-2 . 2) (0 . 0))
  430: 	(("does>") (-1 . 1) (0 . 0))
  431: 	(("while" "[while]") (-2 . 4) (0 . 2))
  432: 	(("repeat" "[repeat]") (-4 . 0) (0 . -4))
  433: 	(("\\g") (-2 . 2) (0 . 0))))
  434: 
  435: (defvar forth-local-indent-words nil 
  436:   "List of Forth words to prepend to `forth-indent-words', when a forth-mode
  437: buffer is created. Should be set by a Forth source, using a local variables 
  438: list at the end of the file (\"Local Variables: ... forth-local-words: ... 
  439: End:\" construct).")
  440: 
  441: (defvar forth-custom-indent-words nil
  442:   "List of Forth words to prepend to `forth-indent-words'. Should be set in
  443:  your .emacs.")
  444: 
  445: (defvar forth-indent-level 4
  446:   "*Indentation of Forth statements.")
  447: (defvar forth-minor-indent-level 2
  448:   "*Minor indentation of Forth statements.")
  449: (defvar forth-compiled-indent-words nil)
  450: 
  451: ;(setq debug-on-error t)
  452: 
  453: ;; Filter list by predicate. This is a somewhat standard function for 
  454: ;; functional programming languages. So why isn't it already implemented 
  455: ;; in Lisp??
  456: (defun forth-filter (predicate list)
  457:   (let ((filtered nil))
  458:     (mapcar (lambda (item)
  459: 	      (when (funcall predicate item)
  460: 		(if filtered
  461: 		    (nconc filtered (list item))
  462: 		  (setq filtered (cons item nil))))
  463: 	      nil) list)
  464:     filtered))
  465: 
  466: ;; Helper function for `forth-compile-word': return whether word has to be
  467: ;; added to the compiled word list, for syntactic parsing and hilighting.
  468: (defun forth-words-filter (word)
  469:   (let* ((hilight (nth 2 word))
  470: 	 (level (cdr hilight))
  471: 	 (parsing-flag (nth 3 word)))
  472:     (or parsing-flag 
  473: 	(<= level forth-hilight-level))))
  474: 
  475: ;; Helper function for `forth-compile-word': translate one entry from 
  476: ;; `forth-words' into the form  (regexp regexp-depth word-description)
  477: (defun forth-compile-words-mapper (word)
  478:   ;; warning: we cannot rely on regexp-opt's PAREN argument, since
  479:   ;; XEmacs will use shy parens by default :-(
  480:   (let* ((matcher (car word))
  481: 	 (regexp 
  482: 	  (concat "\\(" (cond ((stringp matcher) matcher)
  483: 			      ((listp matcher) (regexp-opt matcher))
  484: 			      (t (error "Invalid matcher `%s'")))
  485: 		  "\\)"))
  486: 	 (depth (regexp-opt-depth regexp))
  487: 	 (description (cdr word)))
  488:     (list regexp depth description)))
  489: 
  490: ;; Read `words' and create a compiled representation suitable for efficient
  491: ;; parsing of the form  
  492: ;; (regexp (subexp-count word-description) (subexp-count2 word-description2)
  493: ;;  ...)
  494: (defun forth-compile-wordlist (words)
  495:   (let* ((mapped (mapcar 'forth-compile-words-mapper words))
  496: 	 (regexp (concat "\\<\\(" 
  497: 			 (mapconcat 'car mapped "\\|")
  498: 			 "\\)\\>"))
  499: 	 (sub-count 2)
  500: 	 (sub-list (mapcar 
  501: 		    (lambda (i) 
  502: 		      (let ((sub (cons sub-count (nth 2 i))))
  503: 			(setq sub-count (+ sub-count (nth 1 i)))
  504: 			sub 
  505: 			)) 
  506: 		    mapped)))
  507:     (let ((result (cons regexp sub-list)))
  508:       (byte-compile 'result)
  509:       result)))
  510: 
  511: (defun forth-compile-words ()
  512:   "Compile the the words from `forth-words' and `forth-indent-words' into
  513:  the format that's later used for doing the actual hilighting/indentation.
  514:  Store the resulting compiled wordlists in `forth-compiled-words' and 
  515: `forth-compiled-indent-words', respective"
  516:   (setq forth-compiled-words 
  517: 	(forth-compile-wordlist 
  518: 	 (forth-filter 'forth-words-filter forth-words)))
  519:   (setq forth-compiled-indent-words 
  520: 	(forth-compile-wordlist forth-indent-words)))
  521: 
  522: (defun forth-hack-local-variables ()
  523:   "Parse and bind local variables, set in the contents of the current 
  524:  forth-mode buffer. Prepend `forth-local-words' to `forth-words' and 
  525:  `forth-local-indent-words' to `forth-indent-words'."
  526:   (hack-local-variables)
  527:   (setq forth-words (append forth-local-words forth-words))
  528:   (setq forth-indent-words (append forth-local-indent-words 
  529: 				   forth-indent-words)))
  530: 
  531: (defun forth-customize-words ()
  532:   "Add the words from `forth-custom-words' and `forth-custom-indent-words'
  533:  to `forth-words' and `forth-indent-words', respective. Add 
  534:  `forth-objects-words' and/or `forth-oof-words' to `forth-words', if
  535:  `forth-use-objects' and/or `forth-use-oof', respective is set."
  536:   (setq forth-words (append forth-custom-words forth-words
  537: 			    (if forth-use-oof forth-oof-words nil)
  538: 			    (if forth-use-objects forth-objects-words nil)))
  539:   (setq forth-indent-words (append 
  540: 			    forth-custom-indent-words forth-indent-words)))
  541: 
  542: 
  543: 
  544: ;; get location of first character of previous forth word that's got 
  545: ;; properties
  546: (defun forth-previous-start (pos)
  547:   (let* ((word (get-text-property pos 'forth-word))
  548: 	 (prev (previous-single-property-change 
  549: 		(min (point-max) (1+ pos)) 'forth-word 
  550: 		(current-buffer) (point-min))))
  551:     (if (or (= (point-min) prev) word) prev
  552:       (if (get-text-property (1- prev) 'forth-word)
  553: 	  (previous-single-property-change 
  554: 	   prev 'forth-word (current-buffer) (point-min))
  555: 	(point-min)))))
  556: 
  557: ;; Get location of the last character of the current/next forth word that's
  558: ;; got properties, text that's parsed by the word is considered as parts of 
  559: ;; the word.
  560: (defun forth-next-end (pos)
  561:   (let* ((word (get-text-property pos 'forth-word))
  562: 	 (next (next-single-property-change pos 'forth-word 
  563: 					    (current-buffer) (point-max))))
  564:     (if word next
  565:       (if (get-text-property next 'forth-word)
  566: 	  (next-single-property-change 
  567: 	   next 'forth-word (current-buffer) (point-max))
  568: 	(point-max)))))
  569: 
  570: (defun forth-next-whitespace (pos)
  571:   (save-excursion
  572:     (goto-char pos)
  573:     (skip-syntax-forward "-" (point-max))
  574:     (point)))
  575: (defun forth-previous-word (pos)
  576:   (save-excursion
  577:     (goto-char pos)
  578:     (re-search-backward "\\<" pos (point-min) 1)
  579:     (point)))
  580: 
  581: ;; Delete all properties, used by Forth mode, from `from' to `to'.
  582: (defun forth-delete-properties (from to)
  583:   (remove-text-properties 
  584:    from to '(face nil fontified nil 
  585: 		  forth-parsed nil forth-word nil forth-state nil)))
  586: 
  587: ;; Get the index of the branch of the most recently evaluated regular 
  588: ;; expression that matched. (used for identifying branches "a\\|b\\|c...")
  589: (defun forth-get-regexp-branch ()
  590:   (let ((count 2))
  591:     (while (not (condition-case err (match-beginning count)
  592: 		  (args-out-of-range t)))  ; XEmacs requires error handling
  593:       (setq count (1+ count)))
  594:     count))
  595: 
  596: ;; seek to next forth-word and return its "word-description"
  597: (defun forth-next-known-forth-word (to)
  598:   (if (<= (point) to)
  599:       (progn
  600: 	(let* ((regexp (car forth-compiled-words))
  601: 	       (pos (re-search-forward regexp to t)))
  602: 	  (if pos (let ((branch (forth-get-regexp-branch))
  603: 			(descr (cdr forth-compiled-words)))
  604: 		    (goto-char (match-beginning 0))
  605: 		    (cdr (assoc branch descr)))
  606: 	    'nil)))
  607:     nil))
  608: 
  609: ;; Set properties of forth word at `point', eventually parsing subsequent 
  610: ;; words, and parsing all whitespaces. Set point to delimiter after word.
  611: ;; The word, including it's parsed text gets the `forth-word' property, whose 
  612: ;; value is unique, and may be used for getting the word's start/end 
  613: ;; positions.
  614: (defun forth-set-word-properties (state data)
  615:   (let* ((start (point))
  616: 	 (end (progn (re-search-forward "[ \t]\\|$" (point-max) 1)
  617: 		     (point)))
  618: 	 (type (car data))
  619: 	 (hilight (nth 1 data))
  620: 	 (bad-word (and (not state) (eq type 'compile-only)))
  621: 	 (hlface (if bad-word font-lock-warning-face
  622: 		   (if (<= (cdr hilight) forth-hilight-level)
  623: 		       (car hilight) nil))))
  624:     (when hlface (put-text-property start end 'face hlface))
  625:     ;; if word parses in current state, process parsed range of text
  626:     (when (or (not state) (eq type 'compile-only) (eq type 'immediate))
  627:       (let ((parse-data (nthcdr 2 data)))
  628: 	(while parse-data
  629: 	  (let ((delim (nth 0 parse-data))
  630: 		(skip-leading (nth 1 parse-data))
  631: 		(parse-type (nth 2 parse-data))
  632: 		(parsed-hilight (nth 3 parse-data))
  633: 		(parse-start (point))
  634: 		(parse-end))
  635: 	    (when skip-leading
  636: 	      (while (and (looking-at delim) (> (match-end 0) (point))
  637: 			  (not (looking-at "\n")))
  638: 		(forward-char)))
  639: 	    (re-search-forward delim (point-max) 1)
  640: 	    (setq parse-end (point))
  641: 	    (forth-delete-properties end parse-end)
  642: 	    (when (<= (cdr parsed-hilight) forth-hilight-level)
  643: 	      (put-text-property 
  644: 	       parse-start parse-end 'face (car parsed-hilight)))
  645: 	    (put-text-property 
  646: 	     parse-start parse-end 'forth-parsed parse-type)
  647: 	    (setq end parse-end)
  648: 	    (setq parse-data (nthcdr 4 parse-data))))))
  649:     (put-text-property start end 'forth-word start)))
  650: 
  651: ;; Search for known Forth words in the range `from' to `to', using 
  652: ;; `forth-next-known-forth-word' and set their properties via 
  653: ;; `forth-set-word-properties'.
  654: (defun forth-update-properties (from to &optional loudly)
  655:   (save-excursion
  656:     (let ((msg-count 0) (state) (word-descr) (last-location))
  657:       (goto-char (forth-previous-word (forth-previous-start 
  658: 				       (max (point-min) (1- from)))))
  659:       (setq to (forth-next-end (min (point-max) (1+ to))))
  660:       ;; `to' must be on a space delimiter, if a parsing word was changed
  661:       (setq to (forth-next-whitespace to))
  662:       (setq state (get-text-property (point) 'forth-state))
  663:       (setq last-location (point))
  664:       (forth-delete-properties (point) to)
  665:       (put-text-property (point) to 'fontified t)
  666:       ;; hilight loop...
  667:       (while (setq word-descr (forth-next-known-forth-word to))
  668: 	(when loudly
  669: 	  (when (equal 0 (% msg-count 100))
  670: 	    (message "Parsing Forth code...%s"
  671: 		     (make-string (/ msg-count 100) ?.)))
  672: 	  (setq msg-count (1+ msg-count)))
  673: 	(forth-set-word-properties state word-descr)
  674: 	(when state (put-text-property last-location (point) 'forth-state t))
  675: 	(let ((type (car word-descr)))
  676: 	  (if (eq type 'definition-starter) (setq state t))
  677: 	  (if (eq type 'definition-ender) (setq state nil))
  678: 	  (setq last-location (point))))
  679:       ;; update state property up to `to'
  680:       (if (and state (< (point) to))
  681: 	  (put-text-property last-location to 'forth-state t))
  682:       ;; extend search if following state properties differ from current state
  683:       (if (< to (point-max))
  684: 	  (if (not (equal state (get-text-property (1+ to) 'forth-state)))
  685: 	      (let ((extend-to (next-single-property-change 
  686: 				to 'forth-state (current-buffer) (point-max))))
  687: 		(forth-update-properties to extend-to))
  688: 	    ))
  689:       )))
  690: 
  691: ;; save-buffer-state borrowed from `font-lock.el'
  692: (eval-when-compile 
  693:   (defmacro forth-save-buffer-state (varlist &rest body)
  694:     "Bind variables according to VARLIST and eval BODY restoring buffer state."
  695:     (` (let* ((,@ (append varlist
  696: 		   '((modified (buffer-modified-p)) (buffer-undo-list t)
  697: 		     (inhibit-read-only t) (inhibit-point-motion-hooks t)
  698: 		     before-change-functions after-change-functions
  699: 		     deactivate-mark buffer-file-name buffer-file-truename))))
  700: 	 (,@ body)
  701: 	 (when (and (not modified) (buffer-modified-p))
  702: 	   (set-buffer-modified-p nil))))))
  703: 
  704: ;; Function that is added to the `change-functions' hook. Calls 
  705: ;; `forth-update-properties' and keeps care of disabling undo information
  706: ;; and stuff like that.
  707: (defun forth-change-function (from to len &optional loudly)
  708:   (save-match-data
  709:     (forth-save-buffer-state 
  710:      () 
  711:      (unless forth-disable-parser (forth-update-properties from to loudly))
  712:      (forth-update-warn-long-lines))))
  713: 
  714: (defun forth-fontification-function (from)
  715:   "Function to be called from `fontification-functions' of Emacs 21."
  716:   (save-match-data
  717:     (forth-save-buffer-state
  718:      ((to (min (point-max) (+ from 100))))
  719:      (unless (or forth-disable-parser (not forth-jit-parser)
  720: 		 (get-text-property from 'fontified))
  721:        (forth-update-properties from to)))))
  722: 
  723: (eval-when-compile
  724:   (byte-compile 'forth-set-word-properties)
  725:   (byte-compile 'forth-next-known-forth-word)
  726:   (byte-compile 'forth-update-properties)
  727:   (byte-compile 'forth-delete-properties)
  728:   (byte-compile 'forth-get-regexp-branch)) 
  729: 
  730: ;;; imenu support
  731: ;;;
  732: (defvar forth-defining-words 
  733:   '("VARIABLE" "CONSTANT" "2VARIABLE" "2CONSTANT" "FVARIABLE" "FCONSTANT"
  734:    "USER" "VALUE" "field" "end-struct" "VOCABULARY" "CREATE" ":" "CODE"
  735:    "DEFER" "ALIAS")
  736:   "List of words, that define the following word.
  737: Used for imenu index generation.")
  738: 
  739: (defvar forth-defining-words-regexp nil 
  740:   "Regexp that's generated for matching `forth-defining-words'")
  741:  
  742: (defun forth-next-definition-starter ()
  743:   (progn
  744:     (let* ((pos (re-search-forward forth-defining-words-regexp (point-max) t)))
  745:       (if pos
  746: 	  (if (or (text-property-not-all (match-beginning 0) (match-end 0) 
  747: 					 'forth-parsed nil)
  748: 		  (text-property-not-all (match-beginning 0) (match-end 0)
  749: 					 'forth-state nil)) 
  750: 	      (forth-next-definition-starter)
  751: 	    t)
  752: 	nil))))
  753: 
  754: (defun forth-create-index ()
  755:   (let* ((forth-defining-words-regexp 
  756: 	  (concat "\\<\\(" (regexp-opt forth-defining-words) "\\)\\>"))
  757: 	 (index nil))
  758:     (goto-char (point-min))
  759:     (while (forth-next-definition-starter)
  760:       (if (looking-at "[ \t]*\\([^ \t\n]+\\)")
  761: 	  (setq index (cons (cons (match-string 1) (point)) index))))
  762:     index))
  763: 
  764: ;; top-level require is executed at byte-compile and load time
  765: (eval-and-compile (forth-require 'speedbar))
  766: 
  767: ;; this code is executed at load-time only
  768: (when (memq 'speedbar features)
  769:   (speedbar-add-supported-extension ".fs")
  770:   (speedbar-add-supported-extension ".fb"))
  771: 
  772: ;; (require 'profile)
  773: ;; (setq profile-functions-list '(forth-set-word-properties forth-next-known-forth-word forth-update-properties forth-delete-properties forth-get-regexp-branch))
  774: 
  775: ;;; Indentation
  776: ;;;
  777: 
  778: ;; Return, whether `pos' is the first forth word on its line
  779: (defun forth-first-word-on-line-p (pos)
  780:   (save-excursion
  781:     (beginning-of-line)
  782:     (skip-chars-forward " \t")
  783:     (= pos (point))))
  784: 
  785: ;; Return indentation data (SELF-INDENT . NEXT-INDENT) of next known 
  786: ;; indentation word, or nil if there is no word up to `to'. 
  787: ;; Position `point' at location just after found word, or at `to'. Parsed 
  788: ;; ranges of text will not be taken into consideration!
  789: (defun forth-next-known-indent-word (to)
  790:   (if (<= (point) to)
  791:       (progn
  792: 	(let* ((regexp (car forth-compiled-indent-words))
  793: 	       (pos (re-search-forward regexp to t)))
  794: 	  (if pos
  795: 	      (let* ((start (match-beginning 0))
  796: 		     (end (match-end 0))
  797: 		     (branch (forth-get-regexp-branch))
  798: 		     (descr (cdr forth-compiled-indent-words))
  799: 		     (indent (cdr (assoc branch descr)))
  800: 		     (type (nth 2 indent)))
  801: 		;; skip words that are parsed (strings/comments) and 
  802: 		;; non-immediate words inside definitions
  803: 		(if (or (text-property-not-all start end 'forth-parsed nil)
  804: 			(and (eq type 'non-immediate) 
  805: 			     (text-property-not-all start end 
  806: 						    'forth-state nil)))
  807: 		    (forth-next-known-indent-word to)
  808: 		  (if (forth-first-word-on-line-p (match-beginning 0))
  809: 		      (nth 0 indent) (nth 1 indent))))
  810: 	    nil)))
  811:     nil))
  812:   
  813: ;; Translate indentation value `indent' to indentation column. Multiples of
  814: ;; 2 correspond to multiples of `forth-indent-level'. Odd numbers get an
  815: ;; additional `forth-minor-indent-level' added (or substracted).
  816: (defun forth-convert-to-column (indent)
  817:   (let* ((sign (if (< indent 0) -1 1))
  818: 	 (value (abs indent))
  819: 	 (major (* (/ value 2) forth-indent-level))
  820: 	 (minor (* (% value 2) forth-minor-indent-level)))
  821:     (* sign (+ major minor))))
  822: 
  823: ;; Return the column increment, that the current line of forth code does to
  824: ;; the current or following lines. `which' specifies which indentation values
  825: ;; to use. 0 means the indentation of following lines relative to current 
  826: ;; line, 1 means the indentation of the current line relative to the previous 
  827: ;; line. Return `nil', if there are no indentation words on the current line.
  828: (defun forth-get-column-incr (which)
  829:   (save-excursion
  830:     (let ((regexp (car forth-compiled-indent-words))
  831: 	  (word-indent)
  832: 	  (self-indent nil)
  833: 	  (next-indent nil)
  834: 	  (to (save-excursion (end-of-line) (point))))
  835:       (beginning-of-line)
  836:       (while (setq word-indent (forth-next-known-indent-word to))
  837: 	(let* ((self-incr (car word-indent))
  838: 	       (next-incr (cdr word-indent))
  839: 	       (self-column-incr (forth-convert-to-column self-incr))
  840: 	       (next-column-incr (forth-convert-to-column next-incr)))
  841: 	  (setq next-indent (if next-indent next-indent 0))
  842: 	  (setq self-indent (if self-indent self-indent 0))
  843: 	  (if (or (and (> next-indent 0) (< self-column-incr 0))
  844: 		  (and (< next-indent 0) (> self-column-incr 0)))
  845: 	      (setq next-indent (+ next-indent self-column-incr))
  846: 	    (setq self-indent (+ self-indent self-column-incr)))
  847: 	  (setq next-indent (+ next-indent next-column-incr))))
  848:       (nth which (list self-indent next-indent)))))
  849: 
  850: ;; Find previous line that contains indentation words, return the column,
  851: ;; to which following text should be indented to.
  852: (defun forth-get-anchor-column ()
  853:   (save-excursion
  854:     (if (/= 0 (forward-line -1)) 0
  855:       (let ((indent))
  856: 	(while (not (or (setq indent (forth-get-column-incr 1))
  857: 			(<= (point) (point-min))))
  858: 	  (forward-line -1))
  859: 	(+ (current-indentation) (if indent indent 0))))))
  860: 
  861: (defun forth-indent-line (&optional flag)
  862:   "Correct indentation of the current Forth line."
  863:   (let* ((anchor (forth-get-anchor-column))
  864: 	 (column-incr (forth-get-column-incr 0)))
  865:     (forth-indent-to (if column-incr (+ anchor column-incr) anchor))))
  866: 
  867: (defun forth-current-column ()
  868:   (- (point) (save-excursion (beginning-of-line) (point))))
  869: (defun forth-current-indentation ()
  870:   (- (save-excursion (beginning-of-line) (forward-to-indentation 0) (point))
  871:      (save-excursion (beginning-of-line) (point))))
  872: 
  873: (defun forth-indent-to (x)
  874:   (let ((p nil))
  875:     (setq p (- (forth-current-column) (forth-current-indentation)))
  876:     (forth-delete-indentation)
  877:     (beginning-of-line)
  878:     (indent-to x)
  879:     (if (> p 0) (forward-char p))))
  880: 
  881: (defun forth-delete-indentation ()
  882:   (save-excursion
  883:     (delete-region 
  884:      (progn (beginning-of-line) (point)) 
  885:      (progn (back-to-indentation) (point)))))
  886: 
  887: (defun forth-indent-command ()
  888:   (interactive)
  889:   (forth-indent-line t))
  890: 
  891: ;; remove trailing whitespaces in current line
  892: (defun forth-remove-trailing ()
  893:   (save-excursion
  894:     (end-of-line)
  895:     (delete-region (point) (progn (skip-chars-backward " \t") (point)))))
  896: 
  897: ;; insert newline, removing any trailing whitespaces in the current line
  898: (defun forth-newline-remove-trailing ()
  899:   (save-excursion
  900:     (delete-region (point) (progn (skip-chars-backward " \t") (point))))
  901:   (newline))
  902: ;  (let ((was-point (point-marker)))
  903: ;    (unwind-protect 
  904: ;	(progn (forward-line -1) (forth-remove-trailing))
  905: ;      (goto-char (was-point)))))
  906: 
  907: ;; workaround for bug in `reindent-then-newline-and-indent'
  908: (defun forth-reindent-then-newline-and-indent ()
  909:   (interactive "*")
  910:   (indent-according-to-mode)
  911:   (forth-newline-remove-trailing)
  912:   (indent-according-to-mode))
  913: 
  914: 
  915: ;;; Block file encoding/decoding  (dk)
  916: ;;;
  917: 
  918: (defconst forth-c/l 64 "Number of characters per block line")
  919: (defconst forth-l/b 16 "Number of lines per block")
  920: 
  921: ;; Check whether the unconverted block file line, point is in, does not
  922: ;; contain `\n' and `\t' characters.
  923: (defun forth-check-block-line (line)
  924:   (let ((end (save-excursion (beginning-of-line) (forward-char forth-c/l)
  925: 			     (point))))
  926:     (save-excursion 
  927:       (beginning-of-line)
  928:       (when (search-forward "\n" end t)
  929: 	(message "Warning: line %i contains newline character #10" line)
  930: 	(ding t))
  931:       (beginning-of-line)
  932:       (when (search-forward "\t" end t)
  933: 	(message "Warning: line %i contains tab character #8" line)
  934: 	(ding t)))))
  935: 
  936: (defun forth-convert-from-block (from to)
  937:   "Convert block file format to stream source in current buffer."
  938:   (let ((line (count-lines (point-min) from)))
  939:     (save-excursion
  940:       (goto-char from)
  941:       (set-mark to)
  942:       (while (< (+ (point) forth-c/l) (mark t))
  943: 	(setq line (1+ line))
  944: 	(forth-check-block-line line)
  945: 	(forward-char forth-c/l)
  946: 	(forth-newline-remove-trailing))
  947:       (when (= (+ (point) forth-c/l) (mark t))
  948: 	(forth-remove-trailing))
  949:       (mark t))))
  950: 
  951: ;; Pad a line of a block file up to `forth-c/l' characters, positioning `point'
  952: ;; at the end of line.
  953: (defun forth-pad-block-line ()
  954:   (save-excursion
  955:     (end-of-line)
  956:     (if (<= (current-column) forth-c/l)
  957: 	(move-to-column forth-c/l t)
  958:       (message "Line %i longer than %i characters, truncated"
  959: 	       (count-lines (point-min) (point)) forth-c/l)
  960:       (ding t)
  961:       (move-to-column forth-c/l t)
  962:       (delete-region (point) (progn (end-of-line) (point))))))
  963: 
  964: ;; Replace tab characters in current line by spaces.
  965: (defun forth-convert-tabs-in-line ()
  966:   (save-excursion
  967:     (beginning-of-line)
  968:     (while (search-forward "\t" (save-excursion (end-of-line) (point)) t)
  969:       (backward-char)
  970:       (delete-region (point) (1+ (point)))
  971:       (insert-char ?\  (- tab-width (% (current-column) tab-width))))))
  972: 
  973: ;; Delete newline at end of current line, concatenating it with the following
  974: ;; line. Place `point' at end of newly formed line.
  975: (defun forth-delete-newline ()
  976:   (end-of-line)
  977:   (delete-region (point) (progn (beginning-of-line 2) (point))))
  978: 
  979: (defun forth-convert-to-block (from to &optional original-buffer) 
  980:   "Convert range of text to block file format in current buffer."
  981:   (let* ((lines 0)) ; I have to count lines myself, since `count-lines' has
  982: 		    ; problems with trailing newlines...
  983:     (save-excursion
  984:       (goto-char from)
  985:       (set-mark to)
  986:       ;; pad lines to full length (`forth-c/l' characters per line)
  987:       (while (< (save-excursion (end-of-line) (point)) (mark t))
  988: 	(setq lines (1+ lines))
  989: 	(forth-pad-block-line)
  990: 	(forth-convert-tabs-in-line)
  991: 	(forward-line))
  992:       ;; also make sure the last line is padded, if `to' is at its end
  993:       (end-of-line)
  994:       (when (= (point) (mark t))
  995: 	(setq lines (1+ lines))
  996: 	(forth-pad-block-line)
  997: 	(forth-convert-tabs-in-line))
  998:       ;; remove newlines between lines
  999:       (goto-char from)
 1000:       (while (< (save-excursion (end-of-line) (point)) (mark t))
 1001: 	(forth-delete-newline))
 1002:       ;; append empty lines, until last block is complete
 1003:       (goto-char (mark t))
 1004:       (let* ((required (* (/ (+ lines (1- forth-l/b)) forth-l/b) forth-l/b))
 1005: 	     (pad-lines (- required lines)))
 1006: 	(while (> pad-lines 0)
 1007: 	  (insert-char ?\  forth-c/l)
 1008: 	  (setq pad-lines (1- pad-lines))))
 1009:       (point))))
 1010: 
 1011: (defun forth-detect-block-file-p ()
 1012:   "Return non-nil if the current buffer is in block file format. Detection is
 1013: done by checking whether the first line has 1024 characters or more."
 1014:   (save-restriction 
 1015:     (widen)
 1016:     (save-excursion
 1017:        (goto-char (point-min))
 1018:        (end-of-line)
 1019:        (>= (current-column) 1024))))
 1020: 
 1021: ;; add block file conversion routines to `format-alist'
 1022: (defconst forth-block-format-description
 1023:   '(forth-blocks "Forth block source file" nil 
 1024: 		 forth-convert-from-block forth-convert-to-block 
 1025: 		 t normal-mode))
 1026: (unless (memq forth-block-format-description format-alist)
 1027:   (setq format-alist (cons forth-block-format-description format-alist)))
 1028: 
 1029: ;;; End block file encoding/decoding
 1030: 
 1031: ;;; Block file editing
 1032: ;;;
 1033: (defvar forth-overlay-arrow-string ">>")
 1034: (defvar forth-block-base 1 "Number of first block in block file")
 1035: (defvar forth-show-screen nil
 1036:   "Non-nil means to show screen starts and numbers (for block files)")
 1037: (defvar forth-warn-long-lines nil
 1038:   "Non-nil means to warn about lines that are longer than 64 characters")
 1039: 
 1040: (defvar forth-screen-marker nil)
 1041: (defvar forth-screen-number-string nil)
 1042: 
 1043: (defun forth-update-show-screen ()
 1044:   "If `forth-show-screen' is non-nil, put overlay arrow to start of screen, 
 1045: `point' is in. If arrow now points to different screen than before, display 
 1046: screen number."
 1047:   (if (not forth-show-screen)
 1048:       (setq overlay-arrow-string nil)
 1049:     (save-excursion
 1050:       (let* ((line (count-lines (point-min) (min (point-max) (1+ (point)))))
 1051: 	     (first-line (1+ (* (/ (1- line) forth-l/b) forth-l/b)))
 1052: 	     (scr (+ forth-block-base (/ first-line forth-l/b))))
 1053: 	(setq overlay-arrow-string forth-overlay-arrow-string)
 1054: 	(goto-line first-line)
 1055: 	(setq overlay-arrow-position forth-screen-marker)
 1056: 	(set-marker forth-screen-marker 
 1057: 		    (save-excursion (goto-line first-line) (point)))
 1058: 	(setq forth-screen-number-string (format "%d" scr))))))
 1059: 
 1060: (add-hook 'forth-motion-hooks 'forth-update-show-screen)
 1061: 
 1062: (defun forth-update-warn-long-lines ()
 1063:   "If `forth-warn-long-lines' is non-nil, display a warning whenever a line
 1064: exceeds 64 characters."
 1065:   (when forth-warn-long-lines
 1066:     (when (> (save-excursion (end-of-line) (current-column)) forth-c/l)
 1067:       (message "Warning: current line exceeds %i characters"
 1068: 	       forth-c/l))))
 1069: 
 1070: (add-hook 'forth-motion-hooks 'forth-update-warn-long-lines)
 1071: 
 1072: ;;; End block file editing
 1073: 
 1074: 
 1075: (defvar forth-mode-abbrev-table nil
 1076:   "Abbrev table in use in Forth-mode buffers.")
 1077: 
 1078: (define-abbrev-table 'forth-mode-abbrev-table ())
 1079: 
 1080: (defvar forth-mode-map nil
 1081:   "Keymap used in Forth mode.")
 1082: 
 1083: (if (not forth-mode-map)
 1084:     (setq forth-mode-map (make-sparse-keymap)))
 1085: 
 1086: ;(define-key forth-mode-map "\M-\C-x" 'compile)
 1087: (define-key forth-mode-map "\C-x\\" 'comment-region)
 1088: (define-key forth-mode-map "\C-x~" 'forth-remove-tracers)
 1089: (define-key forth-mode-map "\e\C-m" 'forth-send-paragraph)
 1090: (define-key forth-mode-map "\eo" 'forth-send-buffer)
 1091: (define-key forth-mode-map "\C-x\C-m" 'forth-split)
 1092: (define-key forth-mode-map "\e " 'forth-reload)
 1093: (define-key forth-mode-map "\t" 'forth-indent-command)
 1094: (define-key forth-mode-map "\C-m" 'forth-reindent-then-newline-and-indent)
 1095: (define-key forth-mode-map "\M-q" 'forth-fill-paragraph)
 1096: (define-key forth-mode-map "\e." 'forth-find-tag)
 1097: 
 1098: ;; setup for C-h C-i to work
 1099: (eval-and-compile (forth-require 'info-look))
 1100: (when (memq 'info-look features)
 1101:   (defvar forth-info-lookup '(symbol (forth-mode "\\S-+" t 
 1102: 						  (("(gforth)Word Index"))
 1103: 						  "\\S-+")))
 1104:   (unless (memq forth-info-lookup info-lookup-alist)
 1105:     (setq info-lookup-alist (cons forth-info-lookup info-lookup-alist)))
 1106:   ;; in X-Emacs C-h C-i is by default bound to Info-query
 1107:   (define-key forth-mode-map "\C-h\C-i" 'info-lookup-symbol))
 1108: 
 1109: 
 1110: ;;   (info-lookup-add-help
 1111: ;;    :topic 'symbol
 1112: ;;    :mode 'forth-mode
 1113: ;;    :regexp "[^ 	
 1114: ;; ]+"
 1115: ;;    :ignore-case t
 1116: ;;    :doc-spec '(("(gforth)Name Index" nil "`" "'  "))))
 1117: 
 1118: (require 'etags)
 1119: 
 1120: (defun forth-find-tag (tagname &optional next-p regexp-p)
 1121:   (interactive (find-tag-interactive "Find tag: "))
 1122:   (unless (or regexp-p next-p)
 1123:     (setq tagname (concat "\\(^\\|\\s-\\)\\(" (regexp-quote tagname) 
 1124: 			    "\\)\\(\\s-\\|$\\)")))
 1125:   (switch-to-buffer
 1126:    (find-tag-noselect tagname next-p t)))
 1127: 
 1128: (defvar forth-mode-syntax-table nil
 1129:   "Syntax table in use in Forth-mode buffers.")
 1130: 
 1131: ;; Important: hilighting/indentation now depends on a correct syntax table.
 1132: ;; All characters, except whitespace *must* belong to the "word constituent"
 1133: ;; syntax class. If different behaviour is required, use of Categories might
 1134: ;; help.
 1135: (if (not forth-mode-syntax-table)
 1136:     (progn
 1137:       (setq forth-mode-syntax-table (make-syntax-table))
 1138:       (let ((char 0))
 1139: 	(while (< char ?!)
 1140: 	  (modify-syntax-entry char " " forth-mode-syntax-table)
 1141: 	  (setq char (1+ char)))
 1142: 	(while (< char 256)
 1143: 	  (modify-syntax-entry char "w" forth-mode-syntax-table)
 1144: 	  (setq char (1+ char))))
 1145:       ))
 1146: 
 1147: (defun forth-mode-variables ()
 1148:   (set-syntax-table forth-mode-syntax-table)
 1149:   (setq local-abbrev-table forth-mode-abbrev-table)
 1150:   (make-local-variable 'paragraph-start)
 1151:   (setq paragraph-start (concat "^$\\|" page-delimiter))
 1152:   (make-local-variable 'paragraph-separate)
 1153:   (setq paragraph-separate paragraph-start)
 1154:   (make-local-variable 'indent-line-function)
 1155:   (setq indent-line-function 'forth-indent-line)
 1156: ;  (make-local-variable 'require-final-newline)
 1157: ;  (setq require-final-newline t)
 1158:   (make-local-variable 'comment-start)
 1159:   (setq comment-start "\\ ")
 1160:   ;(make-local-variable 'comment-end)
 1161:   ;(setq comment-end " )")
 1162:   (make-local-variable 'comment-column)
 1163:   (setq comment-column 40)
 1164:   (make-local-variable 'comment-start-skip)
 1165:   (setq comment-start-skip "\\\\ ")
 1166:   (make-local-variable 'comment-indent-function)
 1167:   (setq comment-indent-function 'forth-comment-indent)
 1168:   (make-local-variable 'parse-sexp-ignore-comments)
 1169:   (setq parse-sexp-ignore-comments t)
 1170:   (setq case-fold-search t)
 1171:   (make-local-variable 'forth-was-point)
 1172:   (setq forth-was-point -1)
 1173:   (make-local-variable 'forth-words)
 1174:   (make-local-variable 'forth-compiled-words)
 1175:   (make-local-variable 'forth-compiled-indent-words)
 1176:   (make-local-variable 'forth-hilight-level)
 1177:   (make-local-variable 'after-change-functions)
 1178:   (make-local-variable 'forth-show-screen)
 1179:   (make-local-variable 'forth-screen-marker)
 1180:   (make-local-variable 'forth-warn-long-lines)
 1181:   (make-local-variable 'forth-screen-number-string)
 1182:   (make-local-variable 'forth-use-oof)
 1183:   (make-local-variable 'forth-use-objects) 
 1184:   (setq forth-screen-marker (copy-marker 0))
 1185:   (add-hook 'after-change-functions 'forth-change-function)
 1186:   (if (and forth-jit-parser (>= emacs-major-version 21))
 1187:       (add-hook 'fontification-functions 'forth-fontification-function))
 1188:   (setq imenu-create-index-function 'forth-create-index))
 1189: 
 1190: ;;;###autoload
 1191: (defun forth-mode ()
 1192:   "
 1193: Major mode for editing Forth code. Tab indents for Forth code. Comments
 1194: are delimited with \\ and newline. Paragraphs are separated by blank lines
 1195: only. Block files are autodetected, when read, and converted to normal 
 1196: stream source format. See also `forth-block-mode'.
 1197: \\{forth-mode-map}
 1198:  Forth-split
 1199:     Positions the current buffer on top and a forth-interaction window
 1200:     below. The window size is controlled by the forth-percent-height
 1201:     variable (see below).
 1202:  Forth-reload
 1203:     Reloads the forth library and restarts the forth process.
 1204:  Forth-send-buffer
 1205:     Sends the current buffer, in text representation, as input to the
 1206:     forth process.
 1207:  Forth-send-paragraph
 1208:     Sends the previous or the current paragraph to the forth-process.
 1209:     Note that the cursor only need to be with in the paragraph to be sent.
 1210:  forth-documentation
 1211:     Search for documentation of forward adjacent to cursor. Note! To use
 1212:     this mode you have to add a line, to your .emacs file, defining the
 1213:     directories to search through for documentation files (se variable
 1214:     forth-help-load-path below) e.g. (setq forth-help-load-path '(nil)).
 1215: 
 1216: Variables controlling interaction and startup
 1217:  forth-percent-height
 1218:     Tells split how high to make the edit portion, in percent of the
 1219:     current screen height.
 1220:  forth-program-name
 1221:     Tells the library which program name to execute in the interation
 1222:     window.
 1223: 
 1224: Variables controlling syntax hilighting/recognition of parsed text:
 1225:  `forth-words'
 1226:     List of words that have a special parsing behaviour and/or should be
 1227:     hilighted. Add custom words by setting forth-custom-words in your
 1228:     .emacs, or by setting forth-local-words, in source-files' local 
 1229:     variables lists.
 1230:  forth-use-objects
 1231:     Set this variable to non-nil in your .emacs, or in a local variables 
 1232:     list, to hilight and recognize the words from the \"Objects\" package 
 1233:     for object-oriented programming.
 1234:  forth-use-oof
 1235:     Same as above, just for the \"OOF\" package.
 1236:  forth-custom-words
 1237:     List of custom Forth words to prepend to `forth-words'. Should be set
 1238:     in your .emacs.
 1239:  forth-local-words
 1240:     List of words to prepend to `forth-words', whenever a forth-mode
 1241:     buffer is created. That variable should be set by Forth sources, using
 1242:     a local variables list at the end of file, to get file-specific
 1243:     hilighting.
 1244:     0 [IF]
 1245:        Local Variables: ... 
 1246:        forth-local-words: ...
 1247:        End:
 1248:     [THEN]
 1249:  forth-hilight-level
 1250:     Controls how much syntax hilighting is done. Should be in the range 
 1251:     0..3
 1252: 
 1253: Variables controlling indentation style:
 1254:  `forth-indent-words'
 1255:     List of words that influence indentation.
 1256:  forth-local-indent-words
 1257:     List of words to prepend to `forth-indent-words', similar to 
 1258:     forth-local-words. Should be used for specifying file-specific 
 1259:     indentation, using a local variables list.
 1260:  forth-custom-indent-words
 1261:     List of words to prepend to `forth-indent-words'. Should be set in your
 1262:     .emacs.    
 1263:  forth-indent-level
 1264:     Indentation increment/decrement of Forth statements.
 1265:  forth-minor-indent-level
 1266:     Minor indentation increment/decrement of Forth statemens.
 1267: 
 1268: Variables controlling block-file editing:
 1269:  forth-show-screen
 1270:     Non-nil means, that the start of the current screen is marked by an
 1271:     overlay arrow, and screen numbers are displayed in the mode line.
 1272:     This variable is by default nil for `forth-mode' and t for 
 1273:     `forth-block-mode'.
 1274:  forth-overlay-arrow-string
 1275:     String to display as the overlay arrow, when `forth-show-screen' is t.
 1276:     Setting this variable to nil disables the overlay arrow.
 1277:  forth-block-base
 1278:     Screen number of the first block in a block file. Defaults to 1.
 1279:  forth-warn-long-lines
 1280:     Non-nil means that a warning message is displayed whenever you edit or
 1281:     move over a line that is longer than 64 characters (the maximum line
 1282:     length that can be stored into a block file). This variable defaults to
 1283:     t for `forth-block-mode' and to nil for `forth-mode'.
 1284: 
 1285: Variables controling documentation search
 1286:  forth-help-load-path
 1287:     List of directories to search through to find *.doc
 1288:     (forth-help-file-suffix) files. Nil means current default directory.
 1289:     The specified directories must contain at least one .doc file. If it
 1290:     does not and you still want the load-path to scan that directory, create
 1291:     an empty file dummy.doc.
 1292:  forth-help-file-suffix
 1293:     The file names to search for in each directory specified by
 1294:     forth-help-load-path. Defaulted to '*.doc'. 
 1295: "
 1296:   (interactive)
 1297:   (kill-all-local-variables)
 1298:   (use-local-map forth-mode-map)
 1299:   (setq mode-name "Forth")
 1300:   (setq major-mode 'forth-mode)
 1301:   (forth-install-motion-hook)
 1302:   ;; convert buffer contents from block file format, if necessary
 1303:   (when (forth-detect-block-file-p)
 1304:     (widen)
 1305:     (message "Converting from Forth block source...")
 1306:     (forth-convert-from-block (point-min) (point-max))
 1307:     (message "Converting from Forth block source...done"))
 1308:   ;; if user switched from forth-block-mode to forth-mode, make sure the file
 1309:   ;; is now stored as normal strem source
 1310:   (when (equal buffer-file-format '(forth-blocks))
 1311:     (setq buffer-file-format nil))
 1312:   (forth-mode-variables)
 1313: ;  (if (not (forth-process-running-p))
 1314: ;      (run-forth forth-program-name))
 1315:   (run-hooks 'forth-mode-hook))
 1316: 
 1317: ;;;###autoload
 1318: (define-derived-mode forth-block-mode forth-mode "Forth Block Source" 
 1319:   "Major mode for editing Forth block source files, derived from 
 1320: `forth-mode'. Differences to `forth-mode' are:
 1321:  * files are converted to block format, when written (`buffer-file-format' 
 1322:    is set to `(forth-blocks)')
 1323:  * `forth-show-screen' and `forth-warn-long-lines' are t by default
 1324:   
 1325: Note that the length of lines in block files is limited to 64 characters.
 1326: When writing longer lines to a block file, a warning is displayed in the
 1327: echo area and the line is truncated. 
 1328: 
 1329: Another problem is imposed by block files that contain newline or tab 
 1330: characters. When Emacs converts such files back to block file format, 
 1331: it'll translate those characters to a number of spaces. However, when
 1332: you read such a file, a warning message is displayed in the echo area,
 1333: including a line number that may help you to locate and fix the problem.
 1334: 
 1335: So have a look at the *Messages* buffer, whenever you hear (or see) Emacs' 
 1336: bell during block file read/write operations."
 1337:   (setq buffer-file-format '(forth-blocks))
 1338:   (setq forth-show-screen t)
 1339:   (setq forth-warn-long-lines t)
 1340:   (setq forth-screen-number-string (format "%d" forth-block-base))
 1341:   (setq mode-line-format (append (reverse (cdr (reverse mode-line-format)))
 1342: 				 '("--S" forth-screen-number-string "-%-"))))
 1343: 
 1344: (add-hook 'forth-mode-hook
 1345:       '(lambda () 
 1346: 	 (make-local-variable 'compile-command)
 1347: 	 (setq compile-command "gforth ")
 1348: 	 (forth-hack-local-variables)
 1349: 	 (forth-customize-words)
 1350: 	 (forth-compile-words)
 1351: 	 (unless (and forth-jit-parser (>= emacs-major-version 21))
 1352: 	   (forth-change-function (point-min) (point-max) nil t))))
 1353: 
 1354: (defun forth-fill-paragraph () 
 1355:   "Fill comments (starting with '\'; do not fill code (block style
 1356: programmers who tend to fill code won't use emacs anyway:-)."
 1357:   ; Currently only comments at the start of the line are filled.
 1358:   ; Something like lisp-fill-paragraph may be better.  We cannot use
 1359:   ; fill-paragraph, because it removes the \ from the first comment
 1360:   ; line. Therefore we have to look for the first line of the comment
 1361:   ; and use fill-region.
 1362:   (interactive)
 1363:   (save-excursion
 1364:     (beginning-of-line)
 1365:     (while (and
 1366: 	     (= (forward-line -1) 0)
 1367: 	     (looking-at "[ \t]*\\\\g?[ \t]+")))
 1368:     (if (not (looking-at "[ \t]*\\\\g?[ \t]+"))
 1369: 	(forward-line 1))
 1370:     (let ((from (point))
 1371: 	  (to (save-excursion (forward-paragraph) (point))))
 1372:       (if (looking-at "[ \t]*\\\\g?[ \t]+")
 1373: 	  (progn (goto-char (match-end 0))
 1374: 		 (set-fill-prefix)
 1375: 		 (fill-region from to nil))))))
 1376: 
 1377: (defun forth-comment-indent ()
 1378:   (save-excursion
 1379:     (beginning-of-line)
 1380:     (if (looking-at ":[ \t]*")
 1381: 	(progn
 1382: 	  (end-of-line)
 1383: 	  (skip-chars-backward " \t\n")
 1384: 	  (1+ (current-column)))
 1385:       comment-column)))
 1386: 
 1387: 
 1388: ;; Forth commands
 1389: 
 1390: (defun forth-remove-tracers ()
 1391:   "Remove tracers of the form `~~ '. Queries the user for each occurrence."
 1392:   (interactive)
 1393:   (query-replace-regexp "\\(~~ \\| ~~$\\)" "" nil))
 1394: 
 1395: (defvar forth-program-name "gforth"
 1396:   "*Program invoked by the `run-forth' command.")
 1397: 
 1398: (defvar forth-band-name nil
 1399:   "*Band loaded by the `run-forth' command.")
 1400: 
 1401: (defvar forth-program-arguments nil
 1402:   "*Arguments passed to the Forth program by the `run-forth' command.")
 1403: 
 1404: (defun run-forth (command-line)
 1405:   "Run an inferior Forth process. Output goes to the buffer `*forth*'.
 1406: With argument, asks for a command line. Split up screen and run forth 
 1407: in the lower portion. The current-buffer when called will stay in the
 1408: upper portion of the screen, and all other windows are deleted.
 1409: Call run-forth again to make the *forth* buffer appear in the lower
 1410: part of the screen."
 1411:   (interactive
 1412:    (list (let ((default
 1413: 		 (or forth-process-command-line
 1414: 		     (forth-default-command-line))))
 1415: 	   (if current-prefix-arg
 1416: 	       (read-string "Run Forth: " default)
 1417: 	       default))))
 1418:   (setq forth-process-command-line command-line)
 1419:   (forth-start-process command-line)
 1420:   (forth-split)
 1421:   (forth-set-runlight forth-runlight:input))
 1422: 
 1423: (defun run-forth-if-not ()
 1424:   (if (not (forth-process-running-p))
 1425:       (run-forth forth-program-name)))
 1426: 
 1427: (defun reset-forth ()
 1428:   "Reset the Forth process."
 1429:   (interactive)
 1430:   (let ((process (get-process forth-program-name)))
 1431:     (cond ((or (not process)
 1432: 	       (not (eq (process-status process) 'run))
 1433: 	       (yes-or-no-p
 1434: "The Forth process is running, are you SURE you want to reset it? "))
 1435: 	   (message "Resetting Forth process...")
 1436: 	   (forth-reload)
 1437: 	   (message "Resetting Forth process...done")))))
 1438: 
 1439: (defun forth-default-command-line ()
 1440:   (concat forth-program-name
 1441: 	  (if forth-program-arguments
 1442: 	      (concat " " forth-program-arguments)
 1443: 	      "")))
 1444: 
 1445: ;;;; Internal Variables
 1446: 
 1447: (defvar forth-process-command-line nil
 1448:   "Command used to start the most recent Forth process.")
 1449: 
 1450: (defvar forth-previous-send ""
 1451:   "Most recent expression transmitted to the Forth process.")
 1452: 
 1453: (defvar forth-process-filter-queue '()
 1454:   "Queue used to synchronize filter actions properly.")
 1455: 
 1456: (defvar forth-prompt "ok"
 1457:   "The current forth prompt string.")
 1458: 
 1459: (defvar forth-start-hook nil
 1460:   "If non-nil, a procedure to call when the Forth process is started.
 1461: When called, the current buffer will be the Forth process-buffer.")
 1462: 
 1463: (defvar forth-signal-death-message nil
 1464:   "If non-nil, causes a message to be generated when the Forth process dies.")
 1465: 
 1466: (defvar forth-percent-height 50
 1467:   "Tells run-forth how high the upper window should be in percent.")
 1468: 
 1469: (defconst forth-runlight:input ?I
 1470:   "The character displayed when the Forth process is waiting for input.")
 1471: 
 1472: (defvar forth-mode-string ""
 1473:   "String displayed in the mode line when the Forth process is running.")
 1474: 
 1475: ;;;; Evaluation Commands
 1476: 
 1477: (defun forth-send-string (&rest strings)
 1478:   "Send the string arguments to the Forth process.
 1479: The strings are concatenated and terminated by a newline."
 1480:   (cond ((forth-process-running-p)
 1481: 	 (forth-send-string-1 strings))
 1482: 	((yes-or-no-p "The Forth process has died.  Reset it? ")
 1483: 	 (reset-forth)
 1484: 	 (goto-char (point-max))
 1485: 	 (forth-send-string-1 strings))))
 1486: 
 1487: (defun forth-send-string-1 (strings)
 1488:   (let ((string (apply 'concat strings)))
 1489:     (forth-send-string-2 string)))
 1490: 
 1491: (defun forth-send-string-2 (string)
 1492:   (let ((process (get-process forth-program-name)))
 1493:     (if (not (eq (current-buffer) (get-buffer forth-program-name)))
 1494: 	(progn
 1495: 	 (forth-process-filter-output string)
 1496: 	 (forth-process-filter:finish)))
 1497:     (send-string process (concat string "\n"))
 1498:     (if (eq (current-buffer) (process-buffer process))
 1499: 	(set-marker (process-mark process) (point)))))
 1500: 
 1501: 
 1502: (defun forth-send-region (start end)
 1503:   "Send the current region to the Forth process.
 1504: The region is sent terminated by a newline."
 1505:   (interactive "r")
 1506:   (let ((process (get-process forth-program-name)))
 1507:     (if (and process (eq (current-buffer) (process-buffer process)))
 1508: 	(progn (goto-char end)
 1509: 	       (set-marker (process-mark process) end))))
 1510:   (forth-send-string "\n" (buffer-substring start end) "\n"))
 1511: 
 1512: (defun forth-end-of-paragraph ()
 1513:   (if (looking-at "[\t\n ]+") (skip-chars-backward  "\t\n "))
 1514:   (if (not (re-search-forward "\n[ \t]*\n" nil t))
 1515:       (goto-char (point-max))))
 1516: 
 1517: (defun forth-send-paragraph ()
 1518:   "Send the current or the previous paragraph to the Forth process"
 1519:   (interactive)
 1520:   (let (end)
 1521:     (save-excursion
 1522:       (forth-end-of-paragraph)
 1523:       (skip-chars-backward  "\t\n ")
 1524:       (setq end (point))
 1525:       (if (re-search-backward "\n[ \t]*\n" nil t)
 1526: 	  (setq start (point))
 1527: 	(goto-char (point-min)))
 1528:       (skip-chars-forward  "\t\n ")
 1529:       (forth-send-region (point) end))))
 1530:   
 1531: (defun forth-send-buffer ()
 1532:   "Send the current buffer to the Forth process."
 1533:   (interactive)
 1534:   (if (eq (current-buffer) (forth-process-buffer))
 1535:       (error "Not allowed to send this buffer's contents to Forth"))
 1536:   (forth-send-region (point-min) (point-max)))
 1537: 
 1538: 
 1539: ;;;; Basic Process Control
 1540: 
 1541: (defun forth-start-process (command-line)
 1542:   (let ((buffer (get-buffer-create "*forth*")))
 1543:     (let ((process (get-buffer-process buffer)))
 1544:       (save-excursion
 1545: 	(set-buffer buffer)
 1546: 	(progn (if process (delete-process process))
 1547: 	       (goto-char (point-max))
 1548: 	       (setq mode-line-process '(": %s"))
 1549: 	       (add-to-global-mode-string 'forth-mode-string)
 1550: 	       (setq process
 1551: 		     (apply 'start-process
 1552: 			    (cons forth-program-name
 1553: 				  (cons buffer
 1554: 					(forth-parse-command-line
 1555: 					 command-line)))))
 1556: 	       (set-marker (process-mark process) (point-max))
 1557: 	       (forth-process-filter-initialize t)
 1558: 	       (forth-modeline-initialize)
 1559: 	       (set-process-sentinel process 'forth-process-sentinel)
 1560: 	       (set-process-filter process 'forth-process-filter)
 1561: 	       (run-hooks 'forth-start-hook)))
 1562:     buffer)))
 1563: 
 1564: (defun forth-parse-command-line (string)
 1565:   (setq string (substitute-in-file-name string))
 1566:   (let ((start 0)
 1567: 	(result '()))
 1568:     (while start
 1569:       (let ((index (string-match "[ \t]" string start)))
 1570: 	(setq start
 1571: 	      (cond ((not index)
 1572: 		     (setq result
 1573: 			   (cons (substring string start)
 1574: 				 result))
 1575: 		     nil)
 1576: 		    ((= index start)
 1577: 		     (string-match "[^ \t]" string start))
 1578: 		    (t
 1579: 		     (setq result
 1580: 			   (cons (substring string start index)
 1581: 				 result))
 1582: 		     (1+ index))))))
 1583:     (nreverse result)))
 1584: 
 1585: 
 1586: (defun forth-process-running-p ()
 1587:   "True iff there is a Forth process whose status is `run'."
 1588:   (let ((process (get-process forth-program-name)))
 1589:     (and process
 1590: 	 (eq (process-status process) 'run))))
 1591: 
 1592: (defun forth-process-buffer ()
 1593:   (let ((process (get-process forth-program-name)))
 1594:     (and process (process-buffer process))))
 1595: 
 1596: ;;;; Process Filter
 1597: 
 1598: (defun forth-process-sentinel (proc reason)
 1599:   (let ((inhibit-quit nil))
 1600:     (forth-process-filter-initialize (eq reason 'run))
 1601:     (if (eq reason 'run)
 1602: 	(forth-modeline-initialize)
 1603: 	(setq forth-mode-string "")))
 1604:   (if (and (not (memq reason '(run stop)))
 1605: 	   forth-signal-death-message)
 1606:       (progn (beep)
 1607: 	     (message
 1608: "The Forth process has died!  Do M-x reset-forth to restart it"))))
 1609: 
 1610: (defun forth-process-filter-initialize (running-p)
 1611:   (setq forth-process-filter-queue (cons '() '()))
 1612:   (setq forth-prompt "ok"))
 1613: 
 1614: 
 1615: (defun forth-process-filter (proc string)
 1616:   (forth-process-filter-output string)
 1617:   (forth-process-filter:finish))
 1618: 
 1619: (defun forth-process-filter:enqueue (action)
 1620:   (let ((next (cons action '())))
 1621:     (if (cdr forth-process-filter-queue)
 1622: 	(setcdr (cdr forth-process-filter-queue) next)
 1623: 	(setcar forth-process-filter-queue next))
 1624:     (setcdr forth-process-filter-queue next)))
 1625: 
 1626: (defun forth-process-filter:finish ()
 1627:   (while (car forth-process-filter-queue)
 1628:     (let ((next (car forth-process-filter-queue)))
 1629:       (setcar forth-process-filter-queue (cdr next))
 1630:       (if (not (cdr next))
 1631: 	  (setcdr forth-process-filter-queue '()))
 1632:       (apply (car (car next)) (cdr (car next))))))
 1633: 
 1634: ;;;; Process Filter Output
 1635: 
 1636: (defun forth-process-filter-output (&rest args)
 1637:   (if (not (and args
 1638: 		(null (cdr args))
 1639: 		(stringp (car args))
 1640: 		(string-equal "" (car args))))
 1641:       (forth-process-filter:enqueue
 1642:        (cons 'forth-process-filter-output-1 args))))
 1643: 
 1644: (defun forth-process-filter-output-1 (&rest args)
 1645:   (save-excursion
 1646:     (forth-goto-output-point)
 1647:     (apply 'insert-before-markers args)))
 1648: 
 1649: (defun forth-guarantee-newlines (n)
 1650:   (save-excursion
 1651:     (forth-goto-output-point)
 1652:     (let ((stop nil))
 1653:       (while (and (not stop)
 1654: 		  (bolp))
 1655: 	(setq n (1- n))
 1656: 	(if (bobp)
 1657: 	    (setq stop t)
 1658: 	  (backward-char))))
 1659:     (forth-goto-output-point)
 1660:     (while (> n 0)
 1661:       (insert-before-markers ?\n)
 1662:       (setq n (1- n)))))
 1663: 
 1664: (defun forth-goto-output-point ()
 1665:   (let ((process (get-process forth-program-name)))
 1666:     (set-buffer (process-buffer process))
 1667:     (goto-char (process-mark process))))
 1668: 
 1669: (defun forth-modeline-initialize ()
 1670:   (setq forth-mode-string "  "))
 1671: 
 1672: (defun forth-set-runlight (runlight)
 1673:   (aset forth-mode-string 0 runlight)
 1674:   (forth-modeline-redisplay))
 1675: 
 1676: (defun forth-modeline-redisplay ()
 1677:   (save-excursion (set-buffer (other-buffer)))
 1678:   (set-buffer-modified-p (buffer-modified-p))
 1679:   (sit-for 0))
 1680: 
 1681: ;;;; Process Filter Operations
 1682: 
 1683: (defun add-to-global-mode-string (x)
 1684:   (cond ((null global-mode-string)
 1685: 	 (setq global-mode-string (list "" x " ")))
 1686: 	((not (memq x global-mode-string))
 1687: 	 (setq global-mode-string
 1688: 	       (cons ""
 1689: 		     (cons x
 1690: 			   (cons " "
 1691: 				 (if (equal "" (car global-mode-string))
 1692: 				     (cdr global-mode-string)
 1693: 				     global-mode-string))))))))
 1694: 
 1695: 
 1696: ;; Misc
 1697: 
 1698: (setq auto-mode-alist (append auto-mode-alist
 1699: 				'(("\\.fs$" . forth-mode))))
 1700: 
 1701: (defun forth-split ()
 1702:   (interactive)
 1703:   (forth-split-1 "*forth*"))
 1704: 
 1705: (defun forth-split-1 (buffer)
 1706:   (if (not (eq (window-buffer) (get-buffer buffer)))
 1707:       (progn
 1708: 	(delete-other-windows)
 1709: 	(split-window-vertically
 1710: 	 (/ (* (screen-height) forth-percent-height) 100))
 1711: 	(other-window 1)
 1712: 	(switch-to-buffer buffer)
 1713: 	(goto-char (point-max))
 1714: 	(other-window 1))))
 1715:     
 1716: (defun forth-reload ()
 1717:   (interactive)
 1718:   (let ((process (get-process forth-program-name)))
 1719:     (if process (kill-process process t)))
 1720:   (sleep-for 0 100)
 1721:   (forth-mode))
 1722: 
 1723: 
 1724: ;; Special section for forth-help
 1725: 
 1726: (defvar forth-help-buffer "*Forth-help*"
 1727:   "Buffer used to display the requested documentation.")
 1728: 
 1729: (defvar forth-help-load-path nil
 1730:   "List of directories to search through to find *.doc
 1731:  (forth-help-file-suffix) files. Nil means current default directory.
 1732:  The specified directories must contain at least one .doc file. If it
 1733:  does not and you still want the load-path to scan that directory, create
 1734:  an empty file dummy.doc.")
 1735: 
 1736: (defvar forth-help-file-suffix "*.doc"
 1737:   "The file names to search for in each directory.")
 1738: 
 1739: (setq forth-search-command-prefix "grep -n \"^    [^(]* ")
 1740: (defvar forth-search-command-suffix "/dev/null")
 1741: (defvar forth-grep-error-regexp ": No such file or directory")
 1742: 
 1743: (defun forth-function-called-at-point ()
 1744:   "Return the space delimited word a point."
 1745:   (save-excursion
 1746:     (save-restriction
 1747:       (narrow-to-region (max (point-min) (- (point) 1000)) (point-max))
 1748:       (skip-chars-backward "^ \t\n" (point-min))
 1749:       (if (looking-at "[ \t\n]")
 1750: 	  (forward-char 1))
 1751:       (let (obj (p (point)))
 1752: 	(skip-chars-forward "^ \t\n")
 1753: 	(buffer-substring p (point))))))
 1754: 
 1755: (defun forth-help-names-extend-comp (path-list result)
 1756:   (cond ((null path-list) result)
 1757: 	((null (car path-list))
 1758: 	 (forth-help-names-extend-comp (cdr path-list) 
 1759: 	       (concat result forth-help-file-suffix " ")))
 1760: 	(t (forth-help-names-extend-comp
 1761: 	    (cdr path-list) (concat result
 1762: 				    (expand-file-name (car path-list)) "/"
 1763: 				    forth-help-file-suffix " ")))))
 1764: 
 1765: (defun forth-help-names-extended ()
 1766:   (if forth-help-load-path
 1767:       (forth-help-names-extend-comp forth-help-load-path "")
 1768:     (error "forth-help-load-path not specified")))
 1769: 
 1770: 
 1771: ;(define-key forth-mode-map "\C-hf" 'forth-documentation)
 1772: 
 1773: (defun forth-documentation (function)
 1774:   "Display the full documentation of FORTH word."
 1775:   (interactive
 1776:    (let ((fn (forth-function-called-at-point))
 1777: 	 (enable-recursive-minibuffers t)	     
 1778: 	 search-list
 1779: 	 val)
 1780:      (setq val (read-string (format "Describe forth word (default %s): " fn)))
 1781:      (list (if (equal val "") fn val))))
 1782:   (forth-get-doc (concat forth-search-command-prefix
 1783: 			 (grep-regexp-quote (concat function " ("))
 1784: 			 "[^)]*\-\-\" " (forth-help-names-extended)
 1785: 			 forth-search-command-suffix))
 1786:   (message "C-x C-m switches back to the forth interaction window"))
 1787: 
 1788: (defun forth-get-doc (command)
 1789:   "Display the full documentation of command."
 1790:   (let ((curwin (get-buffer-window (window-buffer)))
 1791: 	reswin
 1792: 	pointmax)
 1793:     (with-output-to-temp-buffer forth-help-buffer
 1794:       (progn
 1795: 	(call-process "sh" nil forth-help-buffer t "-c" command)
 1796: 	(setq reswin (get-buffer-window forth-help-buffer))))
 1797:     (setq reswin (get-buffer-window forth-help-buffer))
 1798:     (select-window reswin)
 1799:     (save-excursion
 1800:       (goto-char (setq pointmax (point-max)))
 1801:       (insert "--------------------\n\n"))
 1802:     (let (fd doc) 
 1803:       (while (setq fd (forth-get-file-data pointmax))
 1804: 	(setq doc (forth-get-doc-string fd))
 1805: 	(save-excursion
 1806: 	  (goto-char (point-max))
 1807: 	  (insert (substring (car fd) (string-match "[^/]*$" (car fd)))
 1808: 		  ":\n\n" doc "\n")))
 1809:       (if (not doc)
 1810: 	  (progn (goto-char (point-max)) (insert "Not found"))))
 1811:     (select-window curwin)))
 1812:   
 1813: (defun forth-skip-error-lines ()
 1814:   (let ((lines 0))
 1815:     (save-excursion
 1816:       (while (re-search-forward forth-grep-error-regexp nil t)
 1817: 	(beginning-of-line)
 1818: 	(forward-line 1)
 1819: 	(setq lines (1+ lines))))
 1820:     (forward-line lines)))
 1821: 
 1822: (defun forth-get-doc-string (fd)
 1823:   "Find file (car fd) and extract documentation from line (nth 1 fd)."
 1824:   (let (result)
 1825:     (save-window-excursion
 1826:       (find-file (car fd))
 1827:       (goto-line (nth 1 fd))
 1828:       (if (not (eq (nth 1 fd) (1+ (count-lines (point-min) (point)))))
 1829: 	  (error "forth-get-doc-string: serious error"))
 1830:       (if (not (re-search-backward "\n[\t ]*\n" nil t))
 1831: 	  (goto-char (point-min))
 1832: 	(goto-char (match-end 0)))
 1833:       (let ((p (point)))
 1834: 	(if (not (re-search-forward "\n[\t ]*\n" nil t))
 1835: 	    (goto-char (point-max)))
 1836: 	(setq result (buffer-substring p (point))))
 1837:       (bury-buffer (current-buffer)))
 1838:     result))
 1839: 
 1840: (defun forth-get-file-data (limit)
 1841:   "Parse grep output and return '(filename line#) list. Return nil when
 1842:  passing limit."
 1843:   (forth-skip-error-lines)
 1844:   (if (< (point) limit)
 1845:       (let ((result (forth-get-file-data-cont limit)))
 1846: 	(forward-line 1)
 1847: 	(beginning-of-line)
 1848: 	result)))
 1849: 
 1850: (defun forth-get-file-data-cont (limit)
 1851:   (let (result)
 1852:     (let ((p (point)))
 1853:       (skip-chars-forward "^:")
 1854:       (setq result (buffer-substring p (point))))
 1855:     (if (< (point) limit)
 1856: 	(let ((p (1+ (point))))
 1857: 	  (forward-char 1)
 1858: 	  (skip-chars-forward "^:")
 1859: 	  (list result (string-to-int (buffer-substring p (point))))))))
 1860: 
 1861: (defun grep-regexp-quote (str)
 1862:   (let ((i 0) (m 1) (res ""))
 1863:     (while (/= m 0)
 1864:       (setq m (string-to-char (substring str i)))
 1865:       (if (/= m 0)
 1866: 	  (progn
 1867: 	    (setq i (1+ i))
 1868: 	    (if (string-match (regexp-quote (char-to-string m))
 1869: 			      ".*\\^$[]")
 1870: 		(setq res (concat res "\\")))
 1871: 	    (setq res (concat res (char-to-string m))))))
 1872:     res))
 1873: 
 1874: 
 1875: (define-key forth-mode-map "\C-x\C-e" 'compile)
 1876: (define-key forth-mode-map "\C-x\C-n" 'next-error)
 1877: (require 'compile)
 1878: 
 1879: (defvar forth-compile-command "gforth ")
 1880: ;(defvar forth-compilation-window-percent-height 30)
 1881: 
 1882: (defun forth-compile (command)
 1883:   (interactive (list (setq forth-compile-command (read-string "Compile command: " forth-compile-command))))
 1884:   (forth-split-1 "*compilation*")
 1885:   (setq ctools-compile-command command)
 1886:   (compile1 ctools-compile-command "No more errors"))
 1887: 
 1888: 
 1889: ;;; Forth menu
 1890: ;;; Mikael Karlsson <qramika@eras70.ericsson.se>
 1891: 
 1892: ;; (dk) code commented out due to complaints of XEmacs users.  After
 1893: ;; all, there's imenu/speedbar, which uses much smarter scanning
 1894: ;; rules.
 1895: 
 1896: ;; (cond ((string-match "XEmacs\\|Lucid" emacs-version)
 1897: ;;        (require 'func-menu)
 1898: 
 1899: ;;   (defconst fume-function-name-regexp-forth
 1900: ;;    "^\\(:\\)[ \t]+\\([^ \t]*\\)"
 1901: ;;    "Expression to get word definitions in Forth.")
 1902: 
 1903: ;;   (setq fume-function-name-regexp-alist
 1904: ;;       (append '((forth-mode . fume-function-name-regexp-forth) 
 1905: ;;              ) fume-function-name-regexp-alist))
 1906: 
 1907: ;;   ;; Find next forth word in the buffer
 1908: ;;   (defun fume-find-next-forth-function-name (buffer)
 1909: ;;     "Searches for the next forth word in BUFFER."
 1910: ;;     (set-buffer buffer)
 1911: ;;     (if (re-search-forward fume-function-name-regexp nil t)
 1912: ;;       (let ((beg (match-beginning 2))
 1913: ;;             (end (match-end 2)))
 1914: ;;         (cons (buffer-substring beg end) beg))))
 1915: 
 1916: ;;   (setq fume-find-function-name-method-alist
 1917: ;;   (append '((forth-mode    . fume-find-next-forth-function-name))))
 1918: 
 1919: ;;   ))
 1920: ;;; End Forth menu
 1921: 
 1922: ;;; File folding of forth-files
 1923: ;;; uses outline
 1924: ;;; Toggle activation with M-x fold-f (when editing a forth-file) 
 1925: ;;; Use f9 to expand, f10 to hide, Or the menubar in xemacs
 1926: ;;;
 1927: ;;; Works most of the times but loses sync with the cursor occasionally 
 1928: ;;; Could be improved by also folding on comments
 1929: 
 1930: ;; (dk) This code needs a rewrite; just too ugly and doesn't use the
 1931: ;; newer and smarter scanning rules of `imenu'. Who needs it anyway??
 1932: 
 1933: ;; (require 'outline)
 1934: 
 1935: ;; (defun f-outline-level ()
 1936: ;;   (cond	((looking-at "\\`\\\\")
 1937: ;; 	 0)
 1938: ;; 	((looking-at "\\\\ SEC")
 1939: ;; 	 0)
 1940: ;; 	((looking-at "\\\\ \\\\ .*")
 1941: ;; 	 0)
 1942: ;; 	((looking-at "\\\\ DEFS")
 1943: ;; 	 1)
 1944: ;; 	((looking-at "\\/\\* ")
 1945: ;; 	 1)
 1946: ;; 	((looking-at ": .*")
 1947: ;; 	 1)
 1948: ;; 	((looking-at "\\\\G")
 1949: ;; 	 2)
 1950: ;; 	((looking-at "[ \t]+\\\\")
 1951: ;; 	 3)))
 1952:   
 1953: ;; (defun fold-f  ()
 1954: ;;    (interactive)
 1955: ;;    (add-hook 'outline-minor-mode-hook 'hide-body)
 1956: 
 1957: ;;    ; outline mode header start, i.e. find word definitions
 1958: ;; ;;;   (setq  outline-regexp  "^\\(:\\)[ \t]+\\([^ \t]*\\)")
 1959: ;;    (setq  outline-regexp  "\\`\\\\\\|:\\|\\\\ SEC\\|\\\\G\\|[ \t]+\\\\\\|\\\\ DEFS\\|\\/\\*\\|\\\\ \\\\ .*")
 1960: ;;    (setq outline-level 'f-outline-level)
 1961: 
 1962: ;;    (outline-minor-mode)
 1963: ;;    (define-key outline-minor-mode-map '(shift up) 'hide-sublevels)
 1964: ;;    (define-key outline-minor-mode-map '(shift right) 'show-children)
 1965: ;;    (define-key outline-minor-mode-map '(shift left) 'hide-subtree)
 1966: ;;    (define-key outline-minor-mode-map '(shift down) 'show-subtree))
 1967: 
 1968: 
 1969: ;;(define-key global-map '(shift up) 'fold-f)
 1970: 
 1971: ;;; end file folding
 1972: 
 1973: ;;; func-menu is a package that scans your source file for function definitions
 1974: ;;; and makes a menubar entry that lets you jump to any particular function
 1975: ;;; definition by selecting it from the menu.  The following code turns this on
 1976: ;;; for all of the recognized languages.  Scanning the buffer takes some time,
 1977: ;;; but not much.
 1978: ;;;
 1979: ;; (cond ((string-match "XEmacs\\|Lucid" emacs-version)
 1980: ;;        (require 'func-menu)
 1981: ;; ;;       (define-key global-map 'f8 'function-menu)
 1982: ;;        (add-hook 'find-fible-hooks 'fume-add-menubar-entry)
 1983: ;; ;       (define-key global-map "\C-cg" 'fume-prompt-function-goto)
 1984: ;; ;       (define-key global-map '(shift button3) 'mouse-function-menu)
 1985: ;; ))
 1986: 
 1987: (provide 'forth-mode)
 1988: 
 1989: ;;; gforth.el ends here

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>