prolog.el 152 KB
Newer Older
1
;;; prolog.el --- major mode for editing and running Prolog (and Mercury) code
Eric S. Raymond's avatar
Eric S. Raymond committed
2

3
;; Copyright (C) 1986, 1987, 1997, 1998, 1999, 2002, 2003, 2011 Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
4

5 6 7 8 9
;; Authors: Emil Åström <emil_astrom(at)hotmail(dot)com>
;;          Milan Zamazal <pdm(at)freesoft(dot)cz>
;;          Stefan Bruda <stefan(at)bruda(dot)ca>  (current maintainer)
;;          * See below for more details
;; Keywords: prolog major mode sicstus swi mercury
Eric S. Raymond's avatar
Eric S. Raymond committed
10

11
(defvar prolog-mode-version "1.22"
12
  "Prolog mode version number.")
root's avatar
root committed
13

14 15 16
;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
root's avatar
root committed
17
;; it under the terms of the GNU General Public License as published by
18 19
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
root's avatar
root committed
20

21
;; GNU Emacs is distributed in the hope that it will be useful,
root's avatar
root committed
22 23 24 25 26
;; 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
27
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

;; Original author: Masanobu UMEDA <umerin(at)mse(dot)kyutech(dot)ac(dot)jp>
;; Parts of this file was taken from a modified version of the original
;; by Johan Andersson, Peter Olin, Mats Carlsson, Johan Bevemyr, Stefan
;; Andersson, and Per Danielsson (all SICS people), and Henrik Båkman
;; at Uppsala University, Sweden.
;;
;; Some ideas and also a few lines of code have been borrowed (not stolen ;-)
;; from Oz.el, the Emacs major mode for the Oz programming language,
;; Copyright (C) 1993 DFKI GmbH, Germany, with permission.
;; Authors: Ralf Scheidhauer and Michael Mehl ([scheidhr|mehl](at)dfki(dot)uni-sb(dot)de)
;;
;; More ideas and code have been taken from the SICStus debugger mode
;; (http://www.csd.uu.se/~perm/source_debug/index.shtml -- broken link
;; as of Mon May 5 08:23:48 EDT 2003) by Per Mildner.
;;
;; Additions for ECLiPSe and other helpful suggestions: Stephan Heuel
;; <heuel(at)ipb(dot)uni-bonn(dot)de>
root's avatar
root committed
46

47
;;; Commentary:
48 49 50 51 52 53 54
;;
;; This package provides a major mode for editing Prolog code, with
;; all the bells and whistles one would expect, including syntax
;; highlighting and auto indentation.  It can also send regions to an
;; inferior Prolog process.
;;
;; The code requires the comint, easymenu, info, imenu, and font-lock
55
;; libraries.  These are normally distributed with GNU Emacs and
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
;; XEmacs.

;;; Installation:
;;
;; Insert the following lines in your init file--typically ~/.emacs
;; (GNU Emacs and XEmacs <21.4), or ~/.xemacs/init.el (XEmacs
;; 21.4)--to use this mode when editing Prolog files under Emacs:
;;
;; (setq load-path (cons "/usr/lib/xemacs/site-lisp" load-path))
;; (autoload 'run-prolog "prolog" "Start a Prolog sub-process." t)
;; (autoload 'prolog-mode "prolog" "Major mode for editing Prolog programs." t)
;; (autoload 'mercury-mode "prolog" "Major mode for editing Mercury programs." t)
;; (setq prolog-system 'swi)  ; optional, the system you are using;
;;                            ; see `prolog-system' below for possible values
;; (setq auto-mode-alist (append '(("\\.pl$" . prolog-mode)
;;                                 ("\\.m$" . mercury-mode))
;;                                auto-mode-alist))
;;
;; where the path in the first line is the file system path to this file.
;; MSDOS paths can be written like "d:/programs/emacs-19.34/site-lisp". 
;; Note: In XEmacs, either `/usr/lib/xemacs/site-lisp' (RPM default in
;; Red Hat-based distributions) or `/usr/local/lib/xemacs/site-lisp'
;; (default when compiling from sources) are automatically added to
;; `load-path', so the first line is not necessary provided that you
;; put this file in the appropriate place.
;;
;; The last s-expression above makes sure that files ending with .pl
;; are assumed to be Prolog files and not Perl, which is the default
84
;; Emacs setting.  If this is not wanted, remove this line.  It is then
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
;; necessary to either
;;
;;  o  insert in your Prolog files the following comment as the first line:
;;
;;       % -*- Mode: Prolog -*-
;;
;;     and then the file will be open in Prolog mode no matter its 
;;     extension, or
;;
;;  o  manually switch to prolog mode after opening a Prolog file, by typing 
;;     M-x prolog-mode.
;;
;; If the command to start the prolog process ('sicstus', 'pl' or
;; 'swipl' for SWI prolog, etc.) is not available in the default path,
;; then it is necessary to set the value of the environment variable
;; EPROLOG to a shell command to invoke the prolog process.  In XEmacs
;; and Emacs 20+ you can also customize the variable
;; `prolog-program-name' (in the group `prolog-inferior') and provide
;; a full path for your Prolog system (swi, scitus, etc.).
;;
;; Note: I (Stefan, the current maintainer) work under XEmacs.  Future
;;   developments will thus be biased towards XEmacs (OK, I admit it,
;;   I am biased towards XEmacs in general), though I will do my best
;;   to keep the GNU Emacs compatibility.  So if you work under Emacs
;;   and see something that does not work do drop me a line, as I have
;;   a smaller chance to notice this kind of bugs otherwise.
111

112
;; Changelog:
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
;; Version 1.22:
;;  o  Allowed both 'swipl' and 'pl' as names for the SWI Prolog
;;     interpreter.
;;  o  Atoms that start a line are not blindly coloured as
;;     predicates.  Instead we check that they are followed by ( or
;;     :- first.  Patch suggested by Guy Wiener.
;; Version 1.21:
;;  o  Cleaned up the code that defines faces.  The missing face
;;     warnings on some Emacsen should disappear.
;; Version 1.20:
;;  o  Improved the handling of clause start detection and multi-line
;;     comments: `prolog-clause-start' no longer finds non-predicate
;;     (e.g., capitalized strings) beginning of clauses.
;;     `prolog-tokenize' recognizes when the end point is within a
;;     multi-line comment.
;; Version 1.19:
;;  o  Minimal changes for Aquamacs inclusion and in general for
;;     better coping with finding the Prolog executable.  Patch
;;     provided by David Reitter 
;; Version 1.18:
;;  o  Fixed syntax highlighting for clause heads that do not begin at
;;     the beginning of the line.
;;  o  Fixed compilation warnings under Emacs.
;;  o  Updated the email address of the current maintainer.
;; Version 1.17:
;;  o  Minor indentation fix (patch by Markus Triska)
;;  o  `prolog-underscore-wordchar-flag' defaults now to nil (more
;;     consistent to other Emacs modes)
;; Version 1.16:
;;  o  Eliminated a possible compilation warning.
;; Version 1.15:
;;  o  Introduced three new customizable variables: electric colon
;;     (`prolog-electric-colon-flag', default nil), electric dash
;;     (`prolog-electric-dash-flag', default nil), and a possibility
;;     to prevent the predicate template insertion from adding commata
;;     (`prolog-electric-dot-full-predicate-template', defaults to t
;;     since it seems quicker to me to just type those commata).  A
;;     trivial adaptation of a patch by Markus Triska.
;;  o  Improved the behaviour of electric if-then-else to only skip
;;     forward if the parenthesis/semicolon is preceded by
;;     whitespace.  Once more a trivial adaptation of a patch by
;;     Markus Triska.
;; Version 1.14:
157
;;  o  Cleaned up align code.  `prolog-align-flag' is eliminated (since
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
;;     on a second thought it does not do anything useful).  Added key
;;     binding (C-c C-a) and menu entry for alignment.
;;  o  Condensed regular expressions for lower and upper case
;;     characters (GNU Emacs seems to go over the regexp length limit
;;     with the original form).  My code on the matter was improved
;;     considerably by Markus Triska.
;;  o  Fixed `prolog-insert-spaces-after-paren' (which used an
;;     unitialized variable).
;;  o  Minor changes to clean up the code and avoid some implicit
;;     package requirements.
;; Version 1.13:
;;  o  Removed the use of `map-char-table' in `prolog-build-case-strings'
;;     which appears to cause prblems in (at least) Emacs 23.0.0.1.
;;  o  Added if-then-else indentation + corresponding electric
;;     characters.  New customization: `prolog-electric-if-then-else-flag'
;;  o  Align support (requires `align').  New customization:
;;     `prolog-align-flag'.
;;  o  Temporary consult files have now the same name throughout the
;;     session.  This prevents issues with reconsulting a buffer
;;     (this event is no longer passed to Prolog as a request to
;;     consult a new file).
;;  o  Adaptive fill mode is now turned on.  Comment indentation is
;;     still worse than it could be though, I am working on it.
;;  o  Improved filling and auto-filling capabilities.  Now block
;;     comments should be [auto-]filled correctly most of the time;
;;     the following pattern in particular is worth noting as being
;;     filled correctly:
;;         <some code here> % some comment here that goes beyond the
;;                          % rightmost column, possibly combined with
;;                          % subsequent comment lines
;;  o  `prolog-char-quote-workaround' now defaults to nil.
;;  o  Note: Many of the above improvements have been suggested by
;;     Markus Triska, who also provided useful patches on the matter
;;     when he realized that I was slow in responding.  Many thanks.
;; Version 1.11 / 1.12
;;  o  GNU Emacs compatibility fix for paragraph filling (fixed
;;     incorrectly in 1.11, fix fixed in 1.12).
;; Version 1.10
;;  o  Added paragraph filling in comment blocks and also correct auto
;;     filling for comments.
;;  o  Fixed the possible "Regular expression too big" error in
;;     `prolog-electric-dot'.
;; Version 1.9
;;  o  Parenthesis expressions are now indented by default so that
;;     components go one underneath the other, just as for compound
;;     terms.  You can use the old style (the second and subsequent
;;     lines being indented to the right in a parenthesis expression)
;;     by setting the customizable variable `prolog-paren-indent-p'
;;     (group "Prolog Indentation") to t.
;;  o  (Somehow awkward) handling of the 0' character escape
208
;;     sequence.  I am looking into a better way of doing it but
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
;;     prospects look bleak.  If this breaks things for you please let
;;     me know and also set the `prolog-char-quote-workaround' (group
;;     "Prolog Other") to nil.
;; Version 1.8
;;  o  Key binding fix.
;; Version 1.7
;;  o  Fixed a number of issues with the syntax of single quotes,
;;     including Debian bug #324520.
;; Version 1.6
;;  o  Fixed mercury mode menu initialization (Debian bug #226121).
;;  o  Fixed (i.e., eliminated) Delete remapping (Debian bug #229636).
;;  o  Corrected indentation for clauses defining quoted atoms.
;; Version 1.5:
;;  o  Keywords fontifying should work in console mode so this is
;;     enabled everywhere.
;; Version 1.4:
;;  o  Now supports GNU Prolog--minor adaptation of a patch by Stefan
;;     Moeding.
;; Version 1.3:
;;  o  Info-follow-nearest-node now called correctly under Emacs too
;;     (thanks to Nicolas Pelletier).  Should be implemented more
;;     elegantly (i.e., without compilation warnings) in the future.
;; Version 1.2:
;;  o  Another prompt fix, still in SWI mode (people seem to have
;;     changed the prompt of SWI Prolog).
;; Version 1.1:
;;  o  Fixed dots in the end of line comments causing indentation
;;     problems.  The following code is now correctly indented (note
;;     the dot terminating the comment):
;;        a(X) :- b(X),                   
;;            c(X).                  % comment here.
;;        a(X).
;;     and so is this (and variants):
;;        a(X) :- b(X),                   
243
;;            c(X).                  /* comment here.  */
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
;;        a(X).
;; Version 1.0:
;;  o  Revamped the menu system.
;;  o  Yet another prompt recognition fix (SWI mode).
;;  o  This is more of a renumbering than a new edition.  I promoted
;;     the mode to version 1.0 to emphasize the fact that it is now
;;     mature and stable enough to be considered production (in my
;;     opinion anyway).
;; Version 0.1.41:
;;  o  GNU Emacs compatibility fixes.
;; Version 0.1.40:
;;  o  prolog-get-predspec is now suitable to be called as
;;     imenu-extract-index-name-function.  The predicate index works.
;;  o  Since imenu works now as advertised, prolog-imenu-flag is t
;;     by default.
;;  o  Eliminated prolog-create-predicate-index since the imenu
;;     utilities now work well.  Actually, this function is also
;;     buggy, and I see no reason to fix it since we do not need it
;;     anyway.
;;  o  Fixed prolog-pred-start, prolog-clause-start, prolog-clause-info.
;;  o  Fix for prolog-build-case-strings; now prolog-upper-case-string
;;     and prolog-lower-case-string are correctly initialized, 
;;  o  Various font-lock changes; most importantly, block comments (/*
;;     ... */) are now correctly fontified in XEmacs even when they
;;     extend on multiple lines.
;; Version 0.1.36: 
;;  o  The debug prompt of SWI Prolog is now correctly recognized.
;; Version 0.1.35: 
;;  o  Minor font-lock bug fixes.


Eric S. Raymond's avatar
Eric S. Raymond committed
275 276
;;; Code:

277 278 279 280 281 282 283 284 285 286 287 288 289 290
(eval-when-compile
  (require 'compile)
  (require 'font-lock)
  ;; We need imenu everywhere because of the predicate index!
  (require 'imenu)
  ;)
  (require 'info)
  (require 'shell)
  )

(require 'comint)
(require 'easymenu)
(require 'align)

291

292
(defgroup prolog nil
293
  "Major modes for editing and running Prolog and Mercury files."
294 295
  :group 'languages)

296 297 298
(defgroup prolog-faces nil
  "Prolog mode specific faces."
  :group 'font-lock)
299

300 301
(defgroup prolog-indentation nil
  "Prolog mode indentation configuration."
302
  :group 'prolog)
root's avatar
root committed
303

304 305
(defgroup prolog-font-lock nil
  "Prolog mode font locking patterns."
306
  :group 'prolog)
root's avatar
root committed
307

308 309
(defgroup prolog-keyboard nil
  "Prolog mode keyboard flags."
310
  :group 'prolog)
root's avatar
root committed
311

312 313 314 315 316 317
(defgroup prolog-inferior nil
  "Inferior Prolog mode options."
  :group 'prolog)

(defgroup prolog-other nil
  "Other Prolog mode options."
318
  :group 'prolog)
root's avatar
root committed
319

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

;;-------------------------------------------------------------------
;; User configurable variables
;;-------------------------------------------------------------------

;; General configuration

(defcustom prolog-system nil
  "*Prolog interpreter/compiler used.
The value of this variable is nil or a symbol.
If it is a symbol, it determines default values of other configuration
variables with respect to properties of the specified Prolog
interpreter/compiler.

Currently recognized symbol values are:
eclipse - Eclipse Prolog
mercury - Mercury
sicstus - SICStus Prolog
swi     - SWI Prolog
gnu     - GNU Prolog"
  :group 'prolog
  :type '(choice (const :tag "SICStus" :value sicstus)
                 (const :tag "SWI Prolog" :value swi)
                 (const :tag "Default" :value nil)))
(make-variable-buffer-local 'prolog-system)

;; NB: This alist can not be processed in prolog-mode-variables to
;; create a prolog-system-version-i variable since it is needed
;; prior to the call to prolog-mode-variables.
(defcustom prolog-system-version
  '((sicstus  (3 . 6))
    (swi      (0 . 0))
    (mercury  (0 . 0))
    (eclipse  (3 . 7))
    (gnu      (0 . 0)))
  "*Alist of Prolog system versions.
The version numbers are of the format (Major . Minor)."
357
  :group 'prolog)
root's avatar
root committed
358

359 360
;; Indentation

361
(defcustom prolog-indent-width 4
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
  "*The indentation width used by the editing buffer."
  :group 'prolog-indentation
  :type 'integer)  

(defcustom prolog-align-comments-flag t
  "*Non-nil means automatically align comments when indenting."
  :group 'prolog-indentation
  :type 'boolean)

(defcustom prolog-indent-mline-comments-flag t
  "*Non-nil means indent contents of /* */ comments.
Otherwise leave such lines as they are."
  :group 'prolog-indentation
  :type 'boolean)

(defcustom prolog-object-end-to-0-flag t
  "*Non-nil means indent closing '}' in SICStus object definitions to level 0.
Otherwise indent to `prolog-indent-width'."
  :group 'prolog-indentation
  :type 'boolean)

(defcustom prolog-left-indent-regexp "\\(;\\|\\*?->\\)"
  "*Regexp for character sequences after which next line is indented.
Next line after such a regexp is indented to the opening paranthesis level."
  :group 'prolog-indentation
  :type 'regexp)

(defcustom prolog-paren-indent-p nil
  "*If non-nil, increase indentation for parenthesis expressions.
The second and subsequent line in a parenthesis expression other than
a compound term can either be indented `prolog-paren-indent' to the
right (if this variable is non-nil) or in the same way as for compound
terms (if this variable is nil, default)."
  :group 'prolog-indentation
  :type 'boolean)

(defcustom prolog-paren-indent 4
  "*The indentation increase for parenthesis expressions.
Only used in ( If -> Then ; Else) and ( Disj1 ; Disj2 ) style expressions."
  :group 'prolog-indentation
  :type 'integer)

(defcustom prolog-parse-mode 'beg-of-clause
  "*The parse mode used (decides from which point parsing is done).
Legal values:
'beg-of-line   - starts parsing at the beginning of a line, unless the
408
                 previous line ends with a backslash.  Fast, but has
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
                 problems detecting multiline /* */ comments.
'beg-of-clause - starts parsing at the beginning of the current clause.
                 Slow, but copes better with /* */ comments."
  :group 'prolog-indentation
  :type '(choice (const :value beg-of-line)
                 (const :value beg-of-clause)))

;; Font locking

(defcustom prolog-keywords
  '((eclipse
     ("use_module" "begin_module" "module_interface" "dynamic"
      "external" "export" "dbgcomp" "nodbgcomp" "compile"))
    (mercury
     ("all" "else" "end_module" "equality" "external" "fail" "func" "if"
      "implementation" "import_module" "include_module" "inst" "instance"
      "interface" "mode" "module" "not" "pragma" "pred" "some" "then" "true"
      "type" "typeclass" "use_module" "where"))
    (sicstus
     ("block" "dynamic" "mode" "module" "multifile" "meta_predicate"
      "parallel" "public" "sequential" "volatile"))
    (swi
     ("discontiguous" "dynamic" "ensure_loaded" "export" "export_list" "import"
      "meta_predicate" "module" "module_transparent" "multifile" "require"
      "use_module" "volatile"))
    (gnu
     ("built_in" "char_conversion" "discontiguous" "dynamic" "ensure_linked"
      "ensure_loaded" "foreign" "include" "initialization" "multifile" "op"
      "public" "set_prolog_flag"))
    (t
     ("dynamic" "module")))
  "*Alist of Prolog keywords which is used for font locking of directives."
  :group 'prolog-font-lock
  :type 'sexp)

(defcustom prolog-types
  '((mercury
     ("char" "float" "int" "io__state" "string" "univ"))
    (t nil))
  "*Alist of Prolog types used by font locking."
  :group 'prolog-font-lock
  :type 'sexp)

(defcustom prolog-mode-specificators
  '((mercury
     ("bound" "di" "free" "ground" "in" "mdi" "mui" "muo" "out" "ui" "uo"))
    (t nil))
  "*Alist of Prolog mode specificators used by font locking."
  :group 'prolog-font-lock
  :type 'sexp)

(defcustom prolog-determinism-specificators
  '((mercury
     ("cc_multi" "cc_nondet" "det" "erroneous" "failure" "multi" "nondet"
      "semidet"))
    (t nil))
  "*Alist of Prolog determinism specificators used by font locking."
  :group 'prolog-font-lock
  :type 'sexp)

(defcustom prolog-directives
  '((mercury
     ("^#[0-9]+"))
    (t nil))
  "*Alist of Prolog source code directives used by font locking."
  :group 'prolog-font-lock
  :type 'sexp)


;; Keyboard

480
(defcustom prolog-electric-newline-flag (not (fboundp 'electric-indent-mode))
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
  "*Non-nil means automatically indent the next line when the user types RET."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-hungry-delete-key-flag nil
  "*Non-nil means delete key consumes all preceding spaces."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-electric-dot-flag nil
  "*Non-nil means make dot key electric.
Electric dot appends newline or inserts head of a new clause.
If dot is pressed at the end of a line where at least one white space
precedes the point, it inserts a recursive call to the current predicate.
If dot is pressed at the beginning of an empty line, it inserts the head
496
of a new clause for the current predicate.  It does not apply in strings
497 498 499 500 501 502 503
and comments. 
It does not apply in strings and comments."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-electric-dot-full-predicate-template nil
  "*If nil, electric dot inserts only the current predicate's name and `(' 
504
for recursive calls or new clause heads.  Non-nil means to also 
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
insert enough commata to cover the predicate's arity and `)', 
and dot and newline for recursive calls."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-electric-underscore-flag nil
  "*Non-nil means make underscore key electric.
Electric underscore replaces the current variable with underscore.
If underscore is pressed not on a variable then it behaves as usual."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-electric-tab-flag nil
  "*Non-nil means make TAB key electric.
Electric TAB inserts spaces after parentheses, ->, and ;
in ( If -> Then ; Else) and ( Disj1 ; Disj2 ) style expressions."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-electric-if-then-else-flag nil
525
  "*Non-nil makes `(', `>' and `;' electric
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
to automatically indent if-then-else constructs."
  :group 'prolog-keyboard
  :type 'boolean)
 
(defcustom prolog-electric-colon-flag nil
  "*Makes `:' electric (inserts `:-' on a new line).
If non-nil, pressing `:' at the end of a line that starts in 
the first column (i.e., clause heads) inserts ` :-' and newline."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-electric-dash-flag nil
  "*Makes `-' electric (inserts a `-->' on a new line).
If non-nil, pressing `-' at the end of a line that starts in
the first column (i.e., DCG heads) inserts ` -->' and newline."
  :group 'prolog-keyboard
  :type 'boolean)

(defcustom prolog-old-sicstus-keys-flag nil
  "*Non-nil means old SICStus Prolog mode keybindings are used."
  :group 'prolog-keyboard
  :type 'boolean)

;; Inferior mode

(defcustom prolog-program-name
  `(((getenv "EPROLOG") (eval (getenv "EPROLOG")))
    (eclipse "eclipse")
    (mercury nil)
    (sicstus "sicstus")
    (swi ,(if (not (executable-find "swipl")) "pl" "swipl"))
    (gnu "gprolog")
    (t ,(let ((names '("prolog" "gprolog" "swipl" "pl")))
 	  (while (and names
 		      (not (executable-find (car names))))
 	    (setq names (cdr names)))
 	  (or (car names) "prolog"))))
  "*Alist of program names for invoking an inferior Prolog with `run-prolog'."
  :group 'prolog-inferior
  :type 'sexp)

(defcustom prolog-program-switches
  '((sicstus ("-i"))
    (t nil))
  "*Alist of switches given to inferior Prolog run with `run-prolog'."
  :group 'prolog-inferior
  :type 'sexp)

(defcustom prolog-consult-string
  '((eclipse "[%f].")
    (mercury nil)
    (sicstus (eval (if (prolog-atleast-version '(3 . 7))
                       "prolog:zap_file(%m,%b,consult,%l)."
                     "prolog:zap_file(%m,%b,consult).")))
    (swi "[%f].")
    (gnu     "[%f].")
    (t "reconsult(%f)."))
  "*Alist of strings defining predicate for reconsulting.

Some parts of the string are replaced:
`%f' by the name of the consulted file (can be a temporary file)
`%b' by the file name of the buffer to consult
`%m' by the module name and name of the consulted file separated by colon
589
`%l' by the line offset into the file.  This is 0 unless consulting a
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
     region of a buffer, in which case it is the number of lines before
     the region."
  :group 'prolog-inferior
  :type 'sexp)

(defcustom prolog-compile-string
  '((eclipse "[%f].")
    (mercury "mmake ")
    (sicstus (eval (if (prolog-atleast-version '(3 . 7))
                       "prolog:zap_file(%m,%b,compile,%l)."
                     "prolog:zap_file(%m,%b,compile).")))
    (swi "[%f].")
    (t "compile(%f)."))
  "*Alist of strings and lists defining predicate for recompilation.

Some parts of the string are replaced:
`%f' by the name of the compiled file (can be a temporary file)
`%b' by the file name of the buffer to compile
`%m' by the module name and name of the compiled file separated by colon
609
`%l' by the line offset into the file.  This is 0 unless compiling a
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
     region of a buffer, in which case it is the number of lines before
     the region.

If `prolog-program-name' is non-nil, it is a string sent to a Prolog process.
If `prolog-program-name' is nil, it is an argument to the `compile' function."
  :group 'prolog-inferior
  :type 'sexp)

(defcustom prolog-eof-string "end_of_file.\n"
  "*Alist of strings that represent end of file for prolog.
nil means send actual operating system end of file."
  :group 'prolog-inferior
  :type 'sexp)

(defcustom prolog-prompt-regexp
  '((eclipse "^[a-zA-Z0-9()]* *\\?- \\|^\\[[a-zA-Z]* [0-9]*\\]:")
    (sicstus "| [ ?][- ] *")
    (swi "^\\(\\[[a-zA-Z]*\\] \\)?[1-9]?[0-9]*[ ]?\\?- \\|^| +")
    (t "^ *\\?-"))
  "*Alist of prompts of the prolog system command line."
  :group 'prolog-inferior
  :type 'sexp)

(defcustom prolog-continued-prompt-regexp
  '((sicstus "^\\(| +\\|     +\\)")
    (t "^|: +"))
  "*Alist of regexps matching the prompt when consulting `user'."
  :group 'prolog-inferior
  :type 'sexp)

(defcustom prolog-debug-on-string "debug.\n"
  "*Predicate for enabling debug mode."
  :group 'prolog-inferior
  :type 'string)

(defcustom prolog-debug-off-string "nodebug.\n"
  "*Predicate for disabling debug mode."
  :group 'prolog-inferior
  :type 'string)

(defcustom prolog-trace-on-string "trace.\n"
  "*Predicate for enabling tracing."
  :group 'prolog-inferior
  :type 'string)

(defcustom prolog-trace-off-string "notrace.\n"
  "*Predicate for disabling tracing."
  :group 'prolog-inferior
  :type 'string)

(defcustom prolog-zip-on-string "zip.\n"
  "*Predicate for enabling zip mode for SICStus."
  :group 'prolog-inferior
  :type 'string)

(defcustom prolog-zip-off-string "nozip.\n"
  "*Predicate for disabling zip mode for SICStus."
  :group 'prolog-inferior
  :type 'string)

(defcustom prolog-use-standard-consult-compile-method-flag t
  "*Non-nil means use the standard compilation method.
672
Otherwise the new compilation method will be used.  This
673 674 675 676 677
utilises a special compilation buffer with the associated
features such as parsing of error messages and automatically
jumping to the source code responsible for the error.

Warning: the new method is so far only experimental and
678
does contain bugs.  The recommended setting for the novice user
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
is non-nil for this variable."
  :group 'prolog-inferior
  :type 'boolean)


;; Miscellaneous

(defcustom prolog-use-prolog-tokenizer-flag t
  "*Non-nil means use the internal prolog tokenizer for indentation etc.
Otherwise use `parse-partial-sexp' which is faster but sometimes incorrect."
  :group 'prolog-other
  :type 'boolean)

(defcustom prolog-imenu-flag t
  "*Non-nil means add a clause index menu for all prolog files."
  :group 'prolog-other
  :type 'boolean)

(defcustom prolog-imenu-max-lines 3000
  "*The maximum number of lines of the file for imenu to be enabled.
Relevant only when `prolog-imenu-flag' is non-nil."
  :group 'prolog-other
  :type 'integer)

(defcustom prolog-info-predicate-index
  "(sicstus)Predicate Index"
  "*The info node for the SICStus predicate index."
  :group 'prolog-other
  :type 'string)

(defcustom prolog-underscore-wordchar-flag nil
  "*Non-nil means underscore (_) is a word-constituent character."
  :group 'prolog-other
  :type 'boolean)

(defcustom prolog-use-sicstus-sd nil
  "*If non-nil, use the source level debugger of SICStus 3#7 and later."
  :group 'prolog-other
  :type 'boolean)

(defcustom prolog-char-quote-workaround nil
720
  ;; FIXME: Use syntax-propertize-function to fix it right.
721 722 723 724 725 726 727 728 729 730
  "*If non-nil, declare 0 as a quote character so that 0'<char> does not break syntax highlighting.
This is really kludgy but I have not found any better way of handling it."
  :group 'prolog-other
  :type 'boolean)


;;-------------------------------------------------------------------
;; Internal variables
;;-------------------------------------------------------------------

731
;;(defvar prolog-temp-filename "")   ; Later set by `prolog-temporary-file'
732

733 734 735 736 737
(defvar prolog-mode-syntax-table
  (let ((table (make-syntax-table)))
    (if prolog-underscore-wordchar-flag
        (modify-syntax-entry ?_ "w" table)
      (modify-syntax-entry ?_ "_" table))
738

739 740 741 742 743 744 745
    (modify-syntax-entry ?+ "." table)
    (modify-syntax-entry ?- "." table)
    (modify-syntax-entry ?= "." table)
    (modify-syntax-entry ?< "." table)
    (modify-syntax-entry ?> "." table)
    (modify-syntax-entry ?| "." table)
    (modify-syntax-entry ?\' "\"" table)
746

747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    ;; Any better way to handle the 0'<char> construct?!?
    (when prolog-char-quote-workaround
      (modify-syntax-entry ?0 "\\" table))

    (modify-syntax-entry ?% "<" table)
    (modify-syntax-entry ?\n ">" table)
    (if (featurep 'xemacs)
        (progn
          (modify-syntax-entry ?* ". 67" table)
          (modify-syntax-entry ?/ ". 58" table)
          )
      ;; Emacs wants to see this it seems:
      (modify-syntax-entry ?* ". 23b" table)
      (modify-syntax-entry ?/ ". 14" table)
      )
    table))
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
(defvar prolog-mode-abbrev-table nil)
(defvar prolog-upper-case-string ""
  "A string containing all upper case characters.
Set by prolog-build-case-strings.")
(defvar prolog-lower-case-string ""
  "A string containing all lower case characters.
Set by prolog-build-case-strings.")
  
(defvar prolog-atom-char-regexp ""
  "Set by prolog-set-atom-regexps.")
;; "Regexp specifying characters which constitute atoms without quoting.")
(defvar prolog-atom-regexp ""
  "Set by prolog-set-atom-regexps.")

(defconst prolog-left-paren "[[({]" 
  "The characters used as left parentheses for the indentation code.")
(defconst prolog-right-paren "[])}]"
  "The characters used as right parentheses for the indentation code.")

(defconst prolog-quoted-atom-regexp
  "\\(^\\|[^0-9]\\)\\('\\([^\n']\\|\\\\'\\)*'\\)"
  "Regexp matching a quoted atom.")
(defconst prolog-string-regexp
  "\\(\"\\([^\n\"]\\|\\\\\"\\)*\"\\)"
  "Regexp matching a string.")
(defconst prolog-head-delimiter "\\(:-\\|\\+:\\|-:\\|\\+\\?\\|-\\?\\|-->\\)"
  "A regexp for matching on the end delimiter of a head (e.g. \":-\").")

(defvar prolog-compilation-buffer "*prolog-compilation*"
  "Name of the output buffer for Prolog compilation/consulting.")

(defvar prolog-temporary-file-name nil)
(defvar prolog-keywords-i nil)
(defvar prolog-types-i nil)
(defvar prolog-mode-specificators-i nil)
(defvar prolog-determinism-specificators-i nil)
(defvar prolog-directives-i nil)
(defvar prolog-program-name-i nil)
(defvar prolog-program-switches-i nil)
(defvar prolog-consult-string-i nil)
(defvar prolog-compile-string-i nil)
(defvar prolog-eof-string-i nil)
(defvar prolog-prompt-regexp-i nil)
(defvar prolog-continued-prompt-regexp-i nil)
(defvar prolog-help-function-i nil)

(defvar prolog-align-rules
  (eval-when-compile
    (mapcar
     (lambda (x)
       (let ((name (car x))
             (sym  (cdr x)))
         `(,(intern (format "prolog-%s" name))
           (regexp . ,(format "\\(\\s-*\\)%s\\(\\s-*\\)" sym))
           (tab-stop . nil)
           (modes . '(prolog-mode))
           (group . (1 2)))))
     '(("dcg" . "-->") ("rule" . ":-") ("simplification" . "<=>")
       ("propagation" . "==>")))))



;;-------------------------------------------------------------------
;; Prolog mode
;;-------------------------------------------------------------------

;; Example: (prolog-atleast-version '(3 . 6))
(defun prolog-atleast-version (version)
  "Return t if the version of the current prolog system is VERSION or later.
VERSION is of the format (Major . Minor)"
  ;; Version.major < major or
  ;; Version.major = major and Version.minor <= minor
  (let* ((thisversion (prolog-find-value-by-system prolog-system-version))
         (thismajor (car thisversion))
         (thisminor (cdr thisversion)))
    (or (< (car version) thismajor)
        (and (= (car version) thismajor)
             (<= (cdr version) thisminor)))
    ))

(define-abbrev-table 'prolog-mode-abbrev-table ())

(defun prolog-find-value-by-system (alist)
  "Get value from ALIST according to `prolog-system'."
  (if (listp alist)
      (let (result
            id)
        (while alist
          (setq id (car (car alist)))
          (if (or (eq id prolog-system)
                  (eq id t)
                  (and (listp id)
                       (eval id)))
              (progn
                (setq result (car (cdr (car alist))))
                (if (and (listp result)
                         (eq (car result) 'eval))
                    (setq result (eval (car (cdr result)))))
                (setq alist nil))
            (setq alist (cdr alist))))
        result)
    alist))
865

root's avatar
root committed
866
(defun prolog-mode-variables ()
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
  "Set some common variables to Prolog code specific values."
  (setq local-abbrev-table prolog-mode-abbrev-table)
  (make-local-variable 'paragraph-start)
  (setq paragraph-start (concat "[ \t]*$\\|" page-delimiter)) ;'%%..'
  (make-local-variable 'paragraph-separate)
  (setq paragraph-separate paragraph-start)
  (make-local-variable 'paragraph-ignore-fill-prefix)
  (setq paragraph-ignore-fill-prefix t)
  (make-local-variable 'normal-auto-fill-function)
  (setq normal-auto-fill-function 'prolog-do-auto-fill)
  (make-local-variable 'indent-line-function)
  (setq indent-line-function 'prolog-indent-line)
  (make-local-variable 'comment-start)
  (setq comment-start "%")
  (make-local-variable 'comment-end)
  (setq comment-end "")
  (make-local-variable 'comment-start-skip)
  ;; This complex regexp makes sure that comments cannot start
  ;; inside quoted atoms or strings
  (setq comment-start-skip 
        (format "^\\(\\(%s\\|%s\\|[^\n\'\"%%]\\)*\\)\\(/\\*+ *\\|%%+ *\\)" 
                prolog-quoted-atom-regexp prolog-string-regexp))
  (make-local-variable 'comment-column)
  (make-local-variable 'comment-indent-function)
  (setq comment-indent-function 'prolog-comment-indent)
  (make-local-variable 'parens-require-spaces)
  (setq parens-require-spaces nil)
  ;; Initialize Prolog system specific variables
  (let ((vars '(prolog-keywords prolog-types prolog-mode-specificators
                prolog-determinism-specificators prolog-directives
                prolog-program-name prolog-program-switches
                prolog-consult-string prolog-compile-string prolog-eof-string
                prolog-prompt-regexp prolog-continued-prompt-regexp
                prolog-help-function)))
    (while vars
      (set (intern (concat (symbol-name (car vars)) "-i"))
903
           (prolog-find-value-by-system (symbol-value (car vars))))
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
      (setq vars (cdr vars))))
  (when (null prolog-program-name-i)
        (make-local-variable 'compile-command)
        (setq compile-command prolog-compile-string-i))
  (make-local-variable 'font-lock-defaults)
  (setq font-lock-defaults
        '(prolog-font-lock-keywords nil nil ((?_ . "w"))))
)

(defun prolog-mode-keybindings-common (map)
  "Define keybindings common to both Prolog modes in MAP."
  (define-key map "\C-c?" 'prolog-help-on-predicate)
  (define-key map "\C-c/" 'prolog-help-apropos)
  (define-key map "\C-c\C-d" 'prolog-debug-on)
  (define-key map "\C-c\C-t" 'prolog-trace-on)
  (if (and (eq prolog-system 'sicstus)
           (prolog-atleast-version '(3 . 7)))
      (define-key map "\C-c\C-z" 'prolog-zip-on))
  (define-key map "\C-c\r" 'run-prolog))

(defun prolog-mode-keybindings-edit (map)
  "Define keybindings for Prolog mode in MAP."
  (define-key map "\M-a" 'prolog-beginning-of-clause)
  (define-key map "\M-e" 'prolog-end-of-clause)
  (define-key map "\M-q" 'prolog-fill-paragraph)
  (define-key map "\C-c\C-a" 'align)
  (define-key map "\C-\M-a" 'prolog-beginning-of-predicate)
  (define-key map "\C-\M-e" 'prolog-end-of-predicate)
  (define-key map "\M-\C-c" 'prolog-mark-clause)
  (define-key map "\M-\C-h" 'prolog-mark-predicate)
  (define-key map "\M-\C-n" 'prolog-forward-list)
  (define-key map "\M-\C-p" 'prolog-backward-list)
  (define-key map "\C-c\C-n" 'prolog-insert-predicate-template)
  (define-key map "\C-c\C-s" 'prolog-insert-predspec)
  (define-key map "\M-\r" 'prolog-insert-next-clause)
  (define-key map "\C-c\C-va" 'prolog-variables-to-anonymous)
  (define-key map "\C-c\C-v\C-s" 'prolog-view-predspec)

  (define-key map [Backspace] 'prolog-electric-delete)
  (define-key map "." 'prolog-electric-dot)
  (define-key map "_" 'prolog-electric-underscore)
  (define-key map "(" 'prolog-electric-if-then-else)
  (define-key map ";" 'prolog-electric-if-then-else)
  (define-key map ">" 'prolog-electric-if-then-else)
  (define-key map ":" 'prolog-electric-colon)
  (define-key map "-" 'prolog-electric-dash)
  (if prolog-electric-newline-flag 
      (define-key map "\r" 'newline-and-indent))

  ;; If we're running SICStus, then map C-c C-c e/d to enabling
  ;; and disabling of the source-level debugging facilities.
  ;(if (and (eq prolog-system 'sicstus)
  ;         (prolog-atleast-version '(3 . 7)))
  ;    (progn
  ;      (define-key map "\C-c\C-ce" 'prolog-enable-sicstus-sd)
  ;      (define-key map "\C-c\C-cd" 'prolog-disable-sicstus-sd)
  ;      ))

  (if prolog-old-sicstus-keys-flag
      (progn
        (define-key map "\C-c\C-c" 'prolog-consult-predicate)
        (define-key map "\C-cc" 'prolog-consult-region)
        (define-key map "\C-cC" 'prolog-consult-buffer)
        (define-key map "\C-c\C-k" 'prolog-compile-predicate)
        (define-key map "\C-ck" 'prolog-compile-region)
        (define-key map "\C-cK" 'prolog-compile-buffer))
    (define-key map "\C-c\C-p" 'prolog-consult-predicate)
    (define-key map "\C-c\C-r" 'prolog-consult-region)
    (define-key map "\C-c\C-b" 'prolog-consult-buffer)
    (define-key map "\C-c\C-f" 'prolog-consult-file)
    (define-key map "\C-c\C-cp" 'prolog-compile-predicate)
    (define-key map "\C-c\C-cr" 'prolog-compile-region)
    (define-key map "\C-c\C-cb" 'prolog-compile-buffer)
977 978 979 980 981 982
    (define-key map "\C-c\C-cf" 'prolog-compile-file))
  
  ;; Inherited from the old prolog.el.
  (define-key map "\e\C-x" 'prolog-consult-region)
  (define-key map "\C-c\C-l" 'prolog-consult-file)
  (define-key map "\C-c\C-z" 'switch-to-prolog))
983 984 985 986 987 988

(defun prolog-mode-keybindings-inferior (map)
  "Define keybindings for inferior Prolog mode in MAP."
  ;; No inferior mode specific keybindings now.
  )

989 990 991 992 993
(defvar prolog-mode-map
  (let ((map (make-sparse-keymap)))
    (prolog-mode-keybindings-common map)
    (prolog-mode-keybindings-edit map)
    map))
994 995 996 997
  

(defvar prolog-mode-hook nil
  "List of functions to call after the prolog mode has initialised.")
root's avatar
root committed
998

999 1000
(unless (fboundp 'prog-mode)
  (defalias 'prog-mode 'fundamental-mode))
Jim Blandy's avatar
Jim Blandy committed
1001
;;;###autoload
1002
(define-derived-mode prolog-mode prog-mode "Prolog"
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
  "Major mode for editing Prolog code.

Blank lines and `%%...' separate paragraphs.  `%'s starts a comment
line and comments can also be enclosed in /* ... */.

If an optional argument SYSTEM is non-nil, set up mode for the given system.

To find out what version of Prolog mode you are running, enter
`\\[prolog-mode-version]'.

root's avatar
root committed
1013 1014
Commands:
\\{prolog-mode-map}
1015
Entry to this mode calls the value of `prolog-mode-hook'
root's avatar
root committed
1016
if that value is non-nil."
1017 1018 1019 1020 1021 1022 1023
  (setq mode-name (concat "Prolog"
                          (cond
                           ((eq prolog-system 'eclipse) "[ECLiPSe]")
                           ((eq prolog-system 'sicstus) "[SICStus]")
                           ((eq prolog-system 'swi) "[SWI]")
                           ((eq prolog-system 'gnu) "[GNU]")
                           (t ""))))
root's avatar
root committed
1024
  (prolog-mode-variables)
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
  (prolog-build-case-strings)
  (prolog-set-atom-regexps)
  (dolist (ar prolog-align-rules) (add-to-list 'align-rules-list ar))

  ;; imenu entry moved to the appropriate hook for consistency
  
  ;; Load SICStus debugger if suitable
  (if (and (eq prolog-system 'sicstus)
           (prolog-atleast-version '(3 . 7))
           prolog-use-sicstus-sd)
1035 1036 1037 1038 1039 1040
      (prolog-enable-sicstus-sd)))

(defvar mercury-mode-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map prolog-mode-map)
    map))
1041 1042

;;;###autoload
1043
(define-derived-mode mercury-mode prolog-mode "Prolog[Mercury]"
1044 1045
  "Major mode for editing Mercury programs.
Actually this is just customized `prolog-mode'."
1046
  (set (make-local-variable 'prolog-system) 'mercury))
1047

root's avatar
root committed
1048

1049 1050 1051 1052
;;-------------------------------------------------------------------
;; Inferior prolog mode
;;-------------------------------------------------------------------

1053 1054 1055 1056 1057 1058
(defvar prolog-inferior-mode-map
  (let ((map (make-sparse-keymap)))
    (prolog-mode-keybindings-common map)
    (prolog-mode-keybindings-inferior map)
    map))
  
1059 1060 1061
(defvar prolog-inferior-mode-hook nil
  "List of functions to call after the inferior prolog mode has initialised.")

1062
(define-derived-mode prolog-inferior-mode comint-mode "Inferior Prolog"
root's avatar
root committed
1063 1064 1065
  "Major mode for interacting with an inferior Prolog process.

The following commands are available:
1066
\\{prolog-inferior-mode-map}
root's avatar
root committed
1067

1068 1069 1070
Entry to this mode calls the value of `prolog-mode-hook' with no arguments,
if that value is non-nil.  Likewise with the value of `comint-mode-hook'.
`prolog-mode-hook' is called after `comint-mode-hook'.
root's avatar
root committed
1071

1072 1073
You can send text to the inferior Prolog from other buffers
using the commands `send-region', `send-string' and \\[prolog-consult-region].
root's avatar
root committed
1074 1075 1076 1077

Commands:
Tab indents for Prolog; with argument, shifts rest
 of expression rigidly with the current line.
1078
Paragraphs are separated only by blank lines and '%%'. '%'s start comments.
root's avatar
root committed
1079 1080 1081

Return at end of buffer sends line as input.
Return not at end copies rest of line to end and sends it.
1082 1083 1084
\\[comint-delchar-or-maybe-eof] sends end-of-file as input.
\\[comint-kill-input] and \\[backward-kill-word] are kill commands,
imitating normal Unix input editing.
root's avatar
root committed
1085
\\[comint-interrupt-subjob] interrupts the shell or its current subjob if any.
1086 1087 1088 1089 1090
\\[comint-stop-subjob] stops, likewise.
\\[comint-quit-subjob] sends quit signal, likewise.

To find out what version of Prolog mode you are running, enter
`\\[prolog-mode-version]'."
1091 1092 1093 1094 1095
  (setq comint-input-filter 'prolog-input-filter)
  (setq mode-line-process '(": %s"))
  (prolog-mode-variables)
  (setq comint-prompt-regexp prolog-prompt-regexp-i)
  (set (make-local-variable 'shell-dirstack-query) "pwd."))
1096 1097 1098 1099 1100 1101 1102

(defun prolog-input-filter (str)
  (cond ((string-match "\\`\\s *\\'" str) nil) ;whitespace
        ((not (eq major-mode 'prolog-inferior-mode)) t)
        ((= (length str) 1) nil)        ;one character
        ((string-match "\\`[rf] *[0-9]*\\'" str) nil) ;r(edo) or f(ail)
        (t t)))
1103

Jim Blandy's avatar
Jim Blandy committed
1104
;;;###autoload
1105
(defun run-prolog (arg)
Stefan Monnier's avatar
Stefan Monnier committed
1106
  "Run an inferior Prolog process, input and output via buffer *prolog*.
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
With prefix argument ARG, restart the Prolog process if running before."
  (interactive "P")
  (if (and arg (get-process "prolog"))
      (progn
        (process-send-string "prolog" "halt.\n")
        (while (get-process "prolog") (sit-for 0.1))))
  (let ((buff (buffer-name)))
    (if (not (string= buff "*prolog*"))
        (prolog-goto-prolog-process-buffer))
    ;; Load SICStus debugger if suitable
    (if (and (eq prolog-system 'sicstus)
             (prolog-atleast-version '(3 . 7))
             prolog-use-sicstus-sd)
        (prolog-enable-sicstus-sd))
    (prolog-mode-variables)
    (prolog-ensure-process)
    ))

(defun prolog-ensure-process (&optional wait)
  "If Prolog process is not running, run it.
If the optional argument WAIT is non-nil, wait for Prolog prompt specified by
the variable `prolog-prompt-regexp'."
  (if (null prolog-program-name-i)
      (error "This Prolog system has defined no interpreter."))
  (if (comint-check-proc "*prolog*")
      ()
    (apply 'make-comint "prolog" prolog-program-name-i nil
           prolog-program-switches-i)
1135
    (with-current-buffer "*prolog*"
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
      (prolog-inferior-mode)
      (if wait
          (progn
            (goto-char (point-max))
            (while
                (save-excursion
                  (not
                   (re-search-backward
                    (concat "\\(" prolog-prompt-regexp-i "\\)" "\\=")
                    nil t)))
              (sit-for 0.1)))))))

(defun prolog-process-insert-string (process string)
  "Insert STRING into inferior Prolog buffer running PROCESS."
  ;; Copied from elisp manual, greek to me
1151 1152 1153 1154 1155 1156 1157 1158 1159
  (with-current-buffer (process-buffer process)
    ;; FIXME: Use window-point-insertion-type instead.
    (let ((moving (= (point) (process-mark process))))
      (save-excursion
        ;; Insert the text, moving the process-marker.
        (goto-char (process-mark process))
        (insert string)
        (set-marker (process-mark process) (point)))
      (if moving (goto-char (process-mark process))))))
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

;;------------------------------------------------------------
;; Old consulting and compiling functions
;;------------------------------------------------------------

(defun prolog-old-process-region (compilep start end)
  "Process the region limited by START and END positions.
If COMPILEP is non-nil then use compilation, otherwise consulting."
   (prolog-ensure-process)
   ;(let ((tmpfile prolog-temp-filename)
   (let ((tmpfile (prolog-bsts (prolog-temporary-file)))
         ;(process (get-process "prolog"))
         (first-line (1+ (count-lines 
                          (point-min) 
                          (save-excursion
                            (goto-char start)
                            (point))))))
     (write-region start end tmpfile)
     (process-send-string
      "prolog" (prolog-build-prolog-command
                compilep tmpfile (prolog-bsts buffer-file-name)
                first-line))
     (prolog-goto-prolog-process-buffer)))

(defun prolog-old-process-predicate (compilep)
  "Process the predicate around point.
If COMPILEP is non-nil then use compilation, otherwise consulting."
  (prolog-old-process-region
   compilep (prolog-pred-start) (prolog-pred-end)))

(defun prolog-old-process-buffer (compilep)
  "Process the entire buffer.
If COMPILEP is non-nil then use compilation, otherwise consulting."
  (prolog-old-process-region compilep (point-min) (point-max)))

(defun prolog-old-process-file (compilep)
  "Process the file of the current buffer.
If COMPILEP is non-nil then use compilation, otherwise consulting."
  (save-some-buffers)
  (prolog-ensure-process)
  (let ((filename (prolog-bsts buffer-file-name)))
    (process-send-string
     "prolog" (prolog-build-prolog-command 
               compilep filename filename))
    (prolog-goto-prolog-process-buffer)))


;;------------------------------------------------------------
;; Consulting and compiling
;;------------------------------------------------------------

;;; Interactive interface functions, used by both the standard
;;; and the experimental consultation and compilation functions
(defun prolog-consult-file ()
  "Consult file of current buffer."
  (interactive)
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-file nil)
    (prolog-consult-compile-file nil)))

(defun prolog-consult-buffer ()
  "Consult buffer."
  (interactive)
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-buffer nil)
    (prolog-consult-compile-buffer nil)))

(defun prolog-consult-region (beg end)
  "Consult region between BEG and END."
  (interactive "r")
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-region nil beg end)
    (prolog-consult-compile-region nil beg end)))

(defun prolog-consult-predicate ()
  "Consult the predicate around current point."
  (interactive)
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-predicate nil)
    (prolog-consult-compile-predicate nil)))

(defun prolog-compile-file ()
  "Compile file of current buffer."
  (interactive)
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-file t)
    (prolog-consult-compile-file t)))

(defun prolog-compile-buffer ()
  "Compile buffer."
  (interactive)
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-buffer t)
    (prolog-consult-compile-buffer t)))

(defun prolog-compile-region (beg end)
  "Compile region between BEG and END."
  (interactive "r")
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-region t beg end)
    (prolog-consult-compile-region t beg end)))

(defun prolog-compile-predicate ()
  "Compile the predicate around current point."
  (interactive)
  (if prolog-use-standard-consult-compile-method-flag
      (prolog-old-process-predicate t)
    (prolog-consult-compile-predicate t)))

(defun prolog-buffer-module ()
  "Select Prolog module name appropriate for current buffer.
Bases decision on buffer contents (-*- line)."
  ;; Look for -*- ... module: MODULENAME; ... -*-
  (let (beg end)
    (save-excursion
      (goto-char (point-min))
      (skip-chars-forward " \t")
      (and (search-forward "-*-" (save-excursion (end-of-line) (point)) t)
           (progn
             (skip-chars-forward " \t")
             (setq beg (point))
             (search-forward "-*-" (save-excursion (end-of-line) (point)) t))
           (progn
             (forward-char -3)
             (skip-chars-backward " \t")
             (setq end (point))
             (goto-char beg)
             (and (let ((case-fold-search t))
                    (search-forward "module:" end t))
                  (progn
                    (skip-chars-forward " \t")
                    (setq beg (point))
                    (if (search-forward ";" end t)
                        (forward-char -1)
                      (goto-char end))
                    (skip-chars-backward " \t")
                    (buffer-substring beg (point)))))))))

(defun prolog-build-prolog-command (compilep file buffername 
                                    &optional first-line)
  "Make Prolog command for FILE compilation/consulting.
If COMPILEP is non-nil, consider compilation, otherwise consulting."
  (let* ((compile-string
          (if compilep prolog-compile-string-i prolog-consult-string-i))
         (module (prolog-buffer-module))
         (file-name (concat "'" file "'"))
         (module-name (if module (concat "'" module "'")))
         (module-file (if module
                          (concat module-name ":" file-name)
                        file-name))
         strbeg strend
         (lineoffset (if first-line
                         (- first-line 1)
                       0)))

    ;; Assure that there is a buffer name
    (if (not buffername)
        (error "The buffer is not saved"))

    (if (not (string-match "^'.*'$" buffername)) ; Add quotes
        (setq buffername (concat "'" buffername "'")))
    (while (string-match "%m" compile-string)
      (setq strbeg (substring compile-string 0 (match-beginning 0)))
      (setq strend (substring compile-string (match-end 0)))
      (setq compile-string (concat strbeg module-file strend)))
    (while (string-match "%f" compile-string)
      (setq strbeg (substring compile-string 0 (match-beginning 0)))
      (setq strend (substring compile-string (match-end 0)))
      (setq compile-string (concat strbeg file-name strend)))
    (while (string-match "%b" compile-string)
      (setq strbeg (substring compile-string 0 (match-beginning 0)))
      (setq strend (substring compile-string (match-end 0)))
      (setq compile-string (concat strbeg buffername strend)))
    (while (string-match "%l" compile-string)
      (setq strbeg (substring compile-string 0 (match-beginning 0)))
      (setq strend (substring compile-string (match-end 0)))
      (setq compile-string (concat strbeg (format "%d" lineoffset) strend)))
    (concat compile-string "\n")))

;;; The rest of this page is experimental code!

;; Global variables for process filter function
(defvar prolog-process-flag nil
  "Non-nil means that a prolog task (i.e. a consultation or compilation job) 
is running.")
(defvar prolog-consult-compile-output ""
  "Hold the unprocessed output from the current prolog task.")
(defvar prolog-consult-compile-first-line 1
  "The number of the first line of the file to consult/compile.
Used for temporary files.")
(defvar prolog-consult-compile-file nil
  "The file to compile/consult (can be a temporary file).")
(defvar prolog-consult-compile-real-file nil
  "The file name of the buffer to compile/consult.")

(defun prolog-consult-compile (compilep file &optional first-line)
  "Consult/compile FILE.
If COMPILEP is non-nil, perform compilation, otherwise perform CONSULTING.
COMMAND is a string described by the variables `prolog-consult-string'
and `prolog-compile-string'.
Optional argument FIRST-LINE is the number of the first line in the compiled
region.

This function must be called from the source code buffer."
  (if prolog-process-flag
      (error "Another Prolog task is running."))
  (prolog-ensure-process t)
  (let* ((buffer (get-buffer-create prolog-compilation-buffer))
         (real-file buffer-file-name)
         (command-string (prolog-build-prolog-command compilep file 
                                                      real-file first-line))
         (process (get-process "prolog"))
         (old-filter (process-filter process)))
1373
    (with-current-buffer buffer
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
      (delete-region (point-min) (point-max))
      (compilation-mode)
      ;; Setting up font-locking for this buffer
      (make-local-variable 'font-lock-defaults)
      (setq font-lock-defaults 
            '(prolog-font-lock-keywords nil nil ((?_ . "w"))))
      (if (eq prolog-system 'sicstus)
          (progn
            (make-local-variable 'compilation-parse-errors-function)
            (setq compilation-parse-errors-function
                  'prolog-parse-sicstus-compilation-errors)))
      (toggle-read-only 0)
      (insert command-string "\n"))
    (save-selected-window
      (pop-to-buffer buffer))
    (setq prolog-process-flag t
          prolog-consult-compile-output ""
          prolog-consult-compile-first-line (if first-line (1- first-line) 0)
          prolog-consult-compile-file file
          prolog-consult-compile-real-file (if (string= 
                                                file buffer-file-name)
                                               nil
                                             real-file))
1397
    (with-current-buffer buffer
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
      (goto-char (point-max))
      (set-process-filter process 'prolog-consult-compile-filter)
      (process-send-string "prolog" command-string)
      ;; (prolog-build-prolog-command compilep file real-file first-line))
      (while (and prolog-process-flag
                  (accept-process-output process 10)) ; 10 secs is ok?
        (sit-for 0.1)
        (unless (get-process "prolog")
            (setq prolog-process-flag nil)))
      (insert (if compilep
                  "\nCompilation finished.\n"
                "\nConsulted.\n"))
      (set-process-filter process old-filter))))

(defun prolog-parse-sicstus-compilation-errors (limit)
  "Parse the prolog compilation buffer for errors.
Argument LIMIT is a buffer position limiting searching.
For use with the `compilation-parse-errors-function' variable."
  (setq compilation-error-list nil)
  (message "Parsing SICStus error messages...")
  (let (filepath dir file errorline)
    (while 
        (re-search-backward
         "{\\([a-zA-Z ]* ERROR\\|Warning\\):.* in line[s ]*\\([0-9]+\\)"
         limit t)
      (setq errorline (string-to-number (match-string 2)))
      (save-excursion
        (re-search-backward
         "{\\(consulting\\|compiling\\|processing\\) \\(.*\\)\\.\\.\\.}"
         limit t)
        (setq filepath (match-string 2)))

      ;; ###### Does this work with SICStus under Windows (i.e. backslahes and stuff?)
      (if (string-match "\\(.*/\\)\\([^/]*\\)$" filepath)
          (progn
            (setq dir (match-string 1 filepath))
            (setq file (match-string 2 filepath))))

      (setq compilation-error-list
            (cons
             (cons (save-excursion
                     (beginning-of-line)
                     (point-marker))
                   (list (list file dir) errorline))
             compilation-error-list)
            ))
    ))

(defun prolog-consult-compile-filter (process output)
  "Filter function for Prolog compilation PROCESS.
Argument OUTPUT is a name of the output file."
  ;;(message "start")
  (setq prolog-consult-compile-output
        (concat prolog-consult-compile-output output))
  ;;(message "pccf1: %s" prolog-consult-compile-output)
  ;; Iterate through the lines of prolog-consult-compile-output
  (let (outputtype)
    (while (and prolog-process-flag
                (or
                 ;; Trace question
                 (progn 
                   (setq outputtype 'trace)
                   (and (eq prolog-system 'sicstus)
                        (string-match
                         "^[ \t]*[0-9]+[ \t]*[0-9]+[ \t]*Call:.*? "
                         prolog-consult-compile-output)))
                 
                 ;; Match anything
                 (progn 
                   (setq outputtype 'normal)
                   (string-match "^.*\n" prolog-consult-compile-output))
                   ))
      ;;(message "outputtype: %s" outputtype)

      (setq output (match-string 0 prolog-consult-compile-output))
      ;; remove the text in output from prolog-consult-compile-output
      (setq prolog-consult-compile-output
            (substring prolog-consult-compile-output (length output)))
      ;;(message "pccf2: %s" prolog-consult-compile-output)
      
      ;; If temporary files were used, then we change the error
      ;; messages to point to the original source file.
      (cond

       ;; If the prolog process was in trace mode then it requires
       ;; user input
       ((and (eq prolog-system 'sicstus) 
             (eq outputtype 'trace))
        (let (input)
          (setq input (concat (read-string output) "\n"))
1488
          (process-send-string process input)
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
          (setq output (concat output input))))

       ((eq prolog-system 'sicstus)
        (if (and prolog-consult-compile-real-file
                 (string-match
                  "\\({.*:.* in line[s ]*\\)\\([0-9]+\\)-\\([0-9]+\\)" output))
            (setq output (replace-match
                          ;; Adds a {processing ...} line so that 
                          ;; `prolog-parse-sicstus-compilation-errors'
                          ;; finds the real file instead of the temporary one.
                          ;; Also fixes the line numbers.
                          (format "Added by Emacs: {processing %s...}\n%s%d-%d"
                                  prolog-consult-compile-real-file
                                  (match-string 1 output)
                                  (+ prolog-consult-compile-first-line
                                     (string-to-number
                                      (match-string 2 output)))
                                  (+ prolog-consult-compile-first-line
                                     (string-to-number
                                      (match-string 3 output))))
                          t t output)))
        )
       
       ((eq prolog-system 'swi)
        (if (and prolog-consult-compile-real-file
                 (string-match (format
                                "%s\\([ \t]*:[ \t]*\\)\\([0-9]+\\)"
                                prolog-consult-compile-file)
                               output))
            (setq output (replace-match
                          ;; Real filename + text + fixed linenum
                          (format "%s%s%d"
                                  prolog-consult-compile-real-file
                                  (match-string 1 output)
                                  (+ prolog-consult-compile-first-line
                                     (string-to-number
                                      (match-string 2 output))))
                          t t output)))
        )
       
       (t ())
       )
      ;; Write the output in the *prolog-compilation* buffer
      (insert output)))

  ;; If the prompt is visible, then the task is finished
  (if (string-match prolog-prompt-regexp-i prolog-consult-compile-output)
      (setq prolog-process-flag nil)))

(defun prolog-consult-compile-file (compilep)
  "Consult/compile file of current buffer.
If COMPILEP is non-nil, compile, otherwise consult."
  (let ((file buffer-file-name))
    (if file
        (progn
          (save-some-buffers)
          (prolog-consult-compile compilep file))
      (prolog-consult-compile-region compilep (point-min) (point-max)))))

(defun prolog-consult-compile-buffer (compilep)
  "Consult/compile current buffer.
If COMPILEP is non-nil, compile, otherwise consult."
  (prolog-consult-compile-region compilep (point-min) (point-max)))

(defun prolog-consult-compile-region (compilep beg end)
  "Consult/compile region between BEG and END.
If COMPILEP is non-nil, compile, otherwise consult."
  ;(let ((file prolog-temp-filename)
  (let ((file (prolog-bsts (prolog-temporary-file)))
        (lines (count-lines 1 beg)))
    (write-region beg end file nil 'no-message)
    (write-region "\n" nil file t 'no-message)
    (prolog-consult-compile compilep file
                            (if (looking-at "^") (1+ lines) lines))
    (delete-file file)))

(defun prolog-consult-compile-predicate (compilep)
  "Consult/compile the predicate around current point.
If COMPILEP is non-nil, compile, otherwise consult."
  (prolog-consult-compile-region
   compilep (prolog-pred-start) (prolog-pred-end)))


;;-------------------------------------------------------------------
;; Font-lock stuff
;;-------------------------------------------------------------------

;; Auxilliary functions
(defun prolog-make-keywords-regexp (keywords &optional protect)
  "Create regexp from the list of strings KEYWORDS.
If PROTECT is non-nil, surround the result regexp by word breaks."
  (let ((regexp
         (if (fboundp 'regexp-opt)
             ;; Emacs 20
             ;; Avoid compile warnings under earlier versions by using eval
             (eval '(regexp-opt keywords))
           ;; Older Emacsen
           (concat (mapconcat 'regexp-quote keywords "\\|")))
         ))
    (if protect
        (concat "\\<\\(" regexp "\\)\\>")
      regexp)))

(defun prolog-font-lock-object-matcher (bound)
  "Find SICStus objects method name for font lock.
Argument BOUND is a buffer position limiting searching."
  (let (point
         (case-fold-search nil))
    (while (and (not point)
                (re-search-forward "\\(::[ \t\n]*{\\|&\\)[ \t]*"
                                   bound t))
      (while (or (re-search-forward "\\=\n[ \t]*" bound t)
                  (re-search-forward "\\=%.*" bound t)
                  (and (re-search-forward "\\=/\\*" bound t)
                       (re-search-forward "\\*/[ \t]*" bound t))))
      (setq point (re-search-forward
                   (format "\\=\\(%s\\)" prolog-atom-regexp)
                   bound t)))
    point))

(defsubst prolog-face-name-p (facename)
  ;; Return t if FACENAME is the name of a face.  This method is
  ;; necessary since facep in XEmacs only returns t for the actual
  ;; face objects (while it's only their names that are used just
  ;; about anywhere else) without providing a predicate that tests
  ;; face names.  This function (including the above commentary) is
  ;; borrowed from cc-mode.
  (memq facename (face-list)))

;; Set everything up
(defun prolog-font-lock-keywords ()
  "Set up font lock keywords for the current Prolog system."
  ;(when window-system
    (require 'font-lock)
    
    ;; Define Prolog faces
    (defface prolog-redo-face
      '((((class grayscale)) (:italic t))
        (((class color)) (:foreground "darkorchid"))
        (t (:italic t)))
      "Prolog mode face for highlighting redo trace lines."
      :group 'prolog-faces)
    (defface prolog-exit-face
      '((((class grayscale)) (:underline t))
        (((class color) (background dark)) (:foreground "green"))
        (((class color) (background light)) (:foreground "ForestGreen"))
        (t (:underline t)))
      "Prolog mode face for highlighting exit trace lines."
      :group 'prolog-faces)