keyence-script-mode

KEYENCEのハンディーターミナルBT-950W/950B/910の開発ソフト「BT-Navigator」のスクリプトを編集するモードです。
visual-basic-mode.elをちょっといじっただけです。
Meadow-3.00-dev (KIKU)」で動作確認をしました。
.emacsに以下を追加して使います。

;;; 以下のコメントは元ネタの visual-basic-mode.el のそのまんまです。
;;; 不勉強にしてライセンスはよく解らないのですが、多分GPLは適用されると
;;; 思います。

;;; visual-basic-mode.el 
;; This is free software.

;; A mode for editing Visual Basic programs.
;; Modified version of Fred White's visual-basic-mode.el

;; Copyright (C) 1996 Fred White <fwhite@alum.mit.edu>
;; Copyright (C) 1998 Free Software Foundation, Inc.
;;   (additions by Dave Love)

;; Author: Fred White <fwhite@alum.mit.edu>
;; Adapted-by: Dave Love <d.love@dl.ac.uk>
;;	     : Kevin Whitefoot <kevin.whitefoot@nopow.abb.no>
;; Version: 1.3 (May 1, 1996)
;; Keywords: languages, basic, Evil

;; (Old) LCD Archive Entry:
;; basic-mode|Fred White|fwhite@alum.mit.edu|
;; A mode for editing Visual Basic programs.|
;; 18-Apr-96|1.0|~/modes/basic-mode.el.Z|

;; This file is NOT part of GNU Emacs but the same permissions apply.
;;
;; GNU Emacs  is free software;	 you can redistribute it and/or modify
;; it under the terms of  the GNU General  Public License as published
;; by  the Free Software  Foundation;  either version  2, or (at  your
;; option) any later version.
;;
;; GNU	Emacs is distributed  in the hope that	it will be useful, but
;; WITHOUT    ANY  WARRANTY;  without even the	   implied warranty of
;; MERCHANTABILITY or FITNESS FOR A  PARTICULAR PURPOSE.  See the  GNU
;; General Public License for more details.
;;
;; You should have received  a copy of	the GNU General Public License
;; along with GNU Emacs; see  the file COPYING.	 If  not, write to the
;; Free Software Foundation, 675  Mass Ave, Cambridge, MA 02139,  USA.
;; This	 program  is free  software;  you  can	redistribute it and/or
;; modify it  under  the terms of the  GNU  General Public License  as
;; published by the Free Software  Foundation; either version 2 of the
;; License, or (at your option) any later version.

;;; Commentary:

;; Purpose of this package:
;;  This is a mode for editing programs written in The World's Most
;;  Successful Programming Language.  It features automatic
;;  indentation, font locking, keyword capitalization, and some minor
;;  convenience functions.

;; Installation instructions
;;  Put basic-mode.el somewhere in your path, compile it, and add the
;;  following to your init file:

;;  (autoload 'visual-basic-mode "visual-basic-mode" "Visual Basic mode." t)
;;  (setq auto-mode-alist (append '(("\\.\\(frm\\|bas\\|cls\\)$" .
;;				    visual-basic-mode)) auto-mode-alist))

;; Of course, under Windows 3.1, you'll have to name this file
;; something shorter than visual-basic-mode.el

;; Revisions:
;; 1.0 18-Apr-96  Initial version
;; 1.1 Accomodate emacs 19.29+ font-lock-defaults
;;     Simon Marshall <Simon.Marshall@esrin.esa.it>
;  1.2 Rename to visual-basic-mode
;; 1.3 Fix some indentation bugs.
;; 1.3+ Changes by Dave Love: [No attempt at compatibility with
;;	anything other than Emacs 20, sorry, but little attempt to
;;	sanitize for Emacs 20 specifically.]
;;	Change `_' syntax only for font-lock and imenu, not generally;
;;	provide levels of font-locking in the current fashion;
;;	font-lock case-insensitively; use regexp-opt with the font-lok
;;	keywords; imenu support; `visual-basic-split-line', bound to
;;	C-M-j; account for single-statement `if' in indentation; add
;;	keyword "Global"; use local-write-file-hooks, not
;;	write-file-hooks.
;; 1.4 September 1998
;; 1.4 KJW Add begin..end, add extra keywords
;;     Add customisation for single line if.  Disallow by default.
;;     Fix if regexp to require whitespace after if and require then.
;;     Add more VB keywords.  Make begin..end work as if..endif so
;;     that forms are formatted correctly.
;; 1.4.1 KJW Merged Dave Love and KJW versions.
;;     Added keywords suggested by Mickey Ferguson
;;     <MFerguson@peinc.com>
;;     Fixed imenu variable to find private variables and enums

;;     Changed syntax class of =, <, > to punctuation to allow dynamic
;;     abbreviations to pick up only the word at point rather than the
;;     whole expression.

;;     Fixed bug introduced by KJW adding suport for begin...end in
;;     forms whereby a single end outdented.

;;     Partially fixed failure to recognise if statements with
;;     continuations (still fails on 'single line' if with
;;     continuation, ugh).

;; Known bugs:
;;  Doesn't know about ":" separated stmts
;;  Doesn't recognize single line if statements if these are broken by
;;  line continuation characters

;; todo:
;;  fwd/back-compound-statement
;;  completion over OCX methods and properties.
;;  IDE integration
;;  Change behaviour of ESC-q to recognise words used as paragraph
;;  titles and prevent them being dragged into the previous
;;  paragraph.
;;  etc.

;;; Code:

;; グローバル変数 features のリストに keyence-script-mode を追加する。
(provide 'keyence-script-mode) 

;; keyence-script-xemacs-p を変数とし、初期値を設定する。
(defvar
  keyence-script-xemacs-p (string-match "XEmacs\\|Lucid" (emacs-version)))

;; keyence-script-winemacs-p を変数とし、初期値を設定する。
(defvar keyence-script-winemacs-p (string-match "Win-Emacs" (emacs-version)))

;; keyence-script-win32-p を変数とし、初期値を設定する。
(defvar keyence-script-win32-p (eq window-system 'w32))

;; カスタマイズ用変数
					
(defvar ; デフォルトのインデントカラム数
  keyence-script-mode-indent 4 "*Default indentation per nesting level.")

					
(defvar ; テキストの構文に従ってフェイスを使って強調表示するかどうか
  keyence-script-fontify-p t "*Whether to fontify Basic buffers.")

(defvar ; BASIC 予約語をキャピタライズするかどうか
  keyence-script-capitalize-keywords-p nil
  "*Whether to capitalize BASIC keywords.")

(defvar ; BASIC ソースコードのワイルドカード
  keyence-script-wild-files "*.scp"
  "*Wildcard pattern for BASIC source files.")
					; 
(defvar ; Visual Basic exe ファイルがもしあれば、そのフルパス名
  keyence-script-ide-pathname nil
  "*The full pathname of your Visual Basic exe file, if any.")

(defvar ; 1 行 If 文のみ
  keyence-script-allow-single-line-if nil
  "*Whether to allow single line if")

;; 関数定義のテンプレート
(defvar keyence-script-defn-templates
  (list "Public Sub ()\nEnd Sub\n\n"
	"Public Function () As Variant\nEnd Function\n\n"
	"Public Property Get ()\nEnd Property\n\n")
  "*List of function templates though which keyence-script-new-sub cycles.")

;; keyence-script-imenu-generic-expression を変数とし、初期値を設定する。
(defvar keyence-script-imenu-generic-expression '())

;; keyence-script-mode-syntax-table を変数とし、初期値を設定する。
(defvar keyence-script-mode-syntax-table nil)

;; keyence-script-mode-syntax-table が空なら、設定する。
(if keyence-script-mode-syntax-table
    ()
  (setq keyence-script-mode-syntax-table (make-syntax-table))

  ;; Comment starter
  (modify-syntax-entry ?/ ". 124b" keyence-script-mode-syntax-table)
  (modify-syntax-entry ?* ". 23"   keyence-script-mode-syntax-table)

  (modify-syntax-entry ?\^m "> b" keyence-script-mode-syntax-table)
  (modify-syntax-entry ?\n  "> b" keyence-script-mode-syntax-table)
  (modify-syntax-entry ?\\  "w"	  keyence-script-mode-syntax-table)
  (modify-syntax-entry ?\=  "."	  keyence-script-mode-syntax-table)
  (modify-syntax-entry ?\<  "."	  keyence-script-mode-syntax-table)

  ;; Make =, etc., punctuation so that dynamic abbreviations work properly
  (modify-syntax-entry ?\> "." keyence-script-mode-syntax-table))


;; keyence-script-mode-map を変数とし、初期値を設定する。
(defvar keyence-script-mode-map nil)

;; keyence-script-mode-map が空なら、設定する
(if keyence-script-mode-map
    ()
  (setq keyence-script-mode-map (make-sparse-keymap))
  (define-key keyence-script-mode-map "\t" 'keyence-script-indent-line)
  (define-key keyence-script-mode-map "\r" 'keyence-script-newline-and-indent)

  (define-key
    keyence-script-mode-map "\M-\C-a" 'keyence-script-beginning-of-defun)

  (define-key keyence-script-mode-map "\M-\C-e"  'keyence-script-end-of-defun)
  (define-key keyence-script-mode-map "\M-\C-h"  'keyence-script-mark-defun)
  (define-key keyence-script-mode-map "\M-\C-\\" 'keyence-script-indent-region)
  (define-key keyence-script-mode-map "\M-q"     'keyence-script-fill-or-indent)
  (define-key keyence-script-mode-map "\M-\C-j"  'keyence-script-split-line)

  (cond
   (keyence-script-winemacs-p
    (define-key keyence-script-mode-map '(control C) 'keyence-script-start-ide))
   (keyence-script-win32-p
    (define-key
      keyence-script-mode-map (read "[?\\S-\\C-c]") 'keyence-script-start-ide)))

  (if keyence-script-xemacs-p
      (progn
	(define-key keyence-script-mode-map "\M-G" 'keyence-script-grep)

	(define-key
	  keyence-script-mode-map '(meta backspace) 'backward-kill-word)

	(define-key
	  keyence-script-mode-map '(control meta /) 'keyence-script-new-sub))))


;; これらの abbrevs をコード文脈でのみ有効とするか
(defvar keyence-script-mode-abbrev-table nil)

;; keyence-script-mode-hook を変数とし、初期値を設定する。
(defvar keyence-script-mode-hook ())

;; Is there a way to case-fold all regexp matches?
;; Change KJW Add enum, , change matching from 0 or more to zero or
;; one for public etc.
(defconst keyence-script-package-start-regexp "^[ \t]*[Pp]ackage")
    

; keyence-script-defun-start-regexp を変数とし、初期値を設定する。
(defconst keyence-script-defun-start-regexp
  "^[ \t]*[Mm]ethod[ \t]+\\(\\w+\\)[ \t]*(?")

(defconst
  keyence-script-defun-end-regexp "^[ \t]*[Ee]nd \\(Method\\|Package\\)")

;; Includes the compile-time #if variation.
;; KJW fixed if to require a whitespace so as to avoid matching, for
;; instance, iFileName and to require then.

;; Two versions; one recognizes single line if just as though it were
;; a multi-line and the other does not.	 Modified again to remove the
;; requirement for then so as to allow it to match if statements that
;; have continuations.
;;(defconst keyence-script-if-regexp
;;   "^[ \t]*#?[Ii]f[ \t]+.*[ \t]+[Tt]hen[ \t]*.*\\('\\|$\\)")
(defconst keyence-script-if-regexp
   "^[ \t]*#?[Ii]f[ \t]+.*[ \t_]+")

(defconst keyence-script-ifthen-regexp "^[ \t]*#?[Ii]f.+\\<[Tt]hen\\>\\s-\\S-+")

(defconst keyence-script-else-regexp "^[ \t]*#?[Ee]lse\\([Ii]f\\)?")
(defconst keyence-script-endif-regexp "[ \t]*#?[Ee]nd[ \t]*[Ii]f")

;;;(defconst keyence-script-continuation-regexp "^.*\_[ \t]*$")

(eval-and-compile
  (defconst keyence-script-label-regexp "^[ \t]*[a-zA-Z0-9_]+:$"))

(defconst keyence-script-select-regexp "^[ \t]*[Ss]elect[ \t]+[Cc]ase")
(defconst keyence-script-case-regexp "^[ \t]*[Cc]ase")
(defconst keyence-script-select-end-regexp "^[ \t]*[Ee]nd[ \t]+[Ss]elect")


(defconst keyence-script-for-regexp "^[ \t]*[Ff]or\\b")
(defconst keyence-script-next-regexp "^[ \t]*[Nn]ext\\b")

(defconst keyence-script-do-regexp "^[ \t]*[Dd]o\\b")
(defconst keyence-script-loop-regexp "^[ \t]*[Ll]oop\\b")

(defconst keyence-script-while-regexp "^[ \t]*[Ww]hile\\b")
(defconst keyence-script-wend-regexp "^[ \t]*[Ww]end\\b")

;; Added KJW Begin..end for forms
(defconst keyence-script-begin-regexp "^[ \t]*[Bb]egin)?")
;; This has created a bug.  End on its own in code should not outdent.
;; How can we fix this?	 They are used in separate Lisp expressions so
;; add another one.
(defconst keyence-script-end-begin-regexp "^[ \t]*[Ee]nd")

(defconst keyence-script-with-regexp "^[ \t]*[Ww]ith\\b")
(defconst keyence-script-end-with-regexp "^[ \t]*[Ee]nd[ \t]?[Ww]ith\\b")

(defconst keyence-script-blank-regexp "^[ \t]*$")
(defconst keyence-script-comment-regexp "^[ \t]*\\s<.*$")


;; This is some approximation of the set of reserved words in Visual Basic.
(eval-and-compile
  (defvar keyence-script-all-keywords
  '("Add" "addNS" "addOn" "Aggregate" "And" "App" "AppActivate" "Application"
    "Array" "As" "Asc" "AscB" "Atn" "Attribute"
    "Beep" "Begin" "BeginTrans" "Boolean" "ByVal" "ByRef"
    "Catch" "CBool" "CByte" "CCur"
    "CDate" "CDbl" "CInt" "CLng" "CSng" "CStr" "CVErr" "CVar" "Call"
    "Case" "ChDir" "ChDrive" "Character" "Choose" "Chr" "ChrB"
    "ClassModule" "Clear" "Clipboard" "Close" "Collection" "Column" "Columns"
    "Command" "CommitTrans" "CompactDatabase" "Component" "Components"
    "Const" "Container" "Containers" "Cos" "CreateDatabase" "CreateObject"
    "CurDir" "Currency"
    "data" "Database" "Databases" "Date" "DateAdd" "DateDiff" "DatePart"
    "DateSerial" "DateValue" "Day" "DBEngine" "DDB" "DebugOut" "decimal"
    "Declare" "Deftype" "DeleteSetting" "Dim" "Dir" "Do" "DoEvents" "Domain"
    "Double" "DrawBox" "Dynaset"
    "Each" "editTitle" "Else" "enable" "enableKeyInput" "End" "EndWith"
    "EndIf" "EndPackage" "EndProperty" "Enum" "Environ" "EOF" "eq" "Erase" "Err"
    "Exec" "Exit" "Exp"
    "False" "Fbreak" "Field" "Fields" "FileAttr" "FileCopy" "FileDateTime"
    "FileLen" "fileName" "Fix" "font" "fontSize" "fontGapx" "fontGapy" "For"
    "Form" "FormTemplate" "Format" "Forms" "FreeFile" "FreeLocks" "Friend"
    "Function" "FV"
    "GetAllSettings" "GetAttr" "GetData" "GetFirst" "GetObject" "GetSetting"
    "Global" "GoSub" "GoTo" "Group" "Groups" "gtin"
    "Hex" "Hour"
    "IIf" "IMEStatus" "IPmt" "IRR" "If" "Image" "Implements" "InStr" "Include"
    "includeCD" "includeStartChar" "Input" "Int" "inputAreaSize" "Integer"
    "inverse" "IsArray" "IsDate" "IsEmpty" "IsError" "IsMissing" "IsNull"
    "IsNumeric" "IsObject"
    "keyNum" "KeyWait" "Kill"
    "LBound" "LCase" "Left" "LOF" "LSet" "LTrim" "Len" "Let" "Like"
    "Load" "LoadPicture" "LoadResData" "LoadResPicture"
    "LoadResString" "Loc" "Log" "Long" "Loop"
    "max" "maxLength" "maxValue" "MDIForm" "Me" "MenuItems" "MenuLine" "Method"
    "Mid" "MIRR" "min" "minLength" "minValue" "Minute" "MkDir" "Month" "MsgBox"
    "multiColumn"
    "New" "Next" "nil" "Not" "Nothing" "Now" "NPer" "NPV"
    "Object" "Oct" "On" "Open" "OpenDatabase" "Option" "Optional" "Or"
    "OutputText"
    "PPmt" "PV" "Package" "Parameter" "Parameters" "Partition" "Picture" "Pmt"
    "posx" "posy" "prefix" "Printer" "Printers" "Private" "ProjectTemplate"
    "Property" "Properties" "Public" "Put"
    "QBColor" "QueryDef" "QueryDefs"
    "RSet" "RTrim" "Randomize" "Rate" "ReDim" "Recordset" "Recordsets"
    "RegisterDatabase" "Relation" "Relations" "Rem" "RepairDatabase"
    "Reset" "ResetColor" "Resume" "Return" "reverse" "Right" "RmDir" "Rnd"
    "Rollback" "row" "RowBuffer"
    "SavePicture" "SaveSetting" "scanMode" "scanType2D" "Second" "Seek"
    "SelBookmarks" "Select" "SelectedComponents" "SendKeys" "separator"
    "SetAttr" "SetColor" "SetDataAccessOption" "SetDefaultWorkspace" "SetKey"
    "Sgn" "Shell" "shift" "ShowMessageBox" "Sin" "Single" "size" "SLN"
    "Snapshot" "Space" "Sqr" "Static" "Step" "Stop" "Str" "StrComp" "StrConv"
    "String" "Sub" "SubMenu" "Switch" "SYD" 
    "Tab" "Table" "TableDef" "TableDefs" "Tan" "Then" "Time" "timeOut"
    "TimeSerial" "TimeValue" "Timer" "To" "Trim" "True" "Type" "TypeName"
    "typeofCD"
    "UBound" "UCase" "Unload" "update" "useCalculator" "useCD" "useEdit"
    "Val" "Variant" "VarType" "Verb"
    "wakeupOn" "Wbreak" "Wcontinue" "Weekday" "Wend" "While" "With" "Workspace"
    "Workspaces" "Write"
    "Year")))

(defvar keyence-script-font-lock-keywords-1
  (eval-when-compile
    (list
     ;; Names of functions.
;;;	(list keyence-script-defun-start-regexp
;;;	      '(1 font-lock-keyword-face nil t)
;;;	      '(2 font-lock-keyword-face nil t)
;;;	      '(3 font-lock-function-name-face))
     (list keyence-script-defun-start-regexp
	   '(1 font-lock-function-name-face))

     ;; Statement labels
     (cons keyence-script-label-regexp 'font-lock-keyword-face)

     ;; Case values
     ;; String-valued cases get font-lock-string-face regardless.
     (list "^[ \t]*case[ \t]+\\([^'\n]+\\)" 1 'font-lock-keyword-face t)

     ;; Any keywords you like.
     (list (concat "\\<" (regexp-opt
			  '("Dim" "If" "Then" "Else" "ElseIf" "End If") t)
		   "\\>")
	   1 'font-lock-keyword-face))))

(defvar keyence-script-font-lock-keywords-2
  (append keyence-script-font-lock-keywords-1
	  (eval-when-compile
	    `((,(concat "\\<" (regexp-opt keyence-script-all-keywords t) "\\>")
		   1 font-lock-keyword-face)))))

(defvar keyence-script-font-lock-keywords keyence-script-font-lock-keywords-1)


(put 'keyence-script-mode 'font-lock-keywords 'keyence-script-font-lock-keywords)

(defun keyence-script-mode ()
  "A mode for editing Microsoft Visual Basic programs.
Features automatic indentation, font locking, keyword capitalization,
and some minor convenience functions.
Commands:
\\{keyence-script-mode-map}"
  (interactive)
  (kill-all-local-variables)
  (use-local-map keyence-script-mode-map)
  (setq major-mode 'keyence-script-mode)
  (setq mode-name "KEYENCE Script")
  (set-syntax-table keyence-script-mode-syntax-table)

;'  (add-hook 'local-write-file-hooks 'keyence-script-untabify)

  (setq local-abbrev-table keyence-script-mode-abbrev-table)
  (if keyence-script-capitalize-keywords-p
      (progn
	(make-local-variable 'pre-abbrev-expand-hook)
	(add-hook 'pre-abbrev-expand-hook
		  'keyence-script-pre-abbrev-expand-hook)
	(abbrev-mode 1)))

  (make-local-variable 'comment-start)
;  (setq comment-start "' ")
  (setq comment-start "/* ")
  (make-local-variable 'comment-start-skip)
;  (setq comment-start-skip "//+ *")
  (setq comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
  (make-local-variable 'comment-column)
  (setq comment-column 40)
  (make-local-variable 'comment-end)
  (setq comment-end " */")

  (make-local-variable 'indent-line-function)
  (setq indent-line-function 'keyence-script-indent-line)

  (if keyence-script-fontify-p
      (keyence-script-enable-font-lock))

  (make-local-variable 'imenu-generic-expression)
  (setq imenu-generic-expression keyence-script-imenu-generic-expression)

  (set (make-local-variable 'imenu-syntax-alist) `((,(string-to-char "_") .
						    "w")))
  (set (make-local-variable 'imenu-case-fold-search) t)

  (setq tab-width 4)

  ;;(make-local-variable 'keyence-script-associated-files)
  ;; doing this here means we need not check to see if it is bound later.
  (add-hook 'find-file-hooks 'keyence-script-load-associated-files)

  (run-hooks 'keyence-script-mode-hook))


(defun keyence-script-enable-font-lock ()
  ;; Emacs 19.29 requires a window-system else font-lock-mode errs out.
  (cond ((or keyence-script-xemacs-p window-system)

	 ;; In win-emacs this sets font-lock-keywords back to nil!
	 (if keyence-script-winemacs-p
	     (font-lock-mode 1))

	 ;; Accomodate emacs 19.29+
	 ;; From: Simon Marshall <Simon.Marshall@esrin.esa.it>
	 (cond ((boundp 'font-lock-defaults)
		(make-local-variable 'font-lock-defaults)
		(setq font-lock-defaults
		      `((keyence-script-font-lock-keywords
			 keyence-script-font-lock-keywords-1
			 keyence-script-font-lock-keywords-2)
			nil t ((,(string-to-char "_") . "w")))))
	       (t
		(make-local-variable 'font-lock-keywords)
		(setq font-lock-keywords keyence-script-font-lock-keywords)))

	 (if keyence-script-winemacs-p
	     (font-lock-fontify-buffer)
	   (font-lock-mode 1)))))

;; KJW should add some odds and bobs here to cover "end if" one way
;; could be to create the abbreviations by removing whitespace then we
;; could put "end if", "end with" and so on in the keyword table
;; Another idea would be to make it intelligent enough to substitute
;; the correct end for the construct (with, select, if)
;; Is this what the abbrev table hook entry is for?
(defun keyence-script-construct-keyword-abbrev-table ()
  (if keyence-script-mode-abbrev-table
      nil
    (let ((words keyence-script-all-keywords)
	  (word nil)
	  (list nil))
      (while words
	(setq word (car words)
	      words (cdr words))
	(setq list (cons (list (downcase word) word) list)))

      (define-abbrev-table 'keyence-script-mode-abbrev-table list))))

;; Would like to do this at compile-time.
(keyence-script-construct-keyword-abbrev-table)


(defun keyence-script-in-code-context-p ()
  (if (fboundp 'buffer-syntactic-context) ; XEmacs function.
      (null (buffer-syntactic-context))
    ;; Attempt to simulate buffer-syntactic-context
    ;; I don't know how reliable this is.
    (let* ((beg (save-excursion
		  (beginning-of-line)
		  (point)))
	   (list
	    (parse-partial-sexp beg (point))))
      (and (null (nth 3 list))		; inside string.
	   (null (nth 4 list))))))	; inside comment


(defun keyence-script-pre-abbrev-expand-hook ()
  ;; Allow our abbrevs only in a code context.
  (setq local-abbrev-table
	(if (keyence-script-in-code-context-p)
	    keyence-script-mode-abbrev-table)))


(defun keyence-script-newline-and-indent (&optional count)
  "Insert a newline, updating indentation."
  (interactive)
  (expand-abbrev)
  (save-excursion
    (keyence-script-indent-line))
  (call-interactively 'newline-and-indent))

(defun keyence-script-beginning-of-defun ()
  (interactive)
  (re-search-backward keyence-script-defun-start-regexp))

(defun keyence-script-end-of-defun ()
  (interactive)
  (re-search-forward keyence-script-defun-end-regexp))

(defun keyence-script-mark-defun ()
  (interactive)
  (beginning-of-line)
  (keyence-script-end-of-defun)
  (set-mark (point))
  (keyence-script-beginning-of-defun)
  (if keyence-script-xemacs-p
      (zmacs-activate-region)))

(defun keyence-script-indent-defun ()
  (interactive)
  (save-excursion
    (keyence-script-mark-defun)
    (call-interactively 'keyence-script-indent-region)))


(defun keyence-script-fill-long-comment ()
  "Fills block of comment lines around point."
  ;; Derived from code in ilisp-ext.el.
  (interactive)
  (save-excursion
    (beginning-of-line)
    (let ((comment-re "^[ \t]*\\s<+[ \t]*"))
      (if (looking-at comment-re)
	  (let ((fill-prefix
		 (buffer-substring
		  (progn (beginning-of-line) (point))
		  (match-end 0))))

	    (while (and (not (bobp))
			(looking-at keyence-script-comment-regexp))
	      (forward-line -1))
	    (if (not (bobp)) (forward-line 1))

	    (let ((start (point)))

	      ;; Make all the line prefixes the same.
	      (while (and (not (eobp))
			  (looking-at comment-re))
		(replace-match fill-prefix)
		(forward-line 1))

	      (if (not (eobp))
		  (beginning-of-line))

	      ;; Fill using fill-prefix
	      (fill-region-as-paragraph start (point))))))))


(defun keyence-script-fill-or-indent ()
  "Fill long comment around point, if any, else indent current definition."
  (interactive)
  (cond ((save-excursion
	   (beginning-of-line)
	   (looking-at keyence-script-comment-regexp))
	 (keyence-script-fill-long-comment))
	(t
	 (keyence-script-indent-defun))))


(defun keyence-script-new-sub ()
  "Insert template for a new subroutine.  Repeat to cycle through alternatives."
  (interactive)
  (beginning-of-line)
  (let ((templates (cons keyence-script-blank-regexp
			 keyence-script-defn-templates))
	(tem nil)
	(bound (point)))
    (while templates
      (setq tem (car templates)
	    templates (cdr templates))
      (cond ((looking-at tem)
	     (replace-match (or (car templates)
				""))
	     (setq templates nil))))

    (search-backward "()" bound t)))


;(defun keyence-script-untabify ()
;  "Do not allow any tabs into the file."
;  (if (eq major-mode 'keyence-script-mode)
;      (untabify (point-min) (point-max)))
;  nil)

(defun keyence-script-default-tag ()
  (if (and (not (bobp))
	   (save-excursion
	     (backward-sexp)
	     (looking-at "\\w")))
      (backward-word 1))
  (let ((s (point))
	(e (save-excursion
	     (forward-sexp)
	     (point))))
    (buffer-substring s e)))

(defun keyence-script-grep (tag)
  "Search BASIC source files in current directory for TAG."
  (interactive
   (list (let* ((def (keyence-script-default-tag))
		(tag (read-string
		      (format "Grep for [%s]: " def))))
	   (if (string= tag "") def tag))))
  (grep (format "grep -n %s %s" tag keyence-script-wild-files)))


;;; IDE Connection.

(defun keyence-script-buffer-project-file ()
  "Return a guess as to the project file associated with the current buffer."
  (car (directory-files (file-name-directory (buffer-file-name)) t "\\.vbp")))

(defun keyence-script-start-ide ()
  "Start Visual Basic (or your favorite IDE, (after Emacs, of course))
on the first project file in the current directory.
Note: it's not a good idea to leave Visual Basic running while you
are editing in Emacs, since Visual Basic has no provision for reloading
changed files."
  (interactive)
  (let (file)
    (cond ((null keyence-script-ide-pathname)
	   (error "No pathname set for Visual Basic.  See keyence-script-ide-pathname"))
	  ((null (setq file (keyence-script-buffer-project-file)))
	   (error "No project file found"))
	  ((fboundp 'win-exec)
	   (iconify-emacs)
	   (win-exec keyence-script-ide-pathname 'win-show-normal file))
	  ((fboundp 'start-process)
	   (iconify-frame (selected-frame))
	   (start-process "*VisualBasic*" nil keyence-script-ide-pathname file))
	  (t
	   (error "No way to spawn process!")))))



;;; Indentation-related stuff.

(defun keyence-script-indent-region (start end)
  "Perform keyence-script-indent-line on each line in region."
  (interactive "r")
  (save-excursion
    (goto-char start)
    (beginning-of-line)
    (while (and (not (eobp))
		(< (point) end))
      (if (not (looking-at keyence-script-blank-regexp))
	  (keyence-script-indent-line))
      (forward-line 1)))

  (cond ((fboundp 'zmacs-deactivate-region)
	 (zmacs-deactivate-region))
	((fboundp 'deactivate-mark)
	 (deactivate-mark))))



(defun keyence-script-previous-line-of-code ()
  (if (not (bobp))
      (forward-line -1))	; previous-line depends on goal column
  (while (and (not (bobp))
	      (or (looking-at keyence-script-blank-regexp)
		  (looking-at keyence-script-comment-regexp)))
    (forward-line -1)))


;;;(defun keyence-script-find-original-statement ()
;;;  "If the current line is a continuation, move back to the original stmt."
;;;  (let ((here (point)))
;;;    (keyence-script-previous-line-of-code)
;;;    (while (and (not (bobp))
;;;		   (looking-at keyence-script-continuation-regexp))
;;;	 (setq here (point))
;;;	 (keyence-script-previous-line-of-code))
;;;    (goto-char here)))

(defun keyence-script-find-matching-stmt (open-regexp close-regexp)
  ;; Searching backwards
  (let ((level 0))
    (while (and (>= level 0) (not (bobp)))
      (keyence-script-previous-line-of-code)
;;;;	  (keyence-script-find-original-statement)
      (cond ((looking-at close-regexp)
	     (setq level (+ level 1)))
	    ((looking-at open-regexp)
	     (setq level (- level 1)))))))

(defun keyence-script-find-matching-if ()
  (keyence-script-find-matching-stmt keyence-script-if-regexp
				   keyence-script-endif-regexp))

(defun keyence-script-find-matching-select ()
  (keyence-script-find-matching-stmt keyence-script-select-regexp
				   keyence-script-select-end-regexp))

(defun keyence-script-find-matching-for ()
  (keyence-script-find-matching-stmt keyence-script-for-regexp
				   keyence-script-next-regexp))

(defun keyence-script-find-matching-do ()
  (keyence-script-find-matching-stmt keyence-script-do-regexp
				   keyence-script-loop-regexp))

(defun keyence-script-find-matching-while ()
  (keyence-script-find-matching-stmt keyence-script-while-regexp
				   keyence-script-wend-regexp))

(defun keyence-script-find-matching-with ()
  (keyence-script-find-matching-stmt keyence-script-with-regexp
				   keyence-script-end-with-regexp))

;;; If this fails it must return the indent of the line preceding the
;;; end not the first line because end without matching begin is a
;;; normal simple statement
(defun keyence-script-find-matching-begin ()
  (let ((original-point (point)))
    (keyence-script-find-matching-stmt keyence-script-begin-regexp
				     keyence-script-end-begin-regexp)
    (if (bobp) ;failed to find a matching begin so assume that it is
	       ;an end statement instead and use the indent of the
	       ;preceding line.
	(progn (goto-char original-point)
	       (keyence-script-previous-line-of-code)))))


(defun keyence-script-calculate-indent ()
  (let ((original-point (point)))
    (save-excursion
      (beginning-of-line)
      ;; Some cases depend only on where we are now.
      (cond ((or (looking-at keyence-script-package-start-regexp)
;		 (looking-at keyence-script-defun-start-regexp)
		 (looking-at keyence-script-label-regexp)
;		 (looking-at keyence-script-defun-end-regexp)
		 )
	     0)

	    ((looking-at keyence-script-defun-end-regexp)
	     (current-indentation))

	    ;; The outdenting stmts, which simply match their original.
	    ((or (looking-at keyence-script-else-regexp)
		 (looking-at keyence-script-endif-regexp))
	     (keyence-script-find-matching-if)
	     (current-indentation))

	    ;; All the other matching pairs act alike.
	    ((looking-at keyence-script-next-regexp) ; for/next
	     (keyence-script-find-matching-for)
	     (current-indentation))

	    ((looking-at keyence-script-loop-regexp) ; do/loop
	     (keyence-script-find-matching-do)
	     (current-indentation))

	    ((looking-at keyence-script-wend-regexp) ; while/wend
	     (keyence-script-find-matching-while)
	     (current-indentation))

	    ((looking-at keyence-script-end-with-regexp) ; with/end with
	     (keyence-script-find-matching-with)
	     (current-indentation))

					; select case/end select
	    ((looking-at keyence-script-select-end-regexp)
	     (keyence-script-find-matching-select)
	     (current-indentation))

	    ;; A case of a select is somewhat special.
	    ((looking-at keyence-script-case-regexp)
	     (keyence-script-find-matching-select)
;;;	     (+ (current-indentation) keyence-script-mode-indent))
	     (current-indentation))

	    ;; Added KJW: Make sure that this comes after the cases
	    ;; for if..endif, end select because end-regexp will also
	    ;; match "end select" etc.
;;;	       ((looking-at keyence-script-end-begin-regexp) ; begin/end
;;;		(keyence-script-find-matching-begin)
;;;		(current-indentation))
	    ((looking-at keyence-script-begin-regexp) ; begin
	     (current-indentation))
	    
	    (t
	     ;; Other cases which depend on the previous line.
	     (keyence-script-previous-line-of-code)

	     ;; Skip over label lines, which always have 0 indent.
	     (while (looking-at keyence-script-label-regexp)
	       (keyence-script-previous-line-of-code))

	     (cond
;;;		 ((looking-at keyence-script-continuation-regexp)
;;;		  (keyence-script-find-original-statement)
;;;		  ;; Indent continuation line under matching open paren,
;;;		  ;; or else one word in.
;;;		  (let* ((orig-stmt (point))
;;;			 (matching-open-paren
;;;			  (condition-case ()
;;;			      (save-excursion
;;;				(goto-char original-point)
;;;				(beginning-of-line)
;;;				(backward-up-list 1)
;;;				;; Only if point is now w/in cont. block.
;;;				(if (<= orig-stmt (point))
;;;				    (current-column)))
;;;			    (error nil))))
;;;		    (cond (matching-open-paren
;;;			   (1+ matching-open-paren))
;;;			  (t
;;;			   ;; Else, after first word on original line.
;;;			   (back-to-indentation)
;;;			   (forward-word 1)
;;;			   (while (looking-at "[ \t]")
;;;			     (forward-char 1))
;;;			   (current-column)))))
	      (t
;;;		  (keyence-script-find-original-statement)

	       (let ((indent (current-indentation)))
		 ;; All the various +indent regexps.
		 (cond ((looking-at keyence-script-package-start-regexp)
			(+ indent keyence-script-mode-indent))

		       ((and (looking-at keyence-script-defun-start-regexp)
			     (+ indent keyence-script-mode-indent)))

		       ((and (or (looking-at keyence-script-if-regexp)
				 (looking-at keyence-script-else-regexp))
			     (not (and keyence-script-allow-single-line-if
				       (looking-at keyence-script-ifthen-regexp))))
			(+ indent keyence-script-mode-indent))

		       ((or (looking-at keyence-script-select-regexp)
			    (looking-at keyence-script-case-regexp))
			(+ indent keyence-script-mode-indent))

		       ((or (looking-at keyence-script-do-regexp)
			    (looking-at keyence-script-for-regexp)
			    (looking-at keyence-script-while-regexp)
			    (looking-at keyence-script-with-regexp)
			    (looking-at keyence-script-begin-regexp)
			    )
			(+ indent keyence-script-mode-indent))

		       (t
			;; By default, just copy indent from prev line.
			indent))))))))))

(defun keyence-script-indent-to-column (col)
  (let* ((bol (save-excursion
		(beginning-of-line)
		(point)))
	 (point-in-whitespace
	  (<= (point) (+ bol (current-indentation))))
	 (blank-line-p
	  (save-excursion
	    (beginning-of-line)
	    (looking-at keyence-script-blank-regexp))))

    (cond ((/= col (current-indentation))
	   (save-excursion
	     (beginning-of-line)
	     (back-to-indentation)
	     (delete-region bol (point))
	     (indent-to col))))

    ;; If point was in the whitespace, move back-to-indentation.
    (cond (blank-line-p
	   (end-of-line))
	  (point-in-whitespace
	   (back-to-indentation)))))


(defun keyence-script-indent-line ()
  "Indent current line for BASIC."
  (interactive)
  (keyence-script-indent-to-column (keyence-script-calculate-indent)))


(defun keyence-script-split-line ()
  "Split line at point, adding continuation character or continuing a comment.
In Abbrev mode, any abbrev before point will be expanded."
  (interactive)
  (let ((pps-list (parse-partial-sexp (save-excursion
					(beginning-of-line)
					(point))
				      (point))))
    ;; Dispatch on syntax at this position.
    (cond ((equal t (nth 4 pps-list))  ; in comment
	   (indent-new-comment-line))
	  ((equal t (nth 4 pps-list))	; in string
	   (error "Can't break line inside a string"))
	  (t (just-one-space)		; leading space on next line
					; doesn't count, sigh
	     (insert "_")
	     (keyence-script-newline-and-indent)))))

(provide 'keyence-script-mode)


;;; Some experimental functions

;;; Load associated files listed in the file local variables block
(defun keyence-script-load-associated-files ()
  "Load files that are useful to have around when editing the source
of the file that has just been loaded.
The file must have a local variable that lists the files to be loaded.
If the file name is relative it is relative to the directory
containing the current buffer.	If the file is already loaded nothing
happens, this prevents circular references causing trouble.  After an
associated file is loaded its associated files list will be
processed."
  (if (boundp 'keyence-script-associated-files)
      (let ((files keyence-script-associated-files)
	    (file nil))
	(while files
	  (setq file (car files)
		files (cdr files))
	  (message "Load associated file: %s" file)
	  (keyence-script-load-file-ifnotloaded file default-directory)))))



(defun keyence-script-load-file-ifnotloaded (file default-directory)
  "Load file if not already loaded.
If file is relative then default-directory provides the path"
  (let((file-absolute (expand-file-name file default-directory)))
    ;; don't do anything if the buffer is already loaded
    (if (get-file-buffer file-absolute)
	()
      (find-file-noselect file-absolute ))))

;;; keyence-script-mode.el ends here