Spelling fixes.
[emacs.git] / lisp / progmodes / prolog.el
blob93d27042dc8ffe608e865edd7bb7172e5a96a744
1 ;;; prolog.el --- major mode for editing and running Prolog (and Mercury) code
3 ;; Copyright (C) 1986-1987, 1997-1999, 2002-2003, 2011
4 ;; Free Software Foundation, Inc.
6 ;; Authors: Emil Åström <emil_astrom(at)hotmail(dot)com>
7 ;; Milan Zamazal <pdm(at)freesoft(dot)cz>
8 ;; Stefan Bruda <stefan(at)bruda(dot)ca>
9 ;; * See below for more details
10 ;; Maintainer: Stefan Bruda <stefan(at)bruda(dot)ca>
11 ;; Keywords: prolog major mode sicstus swi mercury
13 (defvar prolog-mode-version "1.22"
14 "Prolog mode version number.")
16 ;; This file is part of GNU Emacs.
18 ;; GNU Emacs is free software: you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published by
20 ;; the Free Software Foundation, either version 3 of the License, or
21 ;; (at your option) any later version.
23 ;; GNU Emacs is distributed in the hope that it will be useful,
24 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 ;; GNU General Public License for more details.
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 ;; Original author: Masanobu UMEDA <umerin(at)mse(dot)kyutech(dot)ac(dot)jp>
32 ;; Parts of this file was taken from a modified version of the original
33 ;; by Johan Andersson, Peter Olin, Mats Carlsson, Johan Bevemyr, Stefan
34 ;; Andersson, and Per Danielsson (all SICS people), and Henrik Båkman
35 ;; at Uppsala University, Sweden.
37 ;; Some ideas and also a few lines of code have been borrowed (not stolen ;-)
38 ;; from Oz.el, the Emacs major mode for the Oz programming language,
39 ;; Copyright (C) 1993 DFKI GmbH, Germany, with permission.
40 ;; Authors: Ralf Scheidhauer and Michael Mehl ([scheidhr|mehl](at)dfki(dot)uni-sb(dot)de)
42 ;; More ideas and code have been taken from the SICStus debugger mode
43 ;; (http://www.csd.uu.se/~perm/source_debug/index.shtml -- broken link
44 ;; as of Mon May 5 08:23:48 EDT 2003) by Per Mildner.
46 ;; Additions for ECLiPSe and other helpful suggestions: Stephan Heuel
47 ;; <heuel(at)ipb(dot)uni-bonn(dot)de>
49 ;;; Commentary:
51 ;; This package provides a major mode for editing Prolog code, with
52 ;; all the bells and whistles one would expect, including syntax
53 ;; highlighting and auto indentation. It can also send regions to an
54 ;; inferior Prolog process.
56 ;; The code requires the comint, easymenu, info, imenu, and font-lock
57 ;; libraries. These are normally distributed with GNU Emacs and
58 ;; XEmacs.
60 ;;; Installation:
62 ;; Insert the following lines in your init file--typically ~/.emacs
63 ;; (GNU Emacs and XEmacs <21.4), or ~/.xemacs/init.el (XEmacs
64 ;; 21.4)--to use this mode when editing Prolog files under Emacs:
66 ;; (setq load-path (cons "/usr/lib/xemacs/site-lisp" load-path))
67 ;; (autoload 'run-prolog "prolog" "Start a Prolog sub-process." t)
68 ;; (autoload 'prolog-mode "prolog" "Major mode for editing Prolog programs." t)
69 ;; (autoload 'mercury-mode "prolog" "Major mode for editing Mercury programs." t)
70 ;; (setq prolog-system 'swi) ; optional, the system you are using;
71 ;; ; see `prolog-system' below for possible values
72 ;; (setq auto-mode-alist (append '(("\\.pl$" . prolog-mode)
73 ;; ("\\.m$" . mercury-mode))
74 ;; auto-mode-alist))
76 ;; where the path in the first line is the file system path to this file.
77 ;; MSDOS paths can be written like "d:/programs/emacs-19.34/site-lisp".
78 ;; Note: In XEmacs, either `/usr/lib/xemacs/site-lisp' (RPM default in
79 ;; Red Hat-based distributions) or `/usr/local/lib/xemacs/site-lisp'
80 ;; (default when compiling from sources) are automatically added to
81 ;; `load-path', so the first line is not necessary provided that you
82 ;; put this file in the appropriate place.
84 ;; The last s-expression above makes sure that files ending with .pl
85 ;; are assumed to be Prolog files and not Perl, which is the default
86 ;; Emacs setting. If this is not wanted, remove this line. It is then
87 ;; necessary to either
89 ;; o insert in your Prolog files the following comment as the first line:
91 ;; % -*- Mode: Prolog -*-
93 ;; and then the file will be open in Prolog mode no matter its
94 ;; extension, or
96 ;; o manually switch to prolog mode after opening a Prolog file, by typing
97 ;; M-x prolog-mode.
99 ;; If the command to start the prolog process ('sicstus', 'pl' or
100 ;; 'swipl' for SWI prolog, etc.) is not available in the default path,
101 ;; then it is necessary to set the value of the environment variable
102 ;; EPROLOG to a shell command to invoke the prolog process. In XEmacs
103 ;; and Emacs 20+ you can also customize the variable
104 ;; `prolog-program-name' (in the group `prolog-inferior') and provide
105 ;; a full path for your Prolog system (swi, scitus, etc.).
107 ;; Note: I (Stefan, the current maintainer) work under XEmacs. Future
108 ;; developments will thus be biased towards XEmacs (OK, I admit it,
109 ;; I am biased towards XEmacs in general), though I will do my best
110 ;; to keep the GNU Emacs compatibility. So if you work under Emacs
111 ;; and see something that does not work do drop me a line, as I have
112 ;; a smaller chance to notice this kind of bugs otherwise.
114 ;; Changelog:
116 ;; Version 1.22:
117 ;; o Allowed both 'swipl' and 'pl' as names for the SWI Prolog
118 ;; interpreter.
119 ;; o Atoms that start a line are not blindly coloured as
120 ;; predicates. Instead we check that they are followed by ( or
121 ;; :- first. Patch suggested by Guy Wiener.
122 ;; Version 1.21:
123 ;; o Cleaned up the code that defines faces. The missing face
124 ;; warnings on some Emacsen should disappear.
125 ;; Version 1.20:
126 ;; o Improved the handling of clause start detection and multi-line
127 ;; comments: `prolog-clause-start' no longer finds non-predicate
128 ;; (e.g., capitalized strings) beginning of clauses.
129 ;; `prolog-tokenize' recognizes when the end point is within a
130 ;; multi-line comment.
131 ;; Version 1.19:
132 ;; o Minimal changes for Aquamacs inclusion and in general for
133 ;; better coping with finding the Prolog executable. Patch
134 ;; provided by David Reitter
135 ;; Version 1.18:
136 ;; o Fixed syntax highlighting for clause heads that do not begin at
137 ;; the beginning of the line.
138 ;; o Fixed compilation warnings under Emacs.
139 ;; o Updated the email address of the current maintainer.
140 ;; Version 1.17:
141 ;; o Minor indentation fix (patch by Markus Triska)
142 ;; o `prolog-underscore-wordchar-flag' defaults now to nil (more
143 ;; consistent to other Emacs modes)
144 ;; Version 1.16:
145 ;; o Eliminated a possible compilation warning.
146 ;; Version 1.15:
147 ;; o Introduced three new customizable variables: electric colon
148 ;; (`prolog-electric-colon-flag', default nil), electric dash
149 ;; (`prolog-electric-dash-flag', default nil), and a possibility
150 ;; to prevent the predicate template insertion from adding commata
151 ;; (`prolog-electric-dot-full-predicate-template', defaults to t
152 ;; since it seems quicker to me to just type those commata). A
153 ;; trivial adaptation of a patch by Markus Triska.
154 ;; o Improved the behavior of electric if-then-else to only skip
155 ;; forward if the parenthesis/semicolon is preceded by
156 ;; whitespace. Once more a trivial adaptation of a patch by
157 ;; Markus Triska.
158 ;; Version 1.14:
159 ;; o Cleaned up align code. `prolog-align-flag' is eliminated (since
160 ;; on a second thought it does not do anything useful). Added key
161 ;; binding (C-c C-a) and menu entry for alignment.
162 ;; o Condensed regular expressions for lower and upper case
163 ;; characters (GNU Emacs seems to go over the regexp length limit
164 ;; with the original form). My code on the matter was improved
165 ;; considerably by Markus Triska.
166 ;; o Fixed `prolog-insert-spaces-after-paren' (which used an
167 ;; unitialized variable).
168 ;; o Minor changes to clean up the code and avoid some implicit
169 ;; package requirements.
170 ;; Version 1.13:
171 ;; o Removed the use of `map-char-table' in `prolog-build-case-strings'
172 ;; which appears to cause prblems in (at least) Emacs 23.0.0.1.
173 ;; o Added if-then-else indentation + corresponding electric
174 ;; characters. New customization: `prolog-electric-if-then-else-flag'
175 ;; o Align support (requires `align'). New customization:
176 ;; `prolog-align-flag'.
177 ;; o Temporary consult files have now the same name throughout the
178 ;; session. This prevents issues with reconsulting a buffer
179 ;; (this event is no longer passed to Prolog as a request to
180 ;; consult a new file).
181 ;; o Adaptive fill mode is now turned on. Comment indentation is
182 ;; still worse than it could be though, I am working on it.
183 ;; o Improved filling and auto-filling capabilities. Now block
184 ;; comments should be [auto-]filled correctly most of the time;
185 ;; the following pattern in particular is worth noting as being
186 ;; filled correctly:
187 ;; <some code here> % some comment here that goes beyond the
188 ;; % rightmost column, possibly combined with
189 ;; % subsequent comment lines
190 ;; o `prolog-char-quote-workaround' now defaults to nil.
191 ;; o Note: Many of the above improvements have been suggested by
192 ;; Markus Triska, who also provided useful patches on the matter
193 ;; when he realized that I was slow in responding. Many thanks.
194 ;; Version 1.11 / 1.12
195 ;; o GNU Emacs compatibility fix for paragraph filling (fixed
196 ;; incorrectly in 1.11, fix fixed in 1.12).
197 ;; Version 1.10
198 ;; o Added paragraph filling in comment blocks and also correct auto
199 ;; filling for comments.
200 ;; o Fixed the possible "Regular expression too big" error in
201 ;; `prolog-electric-dot'.
202 ;; Version 1.9
203 ;; o Parenthesis expressions are now indented by default so that
204 ;; components go one underneath the other, just as for compound
205 ;; terms. You can use the old style (the second and subsequent
206 ;; lines being indented to the right in a parenthesis expression)
207 ;; by setting the customizable variable `prolog-paren-indent-p'
208 ;; (group "Prolog Indentation") to t.
209 ;; o (Somehow awkward) handling of the 0' character escape
210 ;; sequence. I am looking into a better way of doing it but
211 ;; prospects look bleak. If this breaks things for you please let
212 ;; me know and also set the `prolog-char-quote-workaround' (group
213 ;; "Prolog Other") to nil.
214 ;; Version 1.8
215 ;; o Key binding fix.
216 ;; Version 1.7
217 ;; o Fixed a number of issues with the syntax of single quotes,
218 ;; including Debian bug #324520.
219 ;; Version 1.6
220 ;; o Fixed mercury mode menu initialization (Debian bug #226121).
221 ;; o Fixed (i.e., eliminated) Delete remapping (Debian bug #229636).
222 ;; o Corrected indentation for clauses defining quoted atoms.
223 ;; Version 1.5:
224 ;; o Keywords fontifying should work in console mode so this is
225 ;; enabled everywhere.
226 ;; Version 1.4:
227 ;; o Now supports GNU Prolog--minor adaptation of a patch by Stefan
228 ;; Moeding.
229 ;; Version 1.3:
230 ;; o Info-follow-nearest-node now called correctly under Emacs too
231 ;; (thanks to Nicolas Pelletier). Should be implemented more
232 ;; elegantly (i.e., without compilation warnings) in the future.
233 ;; Version 1.2:
234 ;; o Another prompt fix, still in SWI mode (people seem to have
235 ;; changed the prompt of SWI Prolog).
236 ;; Version 1.1:
237 ;; o Fixed dots in the end of line comments causing indentation
238 ;; problems. The following code is now correctly indented (note
239 ;; the dot terminating the comment):
240 ;; a(X) :- b(X),
241 ;; c(X). % comment here.
242 ;; a(X).
243 ;; and so is this (and variants):
244 ;; a(X) :- b(X),
245 ;; c(X). /* comment here. */
246 ;; a(X).
247 ;; Version 1.0:
248 ;; o Revamped the menu system.
249 ;; o Yet another prompt recognition fix (SWI mode).
250 ;; o This is more of a renumbering than a new edition. I promoted
251 ;; the mode to version 1.0 to emphasize the fact that it is now
252 ;; mature and stable enough to be considered production (in my
253 ;; opinion anyway).
254 ;; Version 0.1.41:
255 ;; o GNU Emacs compatibility fixes.
256 ;; Version 0.1.40:
257 ;; o prolog-get-predspec is now suitable to be called as
258 ;; imenu-extract-index-name-function. The predicate index works.
259 ;; o Since imenu works now as advertised, prolog-imenu-flag is t
260 ;; by default.
261 ;; o Eliminated prolog-create-predicate-index since the imenu
262 ;; utilities now work well. Actually, this function is also
263 ;; buggy, and I see no reason to fix it since we do not need it
264 ;; anyway.
265 ;; o Fixed prolog-pred-start, prolog-clause-start, prolog-clause-info.
266 ;; o Fix for prolog-build-case-strings; now prolog-upper-case-string
267 ;; and prolog-lower-case-string are correctly initialized,
268 ;; o Various font-lock changes; most importantly, block comments (/*
269 ;; ... */) are now correctly fontified in XEmacs even when they
270 ;; extend on multiple lines.
271 ;; Version 0.1.36:
272 ;; o The debug prompt of SWI Prolog is now correctly recognized.
273 ;; Version 0.1.35:
274 ;; o Minor font-lock bug fixes.
276 ;;; TODO:
278 ;; Replace ":type 'sexp" with more precise Custom types.
280 ;;; Code:
282 (eval-when-compile
283 (require 'font-lock)
284 ;; We need imenu everywhere because of the predicate index!
285 (require 'imenu)
287 (require 'info)
288 (require 'shell)
291 (require 'comint)
292 (require 'easymenu)
293 (require 'align)
296 (defgroup prolog nil
297 "Major modes for editing and running Prolog and Mercury files."
298 :group 'languages)
300 (defgroup prolog-faces nil
301 "Prolog mode specific faces."
302 :group 'font-lock)
304 (defgroup prolog-indentation nil
305 "Prolog mode indentation configuration."
306 :group 'prolog)
308 (defgroup prolog-font-lock nil
309 "Prolog mode font locking patterns."
310 :group 'prolog)
312 (defgroup prolog-keyboard nil
313 "Prolog mode keyboard flags."
314 :group 'prolog)
316 (defgroup prolog-inferior nil
317 "Inferior Prolog mode options."
318 :group 'prolog)
320 (defgroup prolog-other nil
321 "Other Prolog mode options."
322 :group 'prolog)
325 ;;-------------------------------------------------------------------
326 ;; User configurable variables
327 ;;-------------------------------------------------------------------
329 ;; General configuration
331 (defcustom prolog-system nil
332 "*Prolog interpreter/compiler used.
333 The value of this variable is nil or a symbol.
334 If it is a symbol, it determines default values of other configuration
335 variables with respect to properties of the specified Prolog
336 interpreter/compiler.
338 Currently recognized symbol values are:
339 eclipse - Eclipse Prolog
340 mercury - Mercury
341 sicstus - SICStus Prolog
342 swi - SWI Prolog
343 gnu - GNU Prolog"
344 :group 'prolog
345 :type '(choice (const :tag "SICStus" :value sicstus)
346 (const :tag "SWI Prolog" :value swi)
347 (const :tag "GNU Prolog" :value gnu)
348 (const :tag "ECLiPSe Prolog" :value eclipse)
349 ;; Mercury shouldn't be needed since we have a separate
350 ;; major mode for it.
351 (const :tag "Default" :value nil)))
352 (make-variable-buffer-local 'prolog-system)
354 ;; NB: This alist can not be processed in prolog-mode-variables to
355 ;; create a prolog-system-version-i variable since it is needed
356 ;; prior to the call to prolog-mode-variables.
357 (defcustom prolog-system-version
358 '((sicstus (3 . 6))
359 (swi (0 . 0))
360 (mercury (0 . 0))
361 (eclipse (3 . 7))
362 (gnu (0 . 0)))
363 ;; FIXME: This should be auto-detected instead of user-provided.
364 "*Alist of Prolog system versions.
365 The version numbers are of the format (Major . Minor)."
366 :group 'prolog)
368 ;; Indentation
370 (defcustom prolog-indent-width 4
371 "*The indentation width used by the editing buffer."
372 :group 'prolog-indentation
373 :type 'integer)
375 (defcustom prolog-align-comments-flag t
376 "*Non-nil means automatically align comments when indenting."
377 :group 'prolog-indentation
378 :type 'boolean)
380 (defcustom prolog-indent-mline-comments-flag t
381 "*Non-nil means indent contents of /* */ comments.
382 Otherwise leave such lines as they are."
383 :group 'prolog-indentation
384 :type 'boolean)
386 (defcustom prolog-object-end-to-0-flag t
387 "*Non-nil means indent closing '}' in SICStus object definitions to level 0.
388 Otherwise indent to `prolog-indent-width'."
389 :group 'prolog-indentation
390 :type 'boolean)
392 (defcustom prolog-left-indent-regexp "\\(;\\|\\*?->\\)"
393 "*Regexp for character sequences after which next line is indented.
394 Next line after such a regexp is indented to the opening paranthesis level."
395 :group 'prolog-indentation
396 :type 'regexp)
398 (defcustom prolog-paren-indent-p nil
399 "*If non-nil, increase indentation for parenthesis expressions.
400 The second and subsequent line in a parenthesis expression other than
401 a compound term can either be indented `prolog-paren-indent' to the
402 right (if this variable is non-nil) or in the same way as for compound
403 terms (if this variable is nil, default)."
404 :group 'prolog-indentation
405 :type 'boolean)
407 (defcustom prolog-paren-indent 4
408 "*The indentation increase for parenthesis expressions.
409 Only used in ( If -> Then ; Else) and ( Disj1 ; Disj2 ) style expressions."
410 :group 'prolog-indentation
411 :type 'integer)
413 (defcustom prolog-parse-mode 'beg-of-clause
414 "*The parse mode used (decides from which point parsing is done).
415 Legal values:
416 'beg-of-line - starts parsing at the beginning of a line, unless the
417 previous line ends with a backslash. Fast, but has
418 problems detecting multiline /* */ comments.
419 'beg-of-clause - starts parsing at the beginning of the current clause.
420 Slow, but copes better with /* */ comments."
421 :group 'prolog-indentation
422 :type '(choice (const :value beg-of-line)
423 (const :value beg-of-clause)))
425 ;; Font locking
427 (defcustom prolog-keywords
428 '((eclipse
429 ("use_module" "begin_module" "module_interface" "dynamic"
430 "external" "export" "dbgcomp" "nodbgcomp" "compile"))
431 (mercury
432 ("all" "else" "end_module" "equality" "external" "fail" "func" "if"
433 "implementation" "import_module" "include_module" "inst" "instance"
434 "interface" "mode" "module" "not" "pragma" "pred" "some" "then" "true"
435 "type" "typeclass" "use_module" "where"))
436 (sicstus
437 ("block" "dynamic" "mode" "module" "multifile" "meta_predicate"
438 "parallel" "public" "sequential" "volatile"))
439 (swi
440 ("discontiguous" "dynamic" "ensure_loaded" "export" "export_list" "import"
441 "meta_predicate" "module" "module_transparent" "multifile" "require"
442 "use_module" "volatile"))
443 (gnu
444 ("built_in" "char_conversion" "discontiguous" "dynamic" "ensure_linked"
445 "ensure_loaded" "foreign" "include" "initialization" "multifile" "op"
446 "public" "set_prolog_flag"))
448 ;; FIXME: Shouldn't we just use the union of all the above here?
449 ("dynamic" "module")))
450 "*Alist of Prolog keywords which is used for font locking of directives."
451 :group 'prolog-font-lock
452 :type 'sexp)
454 (defcustom prolog-types
455 '((mercury
456 ("char" "float" "int" "io__state" "string" "univ"))
457 (t nil))
458 "*Alist of Prolog types used by font locking."
459 :group 'prolog-font-lock
460 :type 'sexp)
462 (defcustom prolog-mode-specificators
463 '((mercury
464 ("bound" "di" "free" "ground" "in" "mdi" "mui" "muo" "out" "ui" "uo"))
465 (t nil))
466 "*Alist of Prolog mode specificators used by font locking."
467 :group 'prolog-font-lock
468 :type 'sexp)
470 (defcustom prolog-determinism-specificators
471 '((mercury
472 ("cc_multi" "cc_nondet" "det" "erroneous" "failure" "multi" "nondet"
473 "semidet"))
474 (t nil))
475 "*Alist of Prolog determinism specificators used by font locking."
476 :group 'prolog-font-lock
477 :type 'sexp)
479 (defcustom prolog-directives
480 '((mercury
481 ("^#[0-9]+"))
482 (t nil))
483 "*Alist of Prolog source code directives used by font locking."
484 :group 'prolog-font-lock
485 :type 'sexp)
488 ;; Keyboard
490 (defcustom prolog-electric-newline-flag (not (fboundp 'electric-indent-mode))
491 "*Non-nil means automatically indent the next line when the user types RET."
492 :group 'prolog-keyboard
493 :type 'boolean)
495 (defcustom prolog-hungry-delete-key-flag nil
496 "*Non-nil means delete key consumes all preceding spaces."
497 :group 'prolog-keyboard
498 :type 'boolean)
500 (defcustom prolog-electric-dot-flag nil
501 "*Non-nil means make dot key electric.
502 Electric dot appends newline or inserts head of a new clause.
503 If dot is pressed at the end of a line where at least one white space
504 precedes the point, it inserts a recursive call to the current predicate.
505 If dot is pressed at the beginning of an empty line, it inserts the head
506 of a new clause for the current predicate. It does not apply in strings
507 and comments.
508 It does not apply in strings and comments."
509 :group 'prolog-keyboard
510 :type 'boolean)
512 (defcustom prolog-electric-dot-full-predicate-template nil
513 "*If nil, electric dot inserts only the current predicate's name and `('
514 for recursive calls or new clause heads. Non-nil means to also
515 insert enough commata to cover the predicate's arity and `)',
516 and dot and newline for recursive calls."
517 :group 'prolog-keyboard
518 :type 'boolean)
520 (defcustom prolog-electric-underscore-flag nil
521 "*Non-nil means make underscore key electric.
522 Electric underscore replaces the current variable with underscore.
523 If underscore is pressed not on a variable then it behaves as usual."
524 :group 'prolog-keyboard
525 :type 'boolean)
527 (defcustom prolog-electric-tab-flag nil
528 "*Non-nil means make TAB key electric.
529 Electric TAB inserts spaces after parentheses, ->, and ;
530 in ( If -> Then ; Else) and ( Disj1 ; Disj2 ) style expressions."
531 :group 'prolog-keyboard
532 :type 'boolean)
534 (defcustom prolog-electric-if-then-else-flag nil
535 "*Non-nil makes `(', `>' and `;' electric
536 to automatically indent if-then-else constructs."
537 :group 'prolog-keyboard
538 :type 'boolean)
540 (defcustom prolog-electric-colon-flag nil
541 "*Makes `:' electric (inserts `:-' on a new line).
542 If non-nil, pressing `:' at the end of a line that starts in
543 the first column (i.e., clause heads) inserts ` :-' and newline."
544 :group 'prolog-keyboard
545 :type 'boolean)
547 (defcustom prolog-electric-dash-flag nil
548 "*Makes `-' electric (inserts a `-->' on a new line).
549 If non-nil, pressing `-' at the end of a line that starts in
550 the first column (i.e., DCG heads) inserts ` -->' and newline."
551 :group 'prolog-keyboard
552 :type 'boolean)
554 (defcustom prolog-old-sicstus-keys-flag nil
555 "*Non-nil means old SICStus Prolog mode keybindings are used."
556 :group 'prolog-keyboard
557 :type 'boolean)
559 ;; Inferior mode
561 (defcustom prolog-program-name
562 `(((getenv "EPROLOG") (eval (getenv "EPROLOG")))
563 (eclipse "eclipse")
564 (mercury nil)
565 (sicstus "sicstus")
566 (swi ,(if (not (executable-find "swipl")) "pl" "swipl"))
567 (gnu "gprolog")
568 (t ,(let ((names '("prolog" "gprolog" "swipl" "pl")))
569 (while (and names
570 (not (executable-find (car names))))
571 (setq names (cdr names)))
572 (or (car names) "prolog"))))
573 "*Alist of program names for invoking an inferior Prolog with `run-prolog'."
574 :group 'prolog-inferior
575 :type 'sexp)
576 (defun prolog-program-name ()
577 (prolog-find-value-by-system prolog-program-name))
579 (defcustom prolog-program-switches
580 '((sicstus ("-i"))
581 (t nil))
582 "*Alist of switches given to inferior Prolog run with `run-prolog'."
583 :group 'prolog-inferior
584 :type 'sexp)
585 (defun prolog-program-switches ()
586 (prolog-find-value-by-system prolog-program-switches))
588 (defcustom prolog-consult-string
589 '((eclipse "[%f].")
590 (mercury nil)
591 (sicstus (eval (if (prolog-atleast-version '(3 . 7))
592 "prolog:zap_file(%m,%b,consult,%l)."
593 "prolog:zap_file(%m,%b,consult).")))
594 (swi "[%f].")
595 (gnu "[%f].")
596 (t "reconsult(%f)."))
597 "*Alist of strings defining predicate for reconsulting.
599 Some parts of the string are replaced:
600 `%f' by the name of the consulted file (can be a temporary file)
601 `%b' by the file name of the buffer to consult
602 `%m' by the module name and name of the consulted file separated by colon
603 `%l' by the line offset into the file. This is 0 unless consulting a
604 region of a buffer, in which case it is the number of lines before
605 the region."
606 :group 'prolog-inferior
607 :type 'sexp)
608 (defun prolog-consult-string ()
609 (prolog-find-value-by-system prolog-consult-string))
611 (defcustom prolog-compile-string
612 '((eclipse "[%f].")
613 (mercury "mmake ")
614 (sicstus (eval (if (prolog-atleast-version '(3 . 7))
615 "prolog:zap_file(%m,%b,compile,%l)."
616 "prolog:zap_file(%m,%b,compile).")))
617 (swi "[%f].")
618 (t "compile(%f)."))
619 "*Alist of strings and lists defining predicate for recompilation.
621 Some parts of the string are replaced:
622 `%f' by the name of the compiled file (can be a temporary file)
623 `%b' by the file name of the buffer to compile
624 `%m' by the module name and name of the compiled file separated by colon
625 `%l' by the line offset into the file. This is 0 unless compiling a
626 region of a buffer, in which case it is the number of lines before
627 the region.
629 If `prolog-program-name' is non-nil, it is a string sent to a Prolog process.
630 If `prolog-program-name' is nil, it is an argument to the `compile' function."
631 :group 'prolog-inferior
632 :type 'sexp)
633 (defun prolog-compile-string ()
634 (prolog-find-value-by-system prolog-compile-string))
636 (defcustom prolog-eof-string "end_of_file.\n"
637 "*Alist of strings that represent end of file for prolog.
638 nil means send actual operating system end of file."
639 :group 'prolog-inferior
640 :type 'sexp)
642 (defcustom prolog-prompt-regexp
643 '((eclipse "^[a-zA-Z0-9()]* *\\?- \\|^\\[[a-zA-Z]* [0-9]*\\]:")
644 (sicstus "| [ ?][- ] *")
645 (swi "^\\(\\[[a-zA-Z]*\\] \\)?[1-9]?[0-9]*[ ]?\\?- \\|^| +")
646 (gnu "^| \\?-")
647 (t "^|? *\\?-"))
648 "*Alist of prompts of the prolog system command line."
649 :group 'prolog-inferior
650 :type 'sexp)
651 (defun prolog-prompt-regexp ()
652 (prolog-find-value-by-system prolog-prompt-regexp))
654 ;; (defcustom prolog-continued-prompt-regexp
655 ;; '((sicstus "^\\(| +\\| +\\)")
656 ;; (t "^|: +"))
657 ;; "*Alist of regexps matching the prompt when consulting `user'."
658 ;; :group 'prolog-inferior
659 ;; :type 'sexp)
661 (defcustom prolog-debug-on-string "debug.\n"
662 "*Predicate for enabling debug mode."
663 :group 'prolog-inferior
664 :type 'string)
666 (defcustom prolog-debug-off-string "nodebug.\n"
667 "*Predicate for disabling debug mode."
668 :group 'prolog-inferior
669 :type 'string)
671 (defcustom prolog-trace-on-string "trace.\n"
672 "*Predicate for enabling tracing."
673 :group 'prolog-inferior
674 :type 'string)
676 (defcustom prolog-trace-off-string "notrace.\n"
677 "*Predicate for disabling tracing."
678 :group 'prolog-inferior
679 :type 'string)
681 (defcustom prolog-zip-on-string "zip.\n"
682 "*Predicate for enabling zip mode for SICStus."
683 :group 'prolog-inferior
684 :type 'string)
686 (defcustom prolog-zip-off-string "nozip.\n"
687 "*Predicate for disabling zip mode for SICStus."
688 :group 'prolog-inferior
689 :type 'string)
691 (defcustom prolog-use-standard-consult-compile-method-flag t
692 "*Non-nil means use the standard compilation method.
693 Otherwise the new compilation method will be used. This
694 utilises a special compilation buffer with the associated
695 features such as parsing of error messages and automatically
696 jumping to the source code responsible for the error.
698 Warning: the new method is so far only experimental and
699 does contain bugs. The recommended setting for the novice user
700 is non-nil for this variable."
701 :group 'prolog-inferior
702 :type 'boolean)
705 ;; Miscellaneous
707 (defcustom prolog-use-prolog-tokenizer-flag
708 (not (fboundp 'syntax-propertize-rules))
709 "*Non-nil means use the internal prolog tokenizer for indentation etc.
710 Otherwise use `parse-partial-sexp' which is faster but sometimes incorrect."
711 :group 'prolog-other
712 :type 'boolean)
714 (defcustom prolog-imenu-flag t
715 "*Non-nil means add a clause index menu for all prolog files."
716 :group 'prolog-other
717 :type 'boolean)
719 (defcustom prolog-imenu-max-lines 3000
720 "*The maximum number of lines of the file for imenu to be enabled.
721 Relevant only when `prolog-imenu-flag' is non-nil."
722 :group 'prolog-other
723 :type 'integer)
725 (defcustom prolog-info-predicate-index
726 "(sicstus)Predicate Index"
727 "*The info node for the SICStus predicate index."
728 :group 'prolog-other
729 :type 'string)
731 (defcustom prolog-underscore-wordchar-flag nil
732 "*Non-nil means underscore (_) is a word-constituent character."
733 :group 'prolog-other
734 :type 'boolean)
736 (defcustom prolog-use-sicstus-sd nil
737 "*If non-nil, use the source level debugger of SICStus 3#7 and later."
738 :group 'prolog-other
739 :type 'boolean)
741 (defcustom prolog-char-quote-workaround nil
742 "*If non-nil, declare 0 as a quote character to handle 0'<char>.
743 This is really kludgy, and unneeded (i.e. obsolete) in Emacs>=24."
744 :group 'prolog-other
745 :type 'boolean)
748 ;;-------------------------------------------------------------------
749 ;; Internal variables
750 ;;-------------------------------------------------------------------
752 ;;(defvar prolog-temp-filename "") ; Later set by `prolog-temporary-file'
754 (defvar prolog-mode-syntax-table
755 ;; The syntax accepted varies depending on the implementation used.
756 ;; Here are some of the differences:
757 ;; - SWI-Prolog accepts nested /*..*/ comments.
758 ;; - Edinburgh-style Prologs take <radix>'<number> for non-decimal number,
759 ;; whereas ISO-style Prologs use 0[obx]<number> instead.
760 ;; - In atoms \x<hex> sometimes needs a terminating \ (ISO-style)
761 ;; and sometimes not.
762 (let ((table (make-syntax-table)))
763 (if prolog-underscore-wordchar-flag
764 (modify-syntax-entry ?_ "w" table)
765 (modify-syntax-entry ?_ "_" table))
767 (modify-syntax-entry ?+ "." table)
768 (modify-syntax-entry ?- "." table)
769 (modify-syntax-entry ?= "." table)
770 (modify-syntax-entry ?< "." table)
771 (modify-syntax-entry ?> "." table)
772 (modify-syntax-entry ?| "." table)
773 (modify-syntax-entry ?\' "\"" table)
775 ;; Any better way to handle the 0'<char> construct?!?
776 (when prolog-char-quote-workaround
777 (modify-syntax-entry ?0 "\\" table))
779 (modify-syntax-entry ?% "<" table)
780 (modify-syntax-entry ?\n ">" table)
781 (if (featurep 'xemacs)
782 (progn
783 (modify-syntax-entry ?* ". 67" table)
784 (modify-syntax-entry ?/ ". 58" table)
786 ;; Emacs wants to see this it seems:
787 (modify-syntax-entry ?* ". 23b" table)
788 (modify-syntax-entry ?/ ". 14" table)
790 table))
791 (defvar prolog-mode-abbrev-table nil)
792 (defvar prolog-upper-case-string ""
793 "A string containing all upper case characters.
794 Set by prolog-build-case-strings.")
795 (defvar prolog-lower-case-string ""
796 "A string containing all lower case characters.
797 Set by prolog-build-case-strings.")
799 (defvar prolog-atom-char-regexp ""
800 "Set by prolog-set-atom-regexps.")
801 ;; "Regexp specifying characters which constitute atoms without quoting.")
802 (defvar prolog-atom-regexp ""
803 "Set by prolog-set-atom-regexps.")
805 (defconst prolog-left-paren "[[({]" ;FIXME: Why not \\s(?
806 "The characters used as left parentheses for the indentation code.")
807 (defconst prolog-right-paren "[])}]" ;FIXME: Why not \\s)?
808 "The characters used as right parentheses for the indentation code.")
810 (defconst prolog-quoted-atom-regexp
811 "\\(^\\|[^0-9]\\)\\('\\([^\n']\\|\\\\'\\)*'\\)"
812 "Regexp matching a quoted atom.")
813 (defconst prolog-string-regexp
814 "\\(\"\\([^\n\"]\\|\\\\\"\\)*\"\\)"
815 "Regexp matching a string.")
816 (defconst prolog-head-delimiter "\\(:-\\|\\+:\\|-:\\|\\+\\?\\|-\\?\\|-->\\)"
817 "A regexp for matching on the end delimiter of a head (e.g. \":-\").")
819 (defvar prolog-compilation-buffer "*prolog-compilation*"
820 "Name of the output buffer for Prolog compilation/consulting.")
822 (defvar prolog-temporary-file-name nil)
823 (defvar prolog-keywords-i nil)
824 (defvar prolog-types-i nil)
825 (defvar prolog-mode-specificators-i nil)
826 (defvar prolog-determinism-specificators-i nil)
827 (defvar prolog-directives-i nil)
828 (defvar prolog-eof-string-i nil)
829 ;; (defvar prolog-continued-prompt-regexp-i nil)
830 (defvar prolog-help-function-i nil)
832 (defvar prolog-align-rules
833 (eval-when-compile
834 (mapcar
835 (lambda (x)
836 (let ((name (car x))
837 (sym (cdr x)))
838 `(,(intern (format "prolog-%s" name))
839 (regexp . ,(format "\\(\\s-*\\)%s\\(\\s-*\\)" sym))
840 (tab-stop . nil)
841 (modes . '(prolog-mode))
842 (group . (1 2)))))
843 '(("dcg" . "-->") ("rule" . ":-") ("simplification" . "<=>")
844 ("propagation" . "==>")))))
848 ;;-------------------------------------------------------------------
849 ;; Prolog mode
850 ;;-------------------------------------------------------------------
852 ;; Example: (prolog-atleast-version '(3 . 6))
853 (defun prolog-atleast-version (version)
854 "Return t if the version of the current prolog system is VERSION or later.
855 VERSION is of the format (Major . Minor)"
856 ;; Version.major < major or
857 ;; Version.major = major and Version.minor <= minor
858 (let* ((thisversion (prolog-find-value-by-system prolog-system-version))
859 (thismajor (car thisversion))
860 (thisminor (cdr thisversion)))
861 (or (< (car version) thismajor)
862 (and (= (car version) thismajor)
863 (<= (cdr version) thisminor)))
866 (define-abbrev-table 'prolog-mode-abbrev-table ())
868 (defun prolog-find-value-by-system (alist)
869 "Get value from ALIST according to `prolog-system'."
870 (let ((system (or prolog-system
871 (buffer-local-value 'prolog-system
872 (prolog-inferior-buffer 'dont-run)))))
873 (if (listp alist)
874 (let (result
876 (while alist
877 (setq id (car (car alist)))
878 (if (or (eq id system)
879 (eq id t)
880 (and (listp id)
881 (eval id)))
882 (progn
883 (setq result (car (cdr (car alist))))
884 (if (and (listp result)
885 (eq (car result) 'eval))
886 (setq result (eval (car (cdr result)))))
887 (setq alist nil))
888 (setq alist (cdr alist))))
889 result)
890 alist)))
892 (defconst prolog-syntax-propertize-function
893 (when (fboundp 'syntax-propertize-rules)
894 (syntax-propertize-rules
895 ;; GNU Prolog only accepts 0'\' rather than 0'', but the only
896 ;; possible meaning of 0'' is rather clear.
897 ("\\<0\\(''?\\)"
898 (1 (unless (save-excursion (nth 8 (syntax-ppss (match-beginning 0))))
899 (string-to-syntax "_"))))
900 ;; We could check that we're not inside an atom, but I don't think
901 ;; that 'foo 8'z could be a valid syntax anyway, so why bother?
902 ("\\<[1-9][0-9]*\\('\\)[0-9a-zA-Z]" (1 "_"))
903 ;; Supposedly, ISO-Prolog wants \NNN\ for octal and \xNNN\ for hexadecimal
904 ;; escape sequences in atoms, so be careful not to let the terminating \
905 ;; escape a subsequent quote.
906 ("\\\\[x0-7][0-9a-fA-F]*\\(\\\\\\)" (1 "_"))
909 (defun prolog-mode-variables ()
910 "Set some common variables to Prolog code specific values."
911 (setq local-abbrev-table prolog-mode-abbrev-table)
912 (set (make-local-variable 'paragraph-start)
913 (concat "[ \t]*$\\|" page-delimiter)) ;'%%..'
914 (set (make-local-variable 'paragraph-separate) paragraph-start)
915 (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
916 (set (make-local-variable 'normal-auto-fill-function) 'prolog-do-auto-fill)
917 (set (make-local-variable 'indent-line-function) 'prolog-indent-line)
918 (set (make-local-variable 'comment-start) "%")
919 (set (make-local-variable 'comment-end) "")
920 (set (make-local-variable 'comment-add) 1)
921 (set (make-local-variable 'comment-start-skip)
922 ;; This complex regexp makes sure that comments cannot start
923 ;; inside quoted atoms or strings
924 (format "^\\(\\(%s\\|%s\\|[^\n\'\"%%]\\)*\\)\\(/\\*+ *\\|%%+ *\\)"
925 prolog-quoted-atom-regexp prolog-string-regexp))
926 (set (make-local-variable 'comment-indent-function) 'prolog-comment-indent)
927 (set (make-local-variable 'parens-require-spaces) nil)
928 ;; Initialize Prolog system specific variables
929 (dolist (var '(prolog-keywords prolog-types prolog-mode-specificators
930 prolog-determinism-specificators prolog-directives
931 prolog-eof-string
932 ;; prolog-continued-prompt-regexp
933 prolog-help-function))
934 (set (intern (concat (symbol-name var) "-i"))
935 (prolog-find-value-by-system (symbol-value var))))
936 (when (null (prolog-program-name))
937 (set (make-local-variable 'compile-command) (prolog-compile-string)))
938 (set (make-local-variable 'font-lock-defaults)
939 '(prolog-font-lock-keywords nil nil ((?_ . "w"))))
940 (set (make-local-variable 'syntax-propertize-function)
941 prolog-syntax-propertize-function)
944 (defun prolog-mode-keybindings-common (map)
945 "Define keybindings common to both Prolog modes in MAP."
946 (define-key map "\C-c?" 'prolog-help-on-predicate)
947 (define-key map "\C-c/" 'prolog-help-apropos)
948 (define-key map "\C-c\C-d" 'prolog-debug-on)
949 (define-key map "\C-c\C-t" 'prolog-trace-on)
950 (define-key map "\C-c\C-z" 'prolog-zip-on)
951 (define-key map "\C-c\r" 'run-prolog))
953 (defun prolog-mode-keybindings-edit (map)
954 "Define keybindings for Prolog mode in MAP."
955 (define-key map "\M-a" 'prolog-beginning-of-clause)
956 (define-key map "\M-e" 'prolog-end-of-clause)
957 (define-key map "\M-q" 'prolog-fill-paragraph)
958 (define-key map "\C-c\C-a" 'align)
959 (define-key map "\C-\M-a" 'prolog-beginning-of-predicate)
960 (define-key map "\C-\M-e" 'prolog-end-of-predicate)
961 (define-key map "\M-\C-c" 'prolog-mark-clause)
962 (define-key map "\M-\C-h" 'prolog-mark-predicate)
963 (define-key map "\M-\C-n" 'prolog-forward-list)
964 (define-key map "\M-\C-p" 'prolog-backward-list)
965 (define-key map "\C-c\C-n" 'prolog-insert-predicate-template)
966 (define-key map "\C-c\C-s" 'prolog-insert-predspec)
967 (define-key map "\M-\r" 'prolog-insert-next-clause)
968 (define-key map "\C-c\C-va" 'prolog-variables-to-anonymous)
969 (define-key map "\C-c\C-v\C-s" 'prolog-view-predspec)
971 (define-key map [Backspace] 'prolog-electric-delete)
972 (define-key map "." 'prolog-electric-dot)
973 (define-key map "_" 'prolog-electric-underscore)
974 (define-key map "(" 'prolog-electric-if-then-else)
975 (define-key map ";" 'prolog-electric-if-then-else)
976 (define-key map ">" 'prolog-electric-if-then-else)
977 (define-key map ":" 'prolog-electric-colon)
978 (define-key map "-" 'prolog-electric-dash)
979 (if prolog-electric-newline-flag
980 (define-key map "\r" 'newline-and-indent))
982 ;; If we're running SICStus, then map C-c C-c e/d to enabling
983 ;; and disabling of the source-level debugging facilities.
984 ;(if (and (eq prolog-system 'sicstus)
985 ; (prolog-atleast-version '(3 . 7)))
986 ; (progn
987 ; (define-key map "\C-c\C-ce" 'prolog-enable-sicstus-sd)
988 ; (define-key map "\C-c\C-cd" 'prolog-disable-sicstus-sd)
989 ; ))
991 (if prolog-old-sicstus-keys-flag
992 (progn
993 (define-key map "\C-c\C-c" 'prolog-consult-predicate)
994 (define-key map "\C-cc" 'prolog-consult-region)
995 (define-key map "\C-cC" 'prolog-consult-buffer)
996 (define-key map "\C-c\C-k" 'prolog-compile-predicate)
997 (define-key map "\C-ck" 'prolog-compile-region)
998 (define-key map "\C-cK" 'prolog-compile-buffer))
999 (define-key map "\C-c\C-p" 'prolog-consult-predicate)
1000 (define-key map "\C-c\C-r" 'prolog-consult-region)
1001 (define-key map "\C-c\C-b" 'prolog-consult-buffer)
1002 (define-key map "\C-c\C-f" 'prolog-consult-file)
1003 (define-key map "\C-c\C-cp" 'prolog-compile-predicate)
1004 (define-key map "\C-c\C-cr" 'prolog-compile-region)
1005 (define-key map "\C-c\C-cb" 'prolog-compile-buffer)
1006 (define-key map "\C-c\C-cf" 'prolog-compile-file))
1008 ;; Inherited from the old prolog.el.
1009 (define-key map "\e\C-x" 'prolog-consult-region)
1010 (define-key map "\C-c\C-l" 'prolog-consult-file)
1011 (define-key map "\C-c\C-z" 'switch-to-prolog))
1013 (defun prolog-mode-keybindings-inferior (_map)
1014 "Define keybindings for inferior Prolog mode in MAP."
1015 ;; No inferior mode specific keybindings now.
1018 (defvar prolog-mode-map
1019 (let ((map (make-sparse-keymap)))
1020 (prolog-mode-keybindings-common map)
1021 (prolog-mode-keybindings-edit map)
1022 map))
1025 (defvar prolog-mode-hook nil
1026 "List of functions to call after the prolog mode has initialized.")
1028 (unless (fboundp 'prog-mode)
1029 (defalias 'prog-mode 'fundamental-mode))
1030 ;;;###autoload
1031 (define-derived-mode prolog-mode prog-mode "Prolog"
1032 "Major mode for editing Prolog code.
1034 Blank lines and `%%...' separate paragraphs. `%'s starts a comment
1035 line and comments can also be enclosed in /* ... */.
1037 If an optional argument SYSTEM is non-nil, set up mode for the given system.
1039 To find out what version of Prolog mode you are running, enter
1040 `\\[prolog-mode-version]'.
1042 Commands:
1043 \\{prolog-mode-map}
1044 Entry to this mode calls the value of `prolog-mode-hook'
1045 if that value is non-nil."
1046 (setq mode-name (concat "Prolog"
1047 (cond
1048 ((eq prolog-system 'eclipse) "[ECLiPSe]")
1049 ((eq prolog-system 'sicstus) "[SICStus]")
1050 ((eq prolog-system 'swi) "[SWI]")
1051 ((eq prolog-system 'gnu) "[GNU]")
1052 (t ""))))
1053 (prolog-mode-variables)
1054 (prolog-build-case-strings)
1055 (prolog-set-atom-regexps)
1056 (dolist (ar prolog-align-rules) (add-to-list 'align-rules-list ar))
1058 ;; imenu entry moved to the appropriate hook for consistency
1060 ;; Load SICStus debugger if suitable
1061 (if (and (eq prolog-system 'sicstus)
1062 (prolog-atleast-version '(3 . 7))
1063 prolog-use-sicstus-sd)
1064 (prolog-enable-sicstus-sd))
1066 (prolog-menu))
1068 (defvar mercury-mode-map
1069 (let ((map (make-sparse-keymap)))
1070 (set-keymap-parent map prolog-mode-map)
1071 map))
1073 ;;;###autoload
1074 (define-derived-mode mercury-mode prolog-mode "Prolog[Mercury]"
1075 "Major mode for editing Mercury programs.
1076 Actually this is just customized `prolog-mode'."
1077 (set (make-local-variable 'prolog-system) 'mercury))
1080 ;;-------------------------------------------------------------------
1081 ;; Inferior prolog mode
1082 ;;-------------------------------------------------------------------
1084 (defvar prolog-inferior-mode-map
1085 (let ((map (make-sparse-keymap)))
1086 (prolog-mode-keybindings-common map)
1087 (prolog-mode-keybindings-inferior map)
1088 (define-key map [remap self-insert-command]
1089 'prolog-inferior-self-insert-command)
1090 map))
1092 (defvar prolog-inferior-mode-hook nil
1093 "List of functions to call after the inferior prolog mode has initialized.")
1095 (defvar prolog-inferior-error-regexp-alist
1096 '(;; GNU Prolog used to not follow the GNU standard format.
1097 ;; ("^\\(.*?\\):\\([0-9]+\\) error: .*(char:\\([0-9]+\\)" 1 2 3)
1098 ;; SWI-Prolog.
1099 ("^\\(?:\\?- *\\)?\\(\\(?:ERROR\\|\\(W\\)arning\\): *\\(.*?\\):\\([1-9][0-9]*\\):\\(?:\\([0-9]*\\):\\)?\\)\\(?:$\\| \\)"
1100 3 4 5 (2 . nil) 1)
1101 ;; GNU-Prolog now uses the GNU standard format.
1102 gnu))
1104 (defun prolog-inferior-self-insert-command ()
1105 "Insert the char in the buffer or pass it directly to the process."
1106 (interactive)
1107 (let* ((proc (get-buffer-process (current-buffer)))
1108 (pmark (and proc (marker-position (process-mark proc)))))
1109 ;; FIXME: the same treatment would be needed for SWI-Prolog, but I can't
1110 ;; seem to find any way for Emacs to figure out when to use it because
1111 ;; SWI doesn't include a " ? " or some such recognizable marker.
1112 (if (and (eq prolog-system 'gnu)
1113 pmark
1114 (null current-prefix-arg)
1115 (eobp)
1116 (eq (point) pmark)
1117 (save-excursion
1118 (goto-char (- pmark 3))
1119 ;; FIXME: check this comes from the process's output, maybe?
1120 (looking-at " \\? ")))
1121 ;; This is GNU prolog waiting to know whether you want more answers
1122 ;; or not (or abort, etc...). The answer is a single char, not
1123 ;; a line, so pass this char directly rather than wait for RET to
1124 ;; send a whole line.
1125 (comint-send-string proc (string last-command-event))
1126 (call-interactively 'self-insert-command))))
1128 (declare-function 'compilation-shell-minor-mode "compile" (&optional arg))
1129 (defvar compilation-error-regexp-alist)
1131 (define-derived-mode prolog-inferior-mode comint-mode "Inferior Prolog"
1132 "Major mode for interacting with an inferior Prolog process.
1134 The following commands are available:
1135 \\{prolog-inferior-mode-map}
1137 Entry to this mode calls the value of `prolog-mode-hook' with no arguments,
1138 if that value is non-nil. Likewise with the value of `comint-mode-hook'.
1139 `prolog-mode-hook' is called after `comint-mode-hook'.
1141 You can send text to the inferior Prolog from other buffers
1142 using the commands `send-region', `send-string' and \\[prolog-consult-region].
1144 Commands:
1145 Tab indents for Prolog; with argument, shifts rest
1146 of expression rigidly with the current line.
1147 Paragraphs are separated only by blank lines and '%%'. '%'s start comments.
1149 Return at end of buffer sends line as input.
1150 Return not at end copies rest of line to end and sends it.
1151 \\[comint-delchar-or-maybe-eof] sends end-of-file as input.
1152 \\[comint-kill-input] and \\[backward-kill-word] are kill commands,
1153 imitating normal Unix input editing.
1154 \\[comint-interrupt-subjob] interrupts the shell or its current subjob if any.
1155 \\[comint-stop-subjob] stops, likewise.
1156 \\[comint-quit-subjob] sends quit signal, likewise.
1158 To find out what version of Prolog mode you are running, enter
1159 `\\[prolog-mode-version]'."
1160 (require 'compile)
1161 (setq comint-input-filter 'prolog-input-filter)
1162 (setq mode-line-process '(": %s"))
1163 (prolog-mode-variables)
1164 (setq comint-prompt-regexp (prolog-prompt-regexp))
1165 (set (make-local-variable 'shell-dirstack-query) "pwd.")
1166 (set (make-local-variable 'compilation-error-regexp-alist)
1167 prolog-inferior-error-regexp-alist)
1168 (compilation-shell-minor-mode)
1169 (prolog-inferior-menu))
1171 (defun prolog-input-filter (str)
1172 (cond ((string-match "\\`\\s *\\'" str) nil) ;whitespace
1173 ((not (derived-mode-p 'prolog-inferior-mode)) t)
1174 ((= (length str) 1) nil) ;one character
1175 ((string-match "\\`[rf] *[0-9]*\\'" str) nil) ;r(edo) or f(ail)
1176 (t t)))
1178 ;;;###autoload
1179 (defun run-prolog (arg)
1180 "Run an inferior Prolog process, input and output via buffer *prolog*.
1181 With prefix argument ARG, restart the Prolog process if running before."
1182 (interactive "P")
1183 ;; FIXME: It should be possible to interactively specify the command to use
1184 ;; to run prolog.
1185 (if (and arg (get-process "prolog"))
1186 (progn
1187 (process-send-string "prolog" "halt.\n")
1188 (while (get-process "prolog") (sit-for 0.1))))
1189 (let ((buff (buffer-name)))
1190 (if (not (string= buff "*prolog*"))
1191 (prolog-goto-prolog-process-buffer))
1192 ;; Load SICStus debugger if suitable
1193 (if (and (eq prolog-system 'sicstus)
1194 (prolog-atleast-version '(3 . 7))
1195 prolog-use-sicstus-sd)
1196 (prolog-enable-sicstus-sd))
1197 (prolog-mode-variables)
1198 (prolog-ensure-process)
1201 (defun prolog-inferior-guess-flavor (&optional ignored)
1202 (setq prolog-system
1203 (when (or (numberp prolog-system) (markerp prolog-system))
1204 (save-excursion
1205 (goto-char (1+ prolog-system))
1206 (cond
1207 ((looking-at "GNU Prolog") 'gnu)
1208 ((looking-at "Welcome to SWI-Prolog\\|%.*\\<swi_") 'swi)
1209 ((looking-at ".*\n") nil) ;There's at least one line.
1210 (t prolog-system)))))
1211 (when (symbolp prolog-system)
1212 (remove-hook 'comint-output-filter-functions
1213 'prolog-inferior-guess-flavor t)
1214 (when prolog-system
1215 (setq comint-prompt-regexp (prolog-prompt-regexp))
1216 (if (eq prolog-system 'gnu)
1217 (set (make-local-variable 'comint-process-echoes) t)))))
1219 (defun prolog-ensure-process (&optional wait)
1220 "If Prolog process is not running, run it.
1221 If the optional argument WAIT is non-nil, wait for Prolog prompt specified by
1222 the variable `prolog-prompt-regexp'."
1223 (if (null (prolog-program-name))
1224 (error "This Prolog system has defined no interpreter."))
1225 (if (comint-check-proc "*prolog*")
1227 (with-current-buffer (get-buffer-create "*prolog*")
1228 (prolog-inferior-mode)
1229 (apply 'make-comint-in-buffer "prolog" (current-buffer)
1230 (prolog-program-name) nil (prolog-program-switches))
1231 (unless prolog-system
1232 ;; Setup auto-detection.
1233 (set (make-local-variable 'prolog-system)
1234 ;; Force re-detection.
1235 (let* ((proc (get-buffer-process (current-buffer)))
1236 (pmark (and proc (marker-position (process-mark proc)))))
1237 (cond
1238 ((null pmark) (1- (point-min)))
1239 ;; The use of insert-before-markers in comint.el together with
1240 ;; the potential use of comint-truncate-buffer in the output
1241 ;; filter, means that it's difficult to reliably keep track of
1242 ;; the buffer position where the process's output started.
1243 ;; If possible we use a marker at "start - 1", so that
1244 ;; insert-before-marker at `start' won't shift it. And if not,
1245 ;; we fall back on using a plain integer.
1246 ((> pmark (point-min)) (copy-marker (1- pmark)))
1247 (t (1- pmark)))))
1248 (add-hook 'comint-output-filter-functions
1249 'prolog-inferior-guess-flavor nil t))
1250 (if wait
1251 (progn
1252 (goto-char (point-max))
1253 (while
1254 (save-excursion
1255 (not
1256 (re-search-backward
1257 (concat "\\(" (prolog-prompt-regexp) "\\)" "\\=")
1258 nil t)))
1259 (sit-for 0.1)))))))
1261 (defun prolog-inferior-buffer (&optional dont-run)
1262 (or (get-buffer "*prolog*")
1263 (unless dont-run
1264 (prolog-ensure-process)
1265 (get-buffer "*prolog*"))))
1267 (defun prolog-process-insert-string (process string)
1268 "Insert STRING into inferior Prolog buffer running PROCESS."
1269 ;; Copied from elisp manual, greek to me
1270 (with-current-buffer (process-buffer process)
1271 ;; FIXME: Use window-point-insertion-type instead.
1272 (let ((moving (= (point) (process-mark process))))
1273 (save-excursion
1274 ;; Insert the text, moving the process-marker.
1275 (goto-char (process-mark process))
1276 (insert string)
1277 (set-marker (process-mark process) (point)))
1278 (if moving (goto-char (process-mark process))))))
1280 ;;------------------------------------------------------------
1281 ;; Old consulting and compiling functions
1282 ;;------------------------------------------------------------
1284 (declare-function compilation-forget-errors "compile" ())
1285 (declare-function compilation-fake-loc "compile"
1286 (marker file &optional line col))
1288 (defun prolog-old-process-region (compilep start end)
1289 "Process the region limited by START and END positions.
1290 If COMPILEP is non-nil then use compilation, otherwise consulting."
1291 (prolog-ensure-process)
1292 ;(let ((tmpfile prolog-temp-filename)
1293 (let ((tmpfile (prolog-temporary-file))
1294 ;(process (get-process "prolog"))
1295 (first-line (1+ (count-lines
1296 (point-min)
1297 (save-excursion
1298 (goto-char start)
1299 (point))))))
1300 (write-region start end tmpfile)
1301 (setq start (copy-marker start))
1302 (with-current-buffer (prolog-inferior-buffer)
1303 (compilation-forget-errors)
1304 (compilation-fake-loc start tmpfile))
1305 (process-send-string
1306 "prolog" (prolog-build-prolog-command
1307 compilep tmpfile (prolog-bsts buffer-file-name)
1308 first-line))
1309 (prolog-goto-prolog-process-buffer)))
1311 (defun prolog-old-process-predicate (compilep)
1312 "Process the predicate around point.
1313 If COMPILEP is non-nil then use compilation, otherwise consulting."
1314 (prolog-old-process-region
1315 compilep (prolog-pred-start) (prolog-pred-end)))
1317 (defun prolog-old-process-buffer (compilep)
1318 "Process the entire buffer.
1319 If COMPILEP is non-nil then use compilation, otherwise consulting."
1320 (prolog-old-process-region compilep (point-min) (point-max)))
1322 (defun prolog-old-process-file (compilep)
1323 "Process the file of the current buffer.
1324 If COMPILEP is non-nil then use compilation, otherwise consulting."
1325 (save-some-buffers)
1326 (prolog-ensure-process)
1327 (with-current-buffer (prolog-inferior-buffer)
1328 (compilation-forget-errors))
1329 (process-send-string
1330 "prolog" (prolog-build-prolog-command
1331 compilep buffer-file-name
1332 (prolog-bsts buffer-file-name)))
1333 (prolog-goto-prolog-process-buffer))
1336 ;;------------------------------------------------------------
1337 ;; Consulting and compiling
1338 ;;------------------------------------------------------------
1340 ;; Interactive interface functions, used by both the standard
1341 ;; and the experimental consultation and compilation functions
1342 (defun prolog-consult-file ()
1343 "Consult file of current buffer."
1344 (interactive)
1345 (if prolog-use-standard-consult-compile-method-flag
1346 (prolog-old-process-file nil)
1347 (prolog-consult-compile-file nil)))
1349 (defun prolog-consult-buffer ()
1350 "Consult buffer."
1351 (interactive)
1352 (if prolog-use-standard-consult-compile-method-flag
1353 (prolog-old-process-buffer nil)
1354 (prolog-consult-compile-buffer nil)))
1356 (defun prolog-consult-region (beg end)
1357 "Consult region between BEG and END."
1358 (interactive "r")
1359 (if prolog-use-standard-consult-compile-method-flag
1360 (prolog-old-process-region nil beg end)
1361 (prolog-consult-compile-region nil beg end)))
1363 (defun prolog-consult-predicate ()
1364 "Consult the predicate around current point."
1365 (interactive)
1366 (if prolog-use-standard-consult-compile-method-flag
1367 (prolog-old-process-predicate nil)
1368 (prolog-consult-compile-predicate nil)))
1370 (defun prolog-compile-file ()
1371 "Compile file of current buffer."
1372 (interactive)
1373 (if prolog-use-standard-consult-compile-method-flag
1374 (prolog-old-process-file t)
1375 (prolog-consult-compile-file t)))
1377 (defun prolog-compile-buffer ()
1378 "Compile buffer."
1379 (interactive)
1380 (if prolog-use-standard-consult-compile-method-flag
1381 (prolog-old-process-buffer t)
1382 (prolog-consult-compile-buffer t)))
1384 (defun prolog-compile-region (beg end)
1385 "Compile region between BEG and END."
1386 (interactive "r")
1387 (if prolog-use-standard-consult-compile-method-flag
1388 (prolog-old-process-region t beg end)
1389 (prolog-consult-compile-region t beg end)))
1391 (defun prolog-compile-predicate ()
1392 "Compile the predicate around current point."
1393 (interactive)
1394 (if prolog-use-standard-consult-compile-method-flag
1395 (prolog-old-process-predicate t)
1396 (prolog-consult-compile-predicate t)))
1398 (defun prolog-buffer-module ()
1399 "Select Prolog module name appropriate for current buffer.
1400 Bases decision on buffer contents (-*- line)."
1401 ;; Look for -*- ... module: MODULENAME; ... -*-
1402 (let (beg end)
1403 (save-excursion
1404 (goto-char (point-min))
1405 (skip-chars-forward " \t")
1406 (and (search-forward "-*-" (line-end-position) t)
1407 (progn
1408 (skip-chars-forward " \t")
1409 (setq beg (point))
1410 (search-forward "-*-" (line-end-position) t))
1411 (progn
1412 (forward-char -3)
1413 (skip-chars-backward " \t")
1414 (setq end (point))
1415 (goto-char beg)
1416 (and (let ((case-fold-search t))
1417 (search-forward "module:" end t))
1418 (progn
1419 (skip-chars-forward " \t")
1420 (setq beg (point))
1421 (if (search-forward ";" end t)
1422 (forward-char -1)
1423 (goto-char end))
1424 (skip-chars-backward " \t")
1425 (buffer-substring beg (point)))))))))
1427 (defun prolog-build-prolog-command (compilep file buffername
1428 &optional first-line)
1429 "Make Prolog command for FILE compilation/consulting.
1430 If COMPILEP is non-nil, consider compilation, otherwise consulting."
1431 (let* ((compile-string
1432 ;; FIXME: If the process is not running yet, the auto-detection of
1433 ;; prolog-system won't help here, so we should make sure
1434 ;; we first run Prolog and then build the command.
1435 (if compilep (prolog-compile-string) (prolog-consult-string)))
1436 (module (prolog-buffer-module))
1437 (file-name (concat "'" (prolog-bsts file) "'"))
1438 (module-name (if module (concat "'" module "'")))
1439 (module-file (if module
1440 (concat module-name ":" file-name)
1441 file-name))
1442 strbeg strend
1443 (lineoffset (if first-line
1444 (- first-line 1)
1445 0)))
1447 ;; Assure that there is a buffer name
1448 (if (not buffername)
1449 (error "The buffer is not saved"))
1451 (if (not (string-match "\\`'.*'\\'" buffername)) ; Add quotes
1452 (setq buffername (concat "'" buffername "'")))
1453 (while (string-match "%m" compile-string)
1454 (setq strbeg (substring compile-string 0 (match-beginning 0)))
1455 (setq strend (substring compile-string (match-end 0)))
1456 (setq compile-string (concat strbeg module-file strend)))
1457 ;; FIXME: The code below will %-expand any %[fbl] that appears in
1458 ;; module-file.
1459 (while (string-match "%f" compile-string)
1460 (setq strbeg (substring compile-string 0 (match-beginning 0)))
1461 (setq strend (substring compile-string (match-end 0)))
1462 (setq compile-string (concat strbeg file-name strend)))
1463 (while (string-match "%b" compile-string)
1464 (setq strbeg (substring compile-string 0 (match-beginning 0)))
1465 (setq strend (substring compile-string (match-end 0)))
1466 (setq compile-string (concat strbeg buffername strend)))
1467 (while (string-match "%l" compile-string)
1468 (setq strbeg (substring compile-string 0 (match-beginning 0)))
1469 (setq strend (substring compile-string (match-end 0)))
1470 (setq compile-string (concat strbeg (format "%d" lineoffset) strend)))
1471 (concat compile-string "\n")))
1473 ;; The rest of this page is experimental code!
1475 ;; Global variables for process filter function
1476 (defvar prolog-process-flag nil
1477 "Non-nil means that a prolog task (i.e. a consultation or compilation job)
1478 is running.")
1479 (defvar prolog-consult-compile-output ""
1480 "Hold the unprocessed output from the current prolog task.")
1481 (defvar prolog-consult-compile-first-line 1
1482 "The number of the first line of the file to consult/compile.
1483 Used for temporary files.")
1484 (defvar prolog-consult-compile-file nil
1485 "The file to compile/consult (can be a temporary file).")
1486 (defvar prolog-consult-compile-real-file nil
1487 "The file name of the buffer to compile/consult.")
1489 (defvar compilation-parse-errors-function)
1491 (defun prolog-consult-compile (compilep file &optional first-line)
1492 "Consult/compile FILE.
1493 If COMPILEP is non-nil, perform compilation, otherwise perform CONSULTING.
1494 COMMAND is a string described by the variables `prolog-consult-string'
1495 and `prolog-compile-string'.
1496 Optional argument FIRST-LINE is the number of the first line in the compiled
1497 region.
1499 This function must be called from the source code buffer."
1500 (if prolog-process-flag
1501 (error "Another Prolog task is running."))
1502 (prolog-ensure-process t)
1503 (let* ((buffer (get-buffer-create prolog-compilation-buffer))
1504 (real-file buffer-file-name)
1505 (command-string (prolog-build-prolog-command compilep file
1506 real-file first-line))
1507 (process (get-process "prolog"))
1508 (old-filter (process-filter process)))
1509 (with-current-buffer buffer
1510 (delete-region (point-min) (point-max))
1511 ;; FIXME: Wasn't this supposed to use prolog-inferior-mode?
1512 (compilation-mode)
1513 ;; FIXME: This doesn't seem to cooperate well with new(ish) compile.el.
1514 ;; Setting up font-locking for this buffer
1515 (set (make-local-variable 'font-lock-defaults)
1516 '(prolog-font-lock-keywords nil nil ((?_ . "w"))))
1517 (if (eq prolog-system 'sicstus)
1518 ;; FIXME: This looks really problematic: not only is this using
1519 ;; the old compilation-parse-errors-function, but
1520 ;; prolog-parse-sicstus-compilation-errors only accepts one argument
1521 ;; whereas compile.el calls it with 2 (and did so at least since
1522 ;; Emacs-20).
1523 (set (make-local-variable 'compilation-parse-errors-function)
1524 'prolog-parse-sicstus-compilation-errors))
1525 (toggle-read-only 0)
1526 (insert command-string "\n"))
1527 (save-selected-window
1528 (pop-to-buffer buffer))
1529 (setq prolog-process-flag t
1530 prolog-consult-compile-output ""
1531 prolog-consult-compile-first-line (if first-line (1- first-line) 0)
1532 prolog-consult-compile-file file
1533 prolog-consult-compile-real-file (if (string=
1534 file buffer-file-name)
1536 real-file))
1537 (with-current-buffer buffer
1538 (goto-char (point-max))
1539 (set-process-filter process 'prolog-consult-compile-filter)
1540 (process-send-string "prolog" command-string)
1541 ;; (prolog-build-prolog-command compilep file real-file first-line))
1542 (while (and prolog-process-flag
1543 (accept-process-output process 10)) ; 10 secs is ok?
1544 (sit-for 0.1)
1545 (unless (get-process "prolog")
1546 (setq prolog-process-flag nil)))
1547 (insert (if compilep
1548 "\nCompilation finished.\n"
1549 "\nConsulted.\n"))
1550 (set-process-filter process old-filter))))
1552 (defvar compilation-error-list)
1554 (defun prolog-parse-sicstus-compilation-errors (limit)
1555 "Parse the prolog compilation buffer for errors.
1556 Argument LIMIT is a buffer position limiting searching.
1557 For use with the `compilation-parse-errors-function' variable."
1558 (setq compilation-error-list nil)
1559 (message "Parsing SICStus error messages...")
1560 (let (filepath dir file errorline)
1561 (while
1562 (re-search-backward
1563 "{\\([a-zA-Z ]* ERROR\\|Warning\\):.* in line[s ]*\\([0-9]+\\)"
1564 limit t)
1565 (setq errorline (string-to-number (match-string 2)))
1566 (save-excursion
1567 (re-search-backward
1568 "{\\(consulting\\|compiling\\|processing\\) \\(.*\\)\\.\\.\\.}"
1569 limit t)
1570 (setq filepath (match-string 2)))
1572 ;; ###### Does this work with SICStus under Windows (i.e. backslahes and stuff?)
1573 (if (string-match "\\(.*/\\)\\([^/]*\\)$" filepath)
1574 (progn
1575 (setq dir (match-string 1 filepath))
1576 (setq file (match-string 2 filepath))))
1578 (setq compilation-error-list
1579 (cons
1580 (cons (save-excursion
1581 (beginning-of-line)
1582 (point-marker))
1583 (list (list file dir) errorline))
1584 compilation-error-list)
1588 (defun prolog-consult-compile-filter (process output)
1589 "Filter function for Prolog compilation PROCESS.
1590 Argument OUTPUT is a name of the output file."
1591 ;;(message "start")
1592 (setq prolog-consult-compile-output
1593 (concat prolog-consult-compile-output output))
1594 ;;(message "pccf1: %s" prolog-consult-compile-output)
1595 ;; Iterate through the lines of prolog-consult-compile-output
1596 (let (outputtype)
1597 (while (and prolog-process-flag
1599 ;; Trace question
1600 (progn
1601 (setq outputtype 'trace)
1602 (and (eq prolog-system 'sicstus)
1603 (string-match
1604 "^[ \t]*[0-9]+[ \t]*[0-9]+[ \t]*Call:.*? "
1605 prolog-consult-compile-output)))
1607 ;; Match anything
1608 (progn
1609 (setq outputtype 'normal)
1610 (string-match "^.*\n" prolog-consult-compile-output))
1612 ;;(message "outputtype: %s" outputtype)
1614 (setq output (match-string 0 prolog-consult-compile-output))
1615 ;; remove the text in output from prolog-consult-compile-output
1616 (setq prolog-consult-compile-output
1617 (substring prolog-consult-compile-output (length output)))
1618 ;;(message "pccf2: %s" prolog-consult-compile-output)
1620 ;; If temporary files were used, then we change the error
1621 ;; messages to point to the original source file.
1622 ;; FIXME: Use compilation-fake-loc instead.
1623 (cond
1625 ;; If the prolog process was in trace mode then it requires
1626 ;; user input
1627 ((and (eq prolog-system 'sicstus)
1628 (eq outputtype 'trace))
1629 (let ((input (concat (read-string output) "\n")))
1630 (process-send-string process input)
1631 (setq output (concat output input))))
1633 ((eq prolog-system 'sicstus)
1634 (if (and prolog-consult-compile-real-file
1635 (string-match
1636 "\\({.*:.* in line[s ]*\\)\\([0-9]+\\)-\\([0-9]+\\)" output))
1637 (setq output (replace-match
1638 ;; Adds a {processing ...} line so that
1639 ;; `prolog-parse-sicstus-compilation-errors'
1640 ;; finds the real file instead of the temporary one.
1641 ;; Also fixes the line numbers.
1642 (format "Added by Emacs: {processing %s...}\n%s%d-%d"
1643 prolog-consult-compile-real-file
1644 (match-string 1 output)
1645 (+ prolog-consult-compile-first-line
1646 (string-to-number
1647 (match-string 2 output)))
1648 (+ prolog-consult-compile-first-line
1649 (string-to-number
1650 (match-string 3 output))))
1651 t t output)))
1654 ((eq prolog-system 'swi)
1655 (if (and prolog-consult-compile-real-file
1656 (string-match (format
1657 "%s\\([ \t]*:[ \t]*\\)\\([0-9]+\\)"
1658 prolog-consult-compile-file)
1659 output))
1660 (setq output (replace-match
1661 ;; Real filename + text + fixed linenum
1662 (format "%s%s%d"
1663 prolog-consult-compile-real-file
1664 (match-string 1 output)
1665 (+ prolog-consult-compile-first-line
1666 (string-to-number
1667 (match-string 2 output))))
1668 t t output)))
1671 (t ())
1673 ;; Write the output in the *prolog-compilation* buffer
1674 (insert output)))
1676 ;; If the prompt is visible, then the task is finished
1677 (if (string-match (prolog-prompt-regexp) prolog-consult-compile-output)
1678 (setq prolog-process-flag nil)))
1680 (defun prolog-consult-compile-file (compilep)
1681 "Consult/compile file of current buffer.
1682 If COMPILEP is non-nil, compile, otherwise consult."
1683 (let ((file buffer-file-name))
1684 (if file
1685 (progn
1686 (save-some-buffers)
1687 (prolog-consult-compile compilep file))
1688 (prolog-consult-compile-region compilep (point-min) (point-max)))))
1690 (defun prolog-consult-compile-buffer (compilep)
1691 "Consult/compile current buffer.
1692 If COMPILEP is non-nil, compile, otherwise consult."
1693 (prolog-consult-compile-region compilep (point-min) (point-max)))
1695 (defun prolog-consult-compile-region (compilep beg end)
1696 "Consult/compile region between BEG and END.
1697 If COMPILEP is non-nil, compile, otherwise consult."
1698 ;(let ((file prolog-temp-filename)
1699 (let ((file (prolog-bsts (prolog-temporary-file)))
1700 (lines (count-lines 1 beg)))
1701 (write-region beg end file nil 'no-message)
1702 (write-region "\n" nil file t 'no-message)
1703 (prolog-consult-compile compilep file
1704 (if (bolp) (1+ lines) lines))
1705 (delete-file file)))
1707 (defun prolog-consult-compile-predicate (compilep)
1708 "Consult/compile the predicate around current point.
1709 If COMPILEP is non-nil, compile, otherwise consult."
1710 (prolog-consult-compile-region
1711 compilep (prolog-pred-start) (prolog-pred-end)))
1714 ;;-------------------------------------------------------------------
1715 ;; Font-lock stuff
1716 ;;-------------------------------------------------------------------
1718 ;; Auxiliary functions
1719 (defun prolog-make-keywords-regexp (keywords &optional protect)
1720 "Create regexp from the list of strings KEYWORDS.
1721 If PROTECT is non-nil, surround the result regexp by word breaks."
1722 (let ((regexp
1723 (if (fboundp 'regexp-opt)
1724 ;; Emacs 20
1725 ;; Avoid compile warnings under earlier versions by using eval
1726 (eval '(regexp-opt keywords))
1727 ;; Older Emacsen
1728 (concat (mapconcat 'regexp-quote keywords "\\|")))
1730 (if protect
1731 (concat "\\<\\(" regexp "\\)\\>")
1732 regexp)))
1734 (defun prolog-font-lock-object-matcher (bound)
1735 "Find SICStus objects method name for font lock.
1736 Argument BOUND is a buffer position limiting searching."
1737 (let (point
1738 (case-fold-search nil))
1739 (while (and (not point)
1740 (re-search-forward "\\(::[ \t\n]*{\\|&\\)[ \t]*"
1741 bound t))
1742 (while (or (re-search-forward "\\=\n[ \t]*" bound t)
1743 (re-search-forward "\\=%.*" bound t)
1744 (and (re-search-forward "\\=/\\*" bound t)
1745 (re-search-forward "\\*/[ \t]*" bound t))))
1746 (setq point (re-search-forward
1747 (format "\\=\\(%s\\)" prolog-atom-regexp)
1748 bound t)))
1749 point))
1751 (defsubst prolog-face-name-p (facename)
1752 ;; Return t if FACENAME is the name of a face. This method is
1753 ;; necessary since facep in XEmacs only returns t for the actual
1754 ;; face objects (while it's only their names that are used just
1755 ;; about anywhere else) without providing a predicate that tests
1756 ;; face names. This function (including the above commentary) is
1757 ;; borrowed from cc-mode.
1758 (memq facename (face-list)))
1760 ;; Set everything up
1761 (defun prolog-font-lock-keywords ()
1762 "Set up font lock keywords for the current Prolog system."
1763 ;(when window-system
1764 (require 'font-lock)
1766 ;; Define Prolog faces
1767 (defface prolog-redo-face
1768 '((((class grayscale)) (:italic t))
1769 (((class color)) (:foreground "darkorchid"))
1770 (t (:italic t)))
1771 "Prolog mode face for highlighting redo trace lines."
1772 :group 'prolog-faces)
1773 (defface prolog-exit-face
1774 '((((class grayscale)) (:underline t))
1775 (((class color) (background dark)) (:foreground "green"))
1776 (((class color) (background light)) (:foreground "ForestGreen"))
1777 (t (:underline t)))
1778 "Prolog mode face for highlighting exit trace lines."
1779 :group 'prolog-faces)
1780 (defface prolog-exception-face
1781 '((((class grayscale)) (:bold t :italic t :underline t))
1782 (((class color)) (:bold t :foreground "black" :background "Khaki"))
1783 (t (:bold t :italic t :underline t)))
1784 "Prolog mode face for highlighting exception trace lines."
1785 :group 'prolog-faces)
1786 (defface prolog-warning-face
1787 '((((class grayscale)) (:underline t))
1788 (((class color) (background dark)) (:foreground "blue"))
1789 (((class color) (background light)) (:foreground "MidnightBlue"))
1790 (t (:underline t)))
1791 "Face name to use for compiler warnings."
1792 :group 'prolog-faces)
1793 (defface prolog-builtin-face
1794 '((((class color) (background light)) (:foreground "Purple"))
1795 (((class color) (background dark)) (:foreground "Cyan"))
1796 (((class grayscale) (background light)) (:foreground "LightGray" :bold t))
1797 (((class grayscale) (background dark)) (:foreground "DimGray" :bold t))
1798 (t (:bold t)))
1799 "Face name to use for compiler warnings."
1800 :group 'prolog-faces)
1801 (defvar prolog-warning-face
1802 (if (prolog-face-name-p 'font-lock-warning-face)
1803 'font-lock-warning-face
1804 'prolog-warning-face)
1805 "Face name to use for built in predicates.")
1806 (defvar prolog-builtin-face
1807 (if (prolog-face-name-p 'font-lock-builtin-face)
1808 'font-lock-builtin-face
1809 'prolog-builtin-face)
1810 "Face name to use for built in predicates.")
1811 (defvar prolog-redo-face 'prolog-redo-face
1812 "Face name to use for redo trace lines.")
1813 (defvar prolog-exit-face 'prolog-exit-face
1814 "Face name to use for exit trace lines.")
1815 (defvar prolog-exception-face 'prolog-exception-face
1816 "Face name to use for exception trace lines.")
1818 ;; Font Lock Patterns
1819 (let (
1820 ;; "Native" Prolog patterns
1821 (head-predicates
1822 (list (format "^\\(%s\\)\\((\\|[ \t]*:-\\)" prolog-atom-regexp)
1823 1 font-lock-function-name-face))
1824 ;(list (format "^%s" prolog-atom-regexp)
1825 ; 0 font-lock-function-name-face))
1826 (head-predicates-1
1827 (list (format "\\.[ \t]*\\(%s\\)" prolog-atom-regexp)
1828 1 font-lock-function-name-face) )
1829 (variables
1830 '("\\<\\([_A-Z][a-zA-Z0-9_]*\\)"
1831 1 font-lock-variable-name-face))
1832 (important-elements
1833 (list (if (eq prolog-system 'mercury)
1834 "[][}{;|]\\|\\\\[+=]\\|<?=>?"
1835 "[][}{!;|]\\|\\*->")
1836 0 'font-lock-keyword-face))
1837 (important-elements-1
1838 '("[^-*]\\(->\\)" 1 font-lock-keyword-face))
1839 (predspecs ; module:predicate/cardinality
1840 (list (format "\\<\\(%s:\\|\\)%s/[0-9]+"
1841 prolog-atom-regexp prolog-atom-regexp)
1842 0 font-lock-function-name-face 'prepend))
1843 (keywords ; directives (queries)
1844 (list
1845 (if (eq prolog-system 'mercury)
1846 (concat
1847 "\\<\\("
1848 (prolog-make-keywords-regexp prolog-keywords-i)
1849 "\\|"
1850 (prolog-make-keywords-regexp
1851 prolog-determinism-specificators-i)
1852 "\\)\\>")
1853 (concat
1854 "^[?:]- *\\("
1855 (prolog-make-keywords-regexp prolog-keywords-i)
1856 "\\)\\>"))
1857 1 prolog-builtin-face))
1858 (quoted_atom (list prolog-quoted-atom-regexp
1859 2 'font-lock-string-face 'append))
1860 (string (list prolog-string-regexp
1861 1 'font-lock-string-face 'append))
1862 ;; SICStus specific patterns
1863 (sicstus-object-methods
1864 (if (eq prolog-system 'sicstus)
1865 '(prolog-font-lock-object-matcher
1866 1 font-lock-function-name-face)))
1867 ;; Mercury specific patterns
1868 (types
1869 (if (eq prolog-system 'mercury)
1870 (list
1871 (prolog-make-keywords-regexp prolog-types-i t)
1872 0 'font-lock-type-face)))
1873 (modes
1874 (if (eq prolog-system 'mercury)
1875 (list
1876 (prolog-make-keywords-regexp prolog-mode-specificators-i t)
1877 0 'font-lock-reference-face)))
1878 (directives
1879 (if (eq prolog-system 'mercury)
1880 (list
1881 (prolog-make-keywords-regexp prolog-directives-i t)
1882 0 'prolog-warning-face)))
1883 ;; Inferior mode specific patterns
1884 (prompt
1885 ;; FIXME: Should be handled by comint already.
1886 (list (prolog-prompt-regexp) 0 'font-lock-keyword-face))
1887 (trace-exit
1888 ;; FIXME: Add to compilation-error-regexp-alist instead.
1889 (cond
1890 ((eq prolog-system 'sicstus)
1891 '("[ \t]*[0-9]+[ \t]+[0-9]+[ \t]*\\(Exit\\):"
1892 1 prolog-exit-face))
1893 ((eq prolog-system 'swi)
1894 '("[ \t]*\\(Exit\\):[ \t]*([ \t0-9]*)" 1 prolog-exit-face))
1895 (t nil)))
1896 (trace-fail
1897 ;; FIXME: Add to compilation-error-regexp-alist instead.
1898 (cond
1899 ((eq prolog-system 'sicstus)
1900 '("[ \t]*[0-9]+[ \t]+[0-9]+[ \t]*\\(Fail\\):"
1901 1 prolog-warning-face))
1902 ((eq prolog-system 'swi)
1903 '("[ \t]*\\(Fail\\):[ \t]*([ \t0-9]*)" 1 prolog-warning-face))
1904 (t nil)))
1905 (trace-redo
1906 ;; FIXME: Add to compilation-error-regexp-alist instead.
1907 (cond
1908 ((eq prolog-system 'sicstus)
1909 '("[ \t]*[0-9]+[ \t]+[0-9]+[ \t]*\\(Redo\\):"
1910 1 prolog-redo-face))
1911 ((eq prolog-system 'swi)
1912 '("[ \t]*\\(Redo\\):[ \t]*([ \t0-9]*)" 1 prolog-redo-face))
1913 (t nil)))
1914 (trace-call
1915 ;; FIXME: Add to compilation-error-regexp-alist instead.
1916 (cond
1917 ((eq prolog-system 'sicstus)
1918 '("[ \t]*[0-9]+[ \t]+[0-9]+[ \t]*\\(Call\\):"
1919 1 font-lock-function-name-face))
1920 ((eq prolog-system 'swi)
1921 '("[ \t]*\\(Call\\):[ \t]*([ \t0-9]*)"
1922 1 font-lock-function-name-face))
1923 (t nil)))
1924 (trace-exception
1925 ;; FIXME: Add to compilation-error-regexp-alist instead.
1926 (cond
1927 ((eq prolog-system 'sicstus)
1928 '("[ \t]*[0-9]+[ \t]+[0-9]+[ \t]*\\(Exception\\):"
1929 1 prolog-exception-face))
1930 ((eq prolog-system 'swi)
1931 '("[ \t]*\\(Exception\\):[ \t]*([ \t0-9]*)"
1932 1 prolog-exception-face))
1933 (t nil)))
1934 (error-message-identifier
1935 ;; FIXME: Add to compilation-error-regexp-alist instead.
1936 (cond
1937 ((eq prolog-system 'sicstus)
1938 '("{\\([A-Z]* ?ERROR:\\)" 1 prolog-exception-face prepend))
1939 ((eq prolog-system 'swi)
1940 '("^[[]\\(WARNING:\\)" 1 prolog-builtin-face prepend))
1941 (t nil)))
1942 (error-whole-messages
1943 ;; FIXME: Add to compilation-error-regexp-alist instead.
1944 (cond
1945 ((eq prolog-system 'sicstus)
1946 '("{\\([A-Z]* ?ERROR:.*\\)}[ \t]*$"
1947 1 font-lock-comment-face append))
1948 ((eq prolog-system 'swi)
1949 '("^[[]WARNING:[^]]*[]]$" 0 font-lock-comment-face append))
1950 (t nil)))
1951 (error-warning-messages
1952 ;; FIXME: Add to compilation-error-regexp-alist instead.
1953 ;; Mostly errors that SICStus asks the user about how to solve,
1954 ;; such as "NAME CLASH:" for example.
1955 (cond
1956 ((eq prolog-system 'sicstus)
1957 '("^[A-Z ]*[A-Z]+:" 0 prolog-warning-face))
1958 (t nil)))
1959 (warning-messages
1960 ;; FIXME: Add to compilation-error-regexp-alist instead.
1961 (cond
1962 ((eq prolog-system 'sicstus)
1963 '("\\({ ?\\(Warning\\|WARNING\\) ?:.*}\\)[ \t]*$"
1964 2 prolog-warning-face prepend))
1965 (t nil))))
1967 ;; Make font lock list
1968 (delq
1970 (cond
1971 ((eq major-mode 'prolog-mode)
1972 (list
1973 head-predicates
1974 head-predicates-1
1975 quoted_atom
1976 string
1977 variables
1978 important-elements
1979 important-elements-1
1980 predspecs
1981 keywords
1982 sicstus-object-methods
1983 types
1984 modes
1985 directives))
1986 ((eq major-mode 'prolog-inferior-mode)
1987 (list
1988 prompt
1989 error-message-identifier
1990 error-whole-messages
1991 error-warning-messages
1992 warning-messages
1993 predspecs
1994 trace-exit
1995 trace-fail
1996 trace-redo
1997 trace-call
1998 trace-exception))
1999 ((eq major-mode 'compilation-mode)
2000 (list
2001 error-message-identifier
2002 error-whole-messages
2003 error-warning-messages
2004 warning-messages
2005 predspecs))))
2009 ;;-------------------------------------------------------------------
2010 ;; Indentation stuff
2011 ;;-------------------------------------------------------------------
2013 ;; NB: This function *MUST* have this optional argument since XEmacs
2014 ;; assumes it. This does not mean we have to use it...
2015 (defun prolog-indent-line (&optional _whole-exp)
2016 "Indent current line as Prolog code.
2017 With argument, indent any additional lines of the same clause
2018 rigidly along with this one (not yet)."
2019 (interactive "p")
2020 (let ((indent (prolog-indent-level))
2021 (pos (- (point-max) (point))))
2022 (beginning-of-line)
2023 (skip-chars-forward " \t")
2024 (indent-line-to indent)
2025 (if (> (- (point-max) pos) (point))
2026 (goto-char (- (point-max) pos)))
2028 ;; Align comments
2029 (if (and prolog-align-comments-flag
2030 (save-excursion
2031 (line-beginning-position)
2032 ;; (let ((start (comment-search-forward (line-end-position) t)))
2033 ;; (and start ;There's a comment to indent.
2034 ;; ;; If it's first on the line, we've indented it already
2035 ;; ;; and prolog-goto-comment-column would inf-loop.
2036 ;; (progn (goto-char start) (skip-chars-backward " \t")
2037 ;; (not (bolp)))))))
2038 (and (looking-at comment-start-skip)
2039 ;; The definition of comment-start-skip used in this
2040 ;; mode is unusual in that it only matches at BOL.
2041 (progn (skip-chars-forward " \t")
2042 (not (eq (point) (match-end 1)))))))
2043 (save-excursion
2044 (prolog-goto-comment-column t)))
2046 ;; Insert spaces if needed
2047 (if (or prolog-electric-tab-flag prolog-electric-if-then-else-flag)
2048 (prolog-insert-spaces-after-paren))
2051 (defun prolog-comment-indent ()
2052 "Compute prolog comment indentation."
2053 ;; FIXME: Only difference with default behavior is that %%% is not
2054 ;; flushed to column 0 but just left where the user put it.
2055 (cond ((looking-at "%%%") (prolog-indentation-level-of-line))
2056 ((looking-at "%%") (prolog-indent-level))
2058 (save-excursion
2059 (skip-chars-backward " \t")
2060 ;; Insert one space at least, except at left margin.
2061 (max (+ (current-column) (if (bolp) 0 1))
2062 comment-column)))
2065 (defun prolog-indent-level ()
2066 "Compute prolog indentation level."
2067 (save-excursion
2068 (beginning-of-line)
2069 (let ((totbal (prolog-region-paren-balance
2070 (prolog-clause-start t) (point)))
2071 (oldpoint (point)))
2072 (skip-chars-forward " \t")
2073 (cond
2074 ((looking-at "%%%") (prolog-indentation-level-of-line))
2075 ;Large comment starts
2076 ((looking-at "%[^%]") comment-column) ;Small comment starts
2077 ((bobp) 0) ;Beginning of buffer
2079 ;; If we found '}' then we must check if it's the
2080 ;; end of an object declaration or something else.
2081 ((and (looking-at "}")
2082 (save-excursion
2083 (forward-char 1)
2084 ;; Goto to matching {
2085 (if prolog-use-prolog-tokenizer-flag
2086 (prolog-backward-list)
2087 (backward-list))
2088 (skip-chars-backward " \t")
2089 (backward-char 2)
2090 (looking-at "::")))
2091 ;; It was an object
2092 (if prolog-object-end-to-0-flag
2094 prolog-indent-width))
2096 ;;End of /* */ comment
2097 ((looking-at "\\*/")
2098 (save-excursion
2099 (prolog-find-start-of-mline-comment)
2100 (skip-chars-backward " \t")
2101 (- (current-column) 2)))
2103 ;; Here we check if the current line is within a /* */ pair
2104 ((and (looking-at "[^%/]")
2105 (eq (prolog-in-string-or-comment) 'cmt))
2106 (if prolog-indent-mline-comments-flag
2107 (prolog-find-start-of-mline-comment)
2108 ;; Same as before
2109 (prolog-indentation-level-of-line)))
2112 (let ((empty t) ind linebal)
2113 ;; See previous indentation
2114 (while empty
2115 (forward-line -1)
2116 (beginning-of-line)
2117 (if (bobp)
2118 (setq empty nil)
2119 (skip-chars-forward " \t")
2120 (if (not (or (not (member (prolog-in-string-or-comment)
2121 '(nil txt)))
2122 (looking-at "%")
2123 (looking-at "\n")))
2124 (setq empty nil))))
2126 ;; Store this line's indentation
2127 (setq ind (if (bobp)
2128 0 ;Beginning of buffer.
2129 (current-column))) ;Beginning of clause.
2131 ;; Compute the balance of the line
2132 (setq linebal (prolog-paren-balance))
2133 ;;(message "bal of previous line %d totbal %d" linebal totbal)
2134 (if (< linebal 0)
2135 (progn
2136 ;; Add 'indent-level' mode to find-unmatched-paren instead?
2137 (end-of-line)
2138 (setq ind (prolog-find-indent-of-matching-paren))))
2140 ;;(message "ind %d" ind)
2141 (beginning-of-line)
2143 ;; Check if the line ends with ":-", ".", ":: {", "}" (might be
2144 ;; unnecessary), "&" or ")" (The last four concerns SICStus objects)
2145 (cond
2146 ;; If the last char of the line is a '&' then set the indent level
2147 ;; to prolog-indent-width (used in SICStus objects)
2148 ((and (eq prolog-system 'sicstus)
2149 (looking-at ".+&[ \t]*\\(%.*\\|\\)$"))
2150 (setq ind prolog-indent-width))
2152 ;; Increase indentation if the previous line was the head of a rule
2153 ;; and does not contain a '.'
2154 ((and (looking-at (format ".*%s[^\\.]*[ \t]*\\(%%.*\\|\\)$"
2155 prolog-head-delimiter))
2156 ;; We must check that the match is at a paren balance of 0.
2157 (save-excursion
2158 (let ((p (point)))
2159 (re-search-forward prolog-head-delimiter)
2160 (>= 0 (prolog-region-paren-balance p (point))))))
2161 (let ((headindent
2162 (if (< (prolog-paren-balance) 0)
2163 (save-excursion
2164 (end-of-line)
2165 (prolog-find-indent-of-matching-paren))
2166 (prolog-indentation-level-of-line))))
2167 (setq ind (+ headindent prolog-indent-width))))
2169 ;; The previous line was the head of an object
2170 ((looking-at ".+ *::.*{[ \t]*$")
2171 (setq ind prolog-indent-width))
2173 ;; If a '.' is found at the end of the previous line, then
2174 ;; decrease the indentation. (The \\(%.*\\|\\) part of the
2175 ;; regexp is for comments at the end of the line)
2176 ((and (looking-at "^.+\\.[ \t]*\\(%.*\\|\\)$")
2177 ;; Make sure that the '.' found is not in a comment or string
2178 (save-excursion
2179 (end-of-line)
2180 (re-search-backward "\\.[ \t]*\\(%.*\\|\\)$" (point-min))
2181 ;; Guard against the real '.' being followed by a
2182 ;; commented '.'.
2183 (if (eq (prolog-in-string-or-comment) 'cmt)
2184 ;; commented out '.'
2185 (let ((here (line-beginning-position)))
2186 (end-of-line)
2187 (re-search-backward "\\.[ \t]*%.*$" here t))
2188 (not (prolog-in-string-or-comment))
2191 (setq ind 0))
2193 ;; If a '.' is found at the end of the previous line, then
2194 ;; decrease the indentation. (The /\\*.*\\*/ part of the
2195 ;; regexp is for C-like comments at the end of the
2196 ;; line--can we merge with the case above?).
2197 ((and (looking-at "^.+\\.[ \t]*\\(/\\*.*\\|\\)$")
2198 ;; Make sure that the '.' found is not in a comment or string
2199 (save-excursion
2200 (end-of-line)
2201 (re-search-backward "\\.[ \t]*\\(/\\*.*\\|\\)$" (point-min))
2202 ;; Guard against the real '.' being followed by a
2203 ;; commented '.'.
2204 (if (eq (prolog-in-string-or-comment) 'cmt)
2205 ;; commented out '.'
2206 (let ((here (line-beginning-position)))
2207 (end-of-line)
2208 (re-search-backward "\\.[ \t]*/\\*.*$" here t))
2209 (not (prolog-in-string-or-comment))
2212 (setq ind 0))
2216 ;; If the last non comment char is a ',' or left paren or a left-
2217 ;; indent-regexp then indent to open parenthesis level
2218 (if (and
2219 (> totbal 0)
2220 ;; SICStus objects have special syntax rules if point is
2221 ;; not inside additional parens (objects are defined
2222 ;; within {...})
2223 (not (and (eq prolog-system 'sicstus)
2224 (= totbal 1)
2225 (prolog-in-object))))
2226 (if (looking-at
2227 (format "\\(%s\\|%s\\|0'.\\|[0-9]+'[0-9a-zA-Z]+\\|[^\n\'\"%%]\\)*\\(,\\|%s\\|%s\\)\[ \t]*\\(%%.*\\|\\)$"
2228 prolog-quoted-atom-regexp prolog-string-regexp
2229 prolog-left-paren prolog-left-indent-regexp))
2230 (progn
2231 (goto-char oldpoint)
2232 (setq ind (prolog-find-unmatched-paren
2233 (if prolog-paren-indent-p
2234 'termdependent
2235 'skipwhite)))
2236 ;;(setq ind (prolog-find-unmatched-paren 'termdependent))
2238 (goto-char oldpoint)
2239 (setq ind (prolog-find-unmatched-paren nil))
2243 ;; Return the indentation level
2245 ))))))
2247 (defun prolog-find-indent-of-matching-paren ()
2248 "Find the indentation level based on the matching parenthesis.
2249 Indentation level is set to the one the point is after when the function is
2250 called."
2251 (save-excursion
2252 ;; Go to the matching paren
2253 (if prolog-use-prolog-tokenizer-flag
2254 (prolog-backward-list)
2255 (backward-list))
2257 ;; If this was the first paren on the line then return this line's
2258 ;; indentation level
2259 (if (prolog-paren-is-the-first-on-line-p)
2260 (prolog-indentation-level-of-line)
2261 ;; It was not the first one
2262 (progn
2263 ;; Find the next paren
2264 (prolog-goto-next-paren 0)
2266 ;; If this paren is a left one then use its column as indent level,
2267 ;; if not then recurse this function
2268 (if (looking-at prolog-left-paren)
2269 (+ (current-column) 1)
2270 (progn
2271 (forward-char 1)
2272 (prolog-find-indent-of-matching-paren)))
2276 (defun prolog-indentation-level-of-line ()
2277 "Return the indentation level of the current line."
2278 (save-excursion
2279 (beginning-of-line)
2280 (skip-chars-forward " \t")
2281 (current-column)))
2283 (defun prolog-paren-is-the-first-on-line-p ()
2284 "Return t if the parenthesis under the point is the first one on the line.
2285 Return nil otherwise.
2286 Note: does not check if the point is actually at a parenthesis!"
2287 (save-excursion
2288 (let ((begofline (line-beginning-position)))
2289 (if (= begofline (point))
2291 (if (prolog-goto-next-paren begofline)
2293 t)))))
2295 (defun prolog-find-unmatched-paren (&optional mode)
2296 "Return the column of the last unmatched left parenthesis.
2297 If MODE is `skipwhite' then any white space after the parenthesis is added to
2298 the answer.
2299 If MODE is `plusone' then the parenthesis' column +1 is returned.
2300 If MODE is `termdependent' then if the unmatched parenthesis is part of
2301 a compound term the function will work as `skipwhite', otherwise
2302 it will return the column paren plus the value of `prolog-paren-indent'.
2303 If MODE is nil or not set then the parenthesis' exact column is returned."
2304 (save-excursion
2305 ;; If the next paren we find is a left one we're finished, if it's
2306 ;; a right one then we go back one step and recurse
2307 (prolog-goto-next-paren 0)
2309 (let ((roundparen (looking-at "(")))
2310 (if (looking-at prolog-left-paren)
2311 (let ((not-part-of-term
2312 (save-excursion
2313 (backward-char 1)
2314 (looking-at "[ \t]"))))
2315 (if (eq mode nil)
2316 (current-column)
2317 (if (and roundparen
2318 (eq mode 'termdependent)
2319 not-part-of-term)
2320 (+ (current-column)
2321 (if prolog-electric-tab-flag
2322 ;; Electric TAB
2323 prolog-paren-indent
2324 ;; Not electric TAB
2325 (if (looking-at ".[ \t]*$")
2327 prolog-paren-indent))
2330 (forward-char 1)
2331 (if (or (eq mode 'skipwhite) (eq mode 'termdependent) )
2332 (skip-chars-forward " \t"))
2333 (current-column))))
2334 ;; Not looking at left paren
2335 (progn
2336 (forward-char 1)
2337 ;; Go to the matching paren. When we get there we have a total
2338 ;; balance of 0.
2339 (if prolog-use-prolog-tokenizer-flag
2340 (prolog-backward-list)
2341 (backward-list))
2342 (prolog-find-unmatched-paren mode)))
2346 (defun prolog-paren-balance ()
2347 "Return the parenthesis balance of the current line.
2348 A return value of n means n more left parentheses than right ones."
2349 (save-excursion
2350 (end-of-line)
2351 (prolog-region-paren-balance (line-beginning-position) (point))))
2353 (defun prolog-region-paren-balance (beg end)
2354 "Return the summed parenthesis balance in the region.
2355 The region is limited by BEG and END positions."
2356 (save-excursion
2357 (let ((state (if prolog-use-prolog-tokenizer-flag
2358 (prolog-tokenize beg end)
2359 (parse-partial-sexp beg end))))
2360 (nth 0 state))))
2362 (defun prolog-goto-next-paren (limit-pos)
2363 "Move the point to the next parenthesis earlier in the buffer.
2364 Return t if a match was found before LIMIT-POS. Return nil otherwise."
2365 (let ((retval (re-search-backward
2366 (concat prolog-left-paren "\\|" prolog-right-paren)
2367 limit-pos t)))
2369 ;; If a match was found but it was in a string or comment, then recurse
2370 (if (and retval (prolog-in-string-or-comment))
2371 (prolog-goto-next-paren limit-pos)
2372 retval)
2375 (defun prolog-in-string-or-comment ()
2376 "Check whether string, atom, or comment is under current point.
2377 Return:
2378 `txt' if the point is in a string, atom, or character code expression
2379 `cmt' if the point is in a comment
2380 nil otherwise."
2381 (save-excursion
2382 (let* ((start
2383 (if (eq prolog-parse-mode 'beg-of-line)
2384 ;; 'beg-of-line
2385 (save-excursion
2386 (let (safepoint)
2387 (beginning-of-line)
2388 (setq safepoint (point))
2389 (while (and (> (point) (point-min))
2390 (progn
2391 (forward-line -1)
2392 (end-of-line)
2393 (if (not (bobp))
2394 (backward-char 1))
2395 (looking-at "\\\\"))
2397 (beginning-of-line)
2398 (setq safepoint (point)))
2399 safepoint))
2400 ;; 'beg-of-clause
2401 (prolog-clause-start)))
2402 (end (point))
2403 (state (if prolog-use-prolog-tokenizer-flag
2404 (prolog-tokenize start end)
2405 (if (fboundp 'syntax-ppss)
2406 (syntax-ppss)
2407 (parse-partial-sexp start end)))))
2408 (cond
2409 ((nth 3 state) 'txt) ; String
2410 ((nth 4 state) 'cmt) ; Comment
2412 (cond
2413 ((looking-at "%") 'cmt) ; Start of a comment
2414 ((looking-at "/\\*") 'cmt) ; Start of a comment
2415 ((looking-at "\'") 'txt) ; Start of an atom
2416 ((looking-at "\"") 'txt) ; Start of a string
2417 (t nil)
2418 ))))
2421 (defun prolog-find-start-of-mline-comment ()
2422 "Return the start column of a /* */ comment.
2423 This assumes that the point is inside a comment."
2424 (re-search-backward "/\\*" (point-min) t)
2425 (forward-char 2)
2426 (skip-chars-forward " \t")
2427 (current-column))
2429 (defun prolog-insert-spaces-after-paren ()
2430 "Insert spaces after the opening parenthesis, \"then\" (->) and \"else\" (;) branches.
2431 Spaces are inserted if all preceding objects on the line are
2432 whitespace characters, parentheses, or then/else branches."
2433 (save-excursion
2434 (let ((regexp (concat "(\\|" prolog-left-indent-regexp))
2435 level)
2436 (beginning-of-line)
2437 (skip-chars-forward " \t")
2438 (when (looking-at regexp)
2439 ;; Treat "( If -> " lines specially.
2440 ;;(setq incr (if (looking-at "(.*->")
2441 ;; 2
2442 ;; prolog-paren-indent))
2444 ;; work on all subsequent "->", "(", ";"
2445 (while (looking-at regexp)
2446 (goto-char (match-end 0))
2447 (setq level (+ (prolog-find-unmatched-paren) prolog-paren-indent))
2449 ;; Remove old white space
2450 (let ((start (point)))
2451 (skip-chars-forward " \t")
2452 (delete-region start (point)))
2453 (indent-to level)
2454 (skip-chars-forward " \t"))
2456 (when (save-excursion
2457 (backward-char 2)
2458 (looking-at "\\s ;\\|\\s (\\|->")) ; (looking-at "\\s \\((\\|;\\)"))
2459 (skip-chars-forward " \t"))
2462 ;;;; Comment filling
2464 (defun prolog-comment-limits ()
2465 "Return the current comment limits plus the comment type (block or line).
2466 The comment limits are the range of a block comment or the range that
2467 contains all adjacent line comments (i.e. all comments that starts in
2468 the same column with no empty lines or non-whitespace characters
2469 between them)."
2470 (let ((here (point))
2471 lit-limits-b lit-limits-e lit-type beg end
2473 (save-restriction
2474 ;; Widen to catch comment limits correctly.
2475 (widen)
2476 (setq end (line-end-position)
2477 beg (line-beginning-position))
2478 (save-excursion
2479 (beginning-of-line)
2480 (setq lit-type (if (search-forward-regexp "%" end t) 'line 'block))
2481 ; (setq lit-type 'line)
2482 ;(if (search-forward-regexp "^[ \t]*%" end t)
2483 ; (setq lit-type 'line)
2484 ; (if (not (search-forward-regexp "%" end t))
2485 ; (setq lit-type 'block)
2486 ; (if (not (= (forward-line 1) 0))
2487 ; (setq lit-type 'block)
2488 ; (setq done t
2489 ; ret (prolog-comment-limits)))
2490 ; ))
2491 (if (eq lit-type 'block)
2492 (progn
2493 (goto-char here)
2494 (when (looking-at "/\\*") (forward-char 2))
2495 (when (and (looking-at "\\*") (> (point) (point-min))
2496 (forward-char -1) (looking-at "/"))
2497 (forward-char 1))
2498 (when (save-excursion (search-backward "/*" nil t))
2499 (list (save-excursion (search-backward "/*") (point))
2500 (or (search-forward "*/" nil t) (point-max)) lit-type)))
2501 ;; line comment
2502 (setq lit-limits-b (- (point) 1)
2503 lit-limits-e end)
2504 (condition-case nil
2505 (if (progn (goto-char lit-limits-b)
2506 (looking-at "%"))
2507 (let ((col (current-column)) done)
2508 (setq beg (point)
2509 end lit-limits-e)
2510 ;; Always at the beginning of the comment
2511 ;; Go backward now
2512 (beginning-of-line)
2513 (while (and (zerop (setq done (forward-line -1)))
2514 (search-forward-regexp "^[ \t]*%"
2515 (line-end-position) t)
2516 (= (+ 1 col) (current-column)))
2517 (setq beg (- (point) 1)))
2518 (when (= done 0)
2519 (forward-line 1))
2520 ;; We may have a line with code above...
2521 (when (and (zerop (setq done (forward-line -1)))
2522 (search-forward "%" (line-end-position) t)
2523 (= (+ 1 col) (current-column)))
2524 (setq beg (- (point) 1)))
2525 (when (= done 0)
2526 (forward-line 1))
2527 ;; Go forward
2528 (goto-char lit-limits-b)
2529 (beginning-of-line)
2530 (while (and (zerop (forward-line 1))
2531 (search-forward-regexp "^[ \t]*%"
2532 (line-end-position) t)
2533 (= (+ 1 col) (current-column)))
2534 (setq end (line-end-position)))
2535 (list beg end lit-type))
2536 (list lit-limits-b lit-limits-e lit-type)
2538 (error (list lit-limits-b lit-limits-e lit-type))))
2539 ))))
2541 (defun prolog-guess-fill-prefix ()
2542 ;; fill 'txt entities?
2543 (when (save-excursion
2544 (end-of-line)
2545 (equal (prolog-in-string-or-comment) 'cmt))
2546 (let* ((bounds (prolog-comment-limits))
2547 (cbeg (car bounds))
2548 (type (nth 2 bounds))
2549 beg end)
2550 (save-excursion
2551 (end-of-line)
2552 (setq end (point))
2553 (beginning-of-line)
2554 (setq beg (point))
2555 (if (and (eq type 'line)
2556 (> cbeg beg)
2557 (save-excursion (not (search-forward-regexp "^[ \t]*%"
2558 cbeg t))))
2559 (progn
2560 (goto-char cbeg)
2561 (search-forward-regexp "%+[ \t]*" end t)
2562 (prolog-replace-in-string (buffer-substring beg (point))
2563 "[^ \t%]" " "))
2564 ;(goto-char beg)
2565 (if (search-forward-regexp "^[ \t]*\\(%+\\|\\*+\\|/\\*+\\)[ \t]*"
2566 end t)
2567 (prolog-replace-in-string (buffer-substring beg (point)) "/" " ")
2568 (beginning-of-line)
2569 (when (search-forward-regexp "^[ \t]+" end t)
2570 (buffer-substring beg (point)))))))))
2572 (defun prolog-fill-paragraph ()
2573 "Fill paragraph comment at or after point."
2574 (interactive)
2575 (let* ((bounds (prolog-comment-limits))
2576 (type (nth 2 bounds)))
2577 (if (eq type 'line)
2578 (let ((fill-prefix (prolog-guess-fill-prefix)))
2579 (fill-paragraph nil))
2580 (save-excursion
2581 (save-restriction
2582 ;; exclude surrounding lines that delimit a multiline comment
2583 ;; and don't contain alphabetic characters, like "/*******",
2584 ;; "- - - */" etc.
2585 (save-excursion
2586 (backward-paragraph)
2587 (unless (bobp) (forward-line))
2588 (if (string-match "^/\\*[^a-zA-Z]*$" (thing-at-point 'line))
2589 (narrow-to-region (point-at-eol) (point-max))))
2590 (save-excursion
2591 (forward-paragraph)
2592 (forward-line -1)
2593 (if (string-match "^[^a-zA-Z]*\\*/$" (thing-at-point 'line))
2594 (narrow-to-region (point-min) (point-at-bol))))
2595 (let ((fill-prefix (prolog-guess-fill-prefix)))
2596 (fill-paragraph nil))))
2599 (defun prolog-do-auto-fill ()
2600 "Carry out Auto Fill for Prolog mode.
2601 In effect it sets the `fill-prefix' when inside comments and then calls
2602 `do-auto-fill'."
2603 (let ((fill-prefix (prolog-guess-fill-prefix)))
2604 (do-auto-fill)
2607 (defalias 'prolog-replace-in-string
2608 (if (fboundp 'replace-in-string)
2609 #'replace-in-string
2610 (lambda (str regexp newtext &optional literal)
2611 (replace-regexp-in-string regexp newtext str nil literal))))
2613 ;;-------------------------------------------------------------------
2614 ;; The tokenizer
2615 ;;-------------------------------------------------------------------
2617 (defconst prolog-tokenize-searchkey
2618 (concat "[0-9]+'"
2619 "\\|"
2620 "['\"]"
2621 "\\|"
2622 prolog-left-paren
2623 "\\|"
2624 prolog-right-paren
2625 "\\|"
2627 "\\|"
2628 "/\\*"
2631 (defun prolog-tokenize (beg end &optional stopcond)
2632 "Tokenize a region of prolog code between BEG and END.
2633 STOPCOND decides the stop condition of the parsing. Valid values
2634 are 'zerodepth which stops the parsing at the first right parenthesis
2635 where the parenthesis depth is zero, 'skipover which skips over
2636 the current entity (e.g. a list, a string, etc.) and nil.
2638 The function returns a list with the following information:
2639 0. parenthesis depth
2640 3. 'atm if END is inside an atom
2641 'str if END is inside a string
2642 'chr if END is in a character code expression (0'x)
2643 nil otherwise
2644 4. non-nil if END is inside a comment
2645 5. end position (always equal to END if STOPCOND is nil)
2646 The rest of the elements are undefined."
2647 (save-excursion
2648 (let* ((end2 (1+ end))
2649 oldp
2650 (depth 0)
2651 (quoted nil)
2652 inside_cmt
2653 (endpos end2)
2654 skiptype ; The type of entity we'll skip over
2656 (goto-char beg)
2658 (if (and (eq stopcond 'skipover)
2659 (looking-at "[^[({'\"]"))
2660 (setq endpos (point)) ; Stay where we are
2661 (while (and
2662 (re-search-forward prolog-tokenize-searchkey end2 t)
2663 (< (point) end2))
2664 (progn
2665 (setq oldp (point))
2666 (goto-char (match-beginning 0))
2667 (cond
2668 ;; Atoms and strings
2669 ((looking-at "'")
2670 ;; Find end of atom
2671 (if (re-search-forward "[^\\]'" end2 'limit)
2672 ;; Found end of atom
2673 (progn
2674 (setq oldp end2)
2675 (if (and (eq stopcond 'skipover)
2676 (not skiptype))
2677 (setq endpos (point))
2678 (setq oldp (point)))) ; Continue tokenizing
2679 (setq quoted 'atm)))
2681 ((looking-at "\"")
2682 ;; Find end of string
2683 (if (re-search-forward "[^\\]\"" end2 'limit)
2684 ;; Found end of string
2685 (progn
2686 (setq oldp end2)
2687 (if (and (eq stopcond 'skipover)
2688 (not skiptype))
2689 (setq endpos (point))
2690 (setq oldp (point)))) ; Continue tokenizing
2691 (setq quoted 'str)))
2693 ;; Paren stuff
2694 ((looking-at prolog-left-paren)
2695 (setq depth (1+ depth))
2696 (setq skiptype 'paren))
2698 ((looking-at prolog-right-paren)
2699 (setq depth (1- depth))
2700 (if (and
2701 (or (eq stopcond 'zerodepth)
2702 (and (eq stopcond 'skipover)
2703 (eq skiptype 'paren)))
2704 (= depth 0))
2705 (progn
2706 (setq endpos (1+ (point)))
2707 (setq oldp end2))))
2709 ;; Comment stuff
2710 ((looking-at comment-start)
2711 (end-of-line)
2712 ;; (if (>= (point) end2)
2713 (if (>= (point) end)
2714 (progn
2715 (setq inside_cmt t)
2716 (setq oldp end2))
2717 (setq oldp (point))))
2719 ((looking-at "/\\*")
2720 (if (re-search-forward "\\*/" end2 'limit)
2721 (setq oldp (point))
2722 (setq inside_cmt t)
2723 (setq oldp end2)))
2725 ;; 0'char
2726 ((looking-at "0'")
2727 (setq oldp (1+ (match-end 0)))
2728 (if (> oldp end)
2729 (setq quoted 'chr)))
2731 ;; base'number
2732 ((looking-at "[0-9]+'")
2733 (goto-char (match-end 0))
2734 (skip-chars-forward "0-9a-zA-Z")
2735 (setq oldp (point)))
2739 (goto-char oldp)
2740 )) ; End of while
2743 ;; Deal with multi-line comments
2744 (and (prolog-inside-mline-comment end)
2745 (setq inside_cmt t))
2747 ;; Create return list
2748 (list depth nil nil quoted inside_cmt endpos)
2751 (defun prolog-inside-mline-comment (here)
2752 (save-excursion
2753 (goto-char here)
2754 (let* ((next-close (save-excursion (search-forward "*/" nil t)))
2755 (next-open (save-excursion (search-forward "/*" nil t)))
2756 (prev-open (save-excursion (search-backward "/*" nil t)))
2757 (prev-close (save-excursion (search-backward "*/" nil t)))
2758 (unmatched-next-close (and next-close
2759 (or (not next-open)
2760 (> next-open next-close))))
2761 (unmatched-prev-open (and prev-open
2762 (or (not prev-close)
2763 (> prev-open prev-close))))
2765 (or unmatched-next-close unmatched-prev-open)
2769 ;;-------------------------------------------------------------------
2770 ;; Online help
2771 ;;-------------------------------------------------------------------
2773 (defvar prolog-help-function
2774 '((mercury nil)
2775 (eclipse prolog-help-online)
2776 ;; (sicstus prolog-help-info)
2777 (sicstus prolog-find-documentation)
2778 (swi prolog-help-online)
2779 (t prolog-help-online))
2780 "Alist for the name of the function for finding help on a predicate.")
2782 (defun prolog-help-on-predicate ()
2783 "Invoke online help on the atom under cursor."
2784 (interactive)
2786 (cond
2787 ;; Redirect help for SICStus to `prolog-find-documentation'.
2788 ((eq prolog-help-function-i 'prolog-find-documentation)
2789 (prolog-find-documentation))
2791 ;; Otherwise, ask for the predicate name and then call the function
2792 ;; in prolog-help-function-i
2794 (let* ((word (prolog-atom-under-point))
2795 (predicate (read-string
2796 (format "Help on predicate%s: "
2797 (if word
2798 (concat " (default " word ")")
2799 ""))
2800 nil nil word))
2801 ;;point
2803 (if prolog-help-function-i
2804 (funcall prolog-help-function-i predicate)
2805 (error "Sorry, no help method defined for this Prolog system."))))
2808 (defun prolog-help-info (predicate)
2809 (let ((buffer (current-buffer))
2810 oldp
2811 (str (concat "^\\* " (regexp-quote predicate) " */")))
2812 (require 'info)
2813 (pop-to-buffer nil)
2814 (Info-goto-node prolog-info-predicate-index)
2815 (if (not (re-search-forward str nil t))
2816 (error (format "Help on predicate `%s' not found." predicate)))
2818 (setq oldp (point))
2819 (if (re-search-forward str nil t)
2820 ;; Multiple matches, ask user
2821 (let ((max 2)
2823 ;; Count matches
2824 (while (re-search-forward str nil t)
2825 (setq max (1+ max)))
2827 (goto-char oldp)
2828 (re-search-backward "[^ /]" nil t)
2829 (recenter 0)
2830 (setq n (read-string ;; was read-input, which is obsolete
2831 (format "Several matches, choose (1-%d): " max) "1"))
2832 (forward-line (- (string-to-number n) 1)))
2833 ;; Single match
2834 (re-search-backward "[^ /]" nil t))
2836 ;; (Info-follow-nearest-node (point))
2837 (prolog-Info-follow-nearest-node)
2838 (re-search-forward (concat "^`" (regexp-quote predicate)) nil t)
2839 (beginning-of-line)
2840 (recenter 0)
2841 (pop-to-buffer buffer)))
2843 (defun prolog-Info-follow-nearest-node ()
2844 (if (featurep 'xemacs)
2845 (Info-follow-nearest-node (point))
2846 (Info-follow-nearest-node)))
2848 (defun prolog-help-online (predicate)
2849 (prolog-ensure-process)
2850 (process-send-string "prolog" (concat "help(" predicate ").\n"))
2851 (display-buffer "*prolog*"))
2853 (defun prolog-help-apropos (string)
2854 "Find Prolog apropos on given STRING.
2855 This function is only available when `prolog-system' is set to `swi'."
2856 (interactive "sApropos: ")
2857 (cond
2858 ((eq prolog-system 'swi)
2859 (prolog-ensure-process)
2860 (process-send-string "prolog" (concat "apropos(" string ").\n"))
2861 (display-buffer "*prolog*"))
2863 (error "Sorry, no Prolog apropos available for this Prolog system."))))
2865 (defun prolog-atom-under-point ()
2866 "Return the atom under or left to the point."
2867 (save-excursion
2868 (let ((nonatom_chars "[](){},\. \t\n")
2869 start)
2870 (skip-chars-forward (concat "^" nonatom_chars))
2871 (skip-chars-backward nonatom_chars)
2872 (skip-chars-backward (concat "^" nonatom_chars))
2873 (setq start (point))
2874 (skip-chars-forward (concat "^" nonatom_chars))
2875 (buffer-substring-no-properties start (point))
2879 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2880 ;; Help function with completion
2881 ;; Stolen from Per Mildner's SICStus debugger mode and modified
2883 (defun prolog-find-documentation ()
2884 "Go to the Info node for a predicate in the SICStus Info manual."
2885 (interactive)
2886 (let ((pred (prolog-read-predicate)))
2887 (prolog-goto-predicate-info pred)))
2889 (defvar prolog-info-alist nil
2890 "Alist with all builtin predicates.
2891 Only for internal use by `prolog-find-documentation'")
2893 ;; Very similar to prolog-help-info except that that function cannot
2894 ;; cope with arity and that it asks the user if there are several
2895 ;; functors with different arity. This function also uses
2896 ;; prolog-info-alist for finding the info node, rather than parsing
2897 ;; the predicate index.
2898 (defun prolog-goto-predicate-info (predicate)
2899 "Go to the info page for PREDICATE, which is a PredSpec."
2900 (interactive)
2901 (require 'info)
2902 (string-match "\\(.*\\)/\\([0-9]+\\).*$" predicate)
2903 (let ((buffer (current-buffer))
2904 (name (match-string 1 predicate))
2905 (arity (string-to-number (match-string 2 predicate)))
2906 ;oldp
2907 ;(str (regexp-quote predicate))
2909 (pop-to-buffer nil)
2911 (Info-goto-node
2912 prolog-info-predicate-index) ;; We must be in the SICStus pages
2913 (Info-goto-node (car (cdr (assoc predicate prolog-info-alist))))
2915 (prolog-find-term (regexp-quote name) arity "^`")
2917 (recenter 0)
2918 (pop-to-buffer buffer))
2921 (defun prolog-read-predicate ()
2922 "Read a PredSpec from the user.
2923 Returned value is a string \"FUNCTOR/ARITY\".
2924 Interaction supports completion."
2925 (let ((default (prolog-atom-under-point)))
2926 ;; If the predicate index is not yet built, do it now
2927 (if (not prolog-info-alist)
2928 (prolog-build-info-alist))
2929 ;; Test if the default string could be the base for completion.
2930 ;; Discard it if not.
2931 (if (eq (try-completion default prolog-info-alist) nil)
2932 (setq default nil))
2933 ;; Read the PredSpec from the user
2934 (completing-read
2935 (if (zerop (length default))
2936 "Help on predicate: "
2937 (concat "Help on predicate (default " default "): "))
2938 prolog-info-alist nil t nil nil default)))
2940 (defun prolog-build-info-alist (&optional verbose)
2941 "Build an alist of all builtins and library predicates.
2942 Each element is of the form (\"NAME/ARITY\" . (INFO-NODE1 INFO-NODE2 ...)).
2943 Typically there is just one Info node associated with each name
2944 If an optional argument VERBOSE is non-nil, print messages at the beginning
2945 and end of list building."
2946 (if verbose
2947 (message "Building info alist..."))
2948 (setq prolog-info-alist
2949 (let ((l ())
2950 (last-entry (cons "" ())))
2951 (save-excursion
2952 (save-window-excursion
2953 ;; select any window but the minibuffer (as we cannot switch
2954 ;; buffers in minibuffer window.
2955 ;; I am not sure this is the right/best way
2956 (if (active-minibuffer-window) ; nil if none active
2957 (select-window (next-window)))
2958 ;; Do this after going away from minibuffer window
2959 (save-window-excursion
2960 (info))
2961 (Info-goto-node prolog-info-predicate-index)
2962 (goto-char (point-min))
2963 (while (re-search-forward
2964 "^\\* \\(.+\\)/\\([0-9]+\\)\\([^\n:*]*\\):" nil t)
2965 (let* ((name (match-string 1))
2966 (arity (string-to-number (match-string 2)))
2967 (comment (match-string 3))
2968 (fa (format "%s/%d%s" name arity comment))
2969 info-node)
2970 (beginning-of-line)
2971 ;; Extract the info node name
2972 (setq info-node (progn
2973 (re-search-forward ":[ \t]*\\([^:]+\\).$")
2974 (match-string 1)
2976 ;; ###### Easier? (from Milan version 0.1.28)
2977 ;; (setq info-node (Info-extract-menu-node-name))
2978 (if (equal fa (car last-entry))
2979 (setcdr last-entry (cons info-node (cdr last-entry)))
2980 (setq last-entry (cons fa (list info-node))
2981 l (cons last-entry l)))))
2982 (nreverse l)
2983 ))))
2984 (if verbose
2985 (message "Building info alist... done.")))
2988 ;;-------------------------------------------------------------------
2989 ;; Miscellaneous functions
2990 ;;-------------------------------------------------------------------
2992 ;; For Windows. Change backslash to slash. SICStus handles either
2993 ;; path separator but backslash must be doubled, therefore use slash.
2994 (defun prolog-bsts (string)
2995 "Change backslashes to slashes in STRING."
2996 (let ((str1 (copy-sequence string))
2997 (len (length string))
2998 (i 0))
2999 (while (< i len)
3000 (if (char-equal (aref str1 i) ?\\)
3001 (aset str1 i ?/))
3002 (setq i (1+ i)))
3003 str1))
3005 ;;(defun prolog-temporary-file ()
3006 ;; "Make temporary file name for compilation."
3007 ;; (make-temp-name
3008 ;; (concat
3009 ;; (or
3010 ;; (getenv "TMPDIR")
3011 ;; (getenv "TEMP")
3012 ;; (getenv "TMP")
3013 ;; (getenv "SYSTEMP")
3014 ;; "/tmp")
3015 ;; "/prolcomp")))
3016 ;;(setq prolog-temp-filename (prolog-bsts (prolog-temporary-file)))
3018 (defun prolog-temporary-file ()
3019 "Make temporary file name for compilation."
3020 (if prolog-temporary-file-name
3021 ;; We already have a file, erase content and continue
3022 (progn
3023 (write-region "" nil prolog-temporary-file-name nil 'silent)
3024 prolog-temporary-file-name)
3025 ;; Actually create the file and set `prolog-temporary-file-name'
3026 ;; accordingly.
3027 (setq prolog-temporary-file-name
3028 (make-temp-file "prolcomp" nil ".pl"))))
3030 (defun prolog-goto-prolog-process-buffer ()
3031 "Switch to the prolog process buffer and go to its end."
3032 (switch-to-buffer-other-window "*prolog*")
3033 (goto-char (point-max))
3036 (defun prolog-enable-sicstus-sd ()
3037 "Enable the source level debugging facilities of SICStus 3.7 and later."
3038 (interactive)
3039 (require 'pltrace) ; Load the SICStus debugger code
3040 ;; Turn on the source level debugging by default
3041 (add-hook 'prolog-inferior-mode-hook 'pltrace-on)
3042 (if (not prolog-use-sicstus-sd)
3043 (progn
3044 ;; If there is a *prolog* buffer, then call pltrace-on
3045 (if (get-buffer "*prolog*")
3046 ;; Avoid compilation warnings by using eval
3047 (eval '(pltrace-on)))
3048 (setq prolog-use-sicstus-sd t)
3051 (defun prolog-disable-sicstus-sd ()
3052 "Disable the source level debugging facilities of SICStus 3.7 and later."
3053 (interactive)
3054 (setq prolog-use-sicstus-sd nil)
3055 ;; Remove the hook
3056 (remove-hook 'prolog-inferior-mode-hook 'pltrace-on)
3057 ;; If there is a *prolog* buffer, then call pltrace-off
3058 (if (get-buffer "*prolog*")
3059 ;; Avoid compile warnings by using eval
3060 (eval '(pltrace-off))))
3062 (defun prolog-toggle-sicstus-sd ()
3063 ;; FIXME: Use define-minor-mode.
3064 "Toggle the source level debugging facilities of SICStus 3.7 and later."
3065 (interactive)
3066 (if prolog-use-sicstus-sd
3067 (prolog-disable-sicstus-sd)
3068 (prolog-enable-sicstus-sd)))
3070 (defun prolog-debug-on (&optional arg)
3071 "Enable debugging.
3072 When called with prefix argument ARG, disable debugging instead."
3073 (interactive "P")
3074 (if arg
3075 (prolog-debug-off)
3076 (prolog-process-insert-string (get-process "prolog")
3077 prolog-debug-on-string)
3078 (process-send-string "prolog" prolog-debug-on-string)))
3080 (defun prolog-debug-off ()
3081 "Disable debugging."
3082 (interactive)
3083 (prolog-process-insert-string (get-process "prolog")
3084 prolog-debug-off-string)
3085 (process-send-string "prolog" prolog-debug-off-string))
3087 (defun prolog-trace-on (&optional arg)
3088 "Enable tracing.
3089 When called with prefix argument ARG, disable tracing instead."
3090 (interactive "P")
3091 (if arg
3092 (prolog-trace-off)
3093 (prolog-process-insert-string (get-process "prolog")
3094 prolog-trace-on-string)
3095 (process-send-string "prolog" prolog-trace-on-string)))
3097 (defun prolog-trace-off ()
3098 "Disable tracing."
3099 (interactive)
3100 (prolog-process-insert-string (get-process "prolog")
3101 prolog-trace-off-string)
3102 (process-send-string "prolog" prolog-trace-off-string))
3104 (defun prolog-zip-on (&optional arg)
3105 "Enable zipping (for SICStus 3.7 and later).
3106 When called with prefix argument ARG, disable zipping instead."
3107 (interactive "P")
3108 (if (not (and (eq prolog-system 'sicstus)
3109 (prolog-atleast-version '(3 . 7))))
3110 (error "Only works for SICStus 3.7 and later"))
3111 (if arg
3112 (prolog-zip-off)
3113 (prolog-process-insert-string (get-process "prolog")
3114 prolog-zip-on-string)
3115 (process-send-string "prolog" prolog-zip-on-string)))
3117 (defun prolog-zip-off ()
3118 "Disable zipping (for SICStus 3.7 and later)."
3119 (interactive)
3120 (prolog-process-insert-string (get-process "prolog")
3121 prolog-zip-off-string)
3122 (process-send-string "prolog" prolog-zip-off-string))
3124 ;; (defun prolog-create-predicate-index ()
3125 ;; "Create an index for all predicates in the buffer."
3126 ;; (let ((predlist '())
3127 ;; clauseinfo
3128 ;; object
3129 ;; pos
3130 ;; )
3131 ;; (goto-char (point-min))
3132 ;; ;; Replace with prolog-clause-start!
3133 ;; (while (re-search-forward "^.+:-" nil t)
3134 ;; (setq pos (match-beginning 0))
3135 ;; (setq clauseinfo (prolog-clause-info))
3136 ;; (setq object (prolog-in-object))
3137 ;; (setq predlist (append
3138 ;; predlist
3139 ;; (list (cons
3140 ;; (if (and (eq prolog-system 'sicstus)
3141 ;; (prolog-in-object))
3142 ;; (format "%s::%s/%d"
3143 ;; object
3144 ;; (nth 0 clauseinfo)
3145 ;; (nth 1 clauseinfo))
3146 ;; (format "%s/%d"
3147 ;; (nth 0 clauseinfo)
3148 ;; (nth 1 clauseinfo)))
3149 ;; pos
3150 ;; ))))
3151 ;; (prolog-end-of-predicate))
3152 ;; predlist))
3154 (defun prolog-get-predspec ()
3155 (save-excursion
3156 (let ((state (prolog-clause-info))
3157 (object (prolog-in-object)))
3158 (if (or (equal (nth 0 state) "") (equal (prolog-in-string-or-comment) 'cmt))
3160 (if (and (eq prolog-system 'sicstus)
3161 object)
3162 (format "%s::%s/%d"
3163 object
3164 (nth 0 state)
3165 (nth 1 state))
3166 (format "%s/%d"
3167 (nth 0 state)
3168 (nth 1 state)))
3169 ))))
3171 ;; For backward compatibility. Stolen from custom.el.
3172 (or (fboundp 'match-string)
3173 ;; Introduced in Emacs 19.29.
3174 (defun match-string (num &optional string)
3175 "Return string of text matched by last search.
3176 NUM specifies which parenthesized expression in the last regexp.
3177 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3178 Zero means the entire text matched by the whole regexp or whole string.
3179 STRING should be given if the last search was by `string-match' on STRING."
3180 (if (match-beginning num)
3181 (if string
3182 (substring string (match-beginning num) (match-end num))
3183 (buffer-substring (match-beginning num) (match-end num))))))
3185 (defun prolog-pred-start ()
3186 "Return the starting point of the first clause of the current predicate."
3187 (save-excursion
3188 (goto-char (prolog-clause-start))
3189 ;; Find first clause, unless it was a directive
3190 (if (and (not (looking-at "[:?]-"))
3191 (not (looking-at "[ \t]*[%/]")) ; Comment
3194 (let* ((pinfo (prolog-clause-info))
3195 (predname (nth 0 pinfo))
3196 (arity (nth 1 pinfo))
3197 (op (point)))
3198 (while (and (re-search-backward
3199 (format "^%s\\([(\\.]\\| *%s\\)"
3200 predname prolog-head-delimiter) nil t)
3201 (= arity (nth 1 (prolog-clause-info)))
3203 (setq op (point)))
3204 (if (eq prolog-system 'mercury)
3205 ;; Skip to the beginning of declarations of the predicate
3206 (progn
3207 (goto-char (prolog-beginning-of-clause))
3208 (while (and (not (eq (point) op))
3209 (looking-at
3210 (format ":-[ \t]*\\(pred\\|mode\\)[ \t]+%s"
3211 predname)))
3212 (setq op (point))
3213 (goto-char (prolog-beginning-of-clause)))))
3215 (point))))
3217 (defun prolog-pred-end ()
3218 "Return the position at the end of the last clause of the current predicate."
3219 (save-excursion
3220 (goto-char (prolog-clause-end)) ; if we are before the first predicate
3221 (goto-char (prolog-clause-start))
3222 (let* ((pinfo (prolog-clause-info))
3223 (predname (nth 0 pinfo))
3224 (arity (nth 1 pinfo))
3225 oldp
3226 (notdone t)
3227 (op (point)))
3228 (if (looking-at "[:?]-")
3229 ;; This was a directive
3230 (progn
3231 (if (and (eq prolog-system 'mercury)
3232 (looking-at
3233 (format ":-[ \t]*\\(pred\\|mode\\)[ \t]+\\(%s+\\)"
3234 prolog-atom-regexp)))
3235 ;; Skip predicate declarations
3236 (progn
3237 (setq predname (buffer-substring-no-properties
3238 (match-beginning 2) (match-end 2)))
3239 (while (re-search-forward
3240 (format
3241 "\n*\\(:-[ \t]*\\(pred\\|mode\\)[ \t]+\\)?%s[( \t]"
3242 predname)
3243 nil t))))
3244 (goto-char (prolog-clause-end))
3245 (setq op (point)))
3246 ;; It was not a directive, find the last clause
3247 (while (and notdone
3248 (re-search-forward
3249 (format "^%s\\([(\\.]\\| *%s\\)"
3250 predname prolog-head-delimiter) nil t)
3251 (= arity (nth 1 (prolog-clause-info))))
3252 (setq oldp (point))
3253 (setq op (prolog-clause-end))
3254 (if (>= oldp op)
3255 ;; End of clause not found.
3256 (setq notdone nil)
3257 ;; Continue while loop
3258 (goto-char op))))
3259 op)))
3261 (defun prolog-clause-start (&optional not-allow-methods)
3262 "Return the position at the start of the head of the current clause.
3263 If NOTALLOWMETHODS is non-nil then do not match on methods in
3264 objects (relevent only if 'prolog-system' is set to 'sicstus)."
3265 (save-excursion
3266 (let ((notdone t)
3267 (retval (point-min)))
3268 (end-of-line)
3270 ;; SICStus object?
3271 (if (and (not not-allow-methods)
3272 (eq prolog-system 'sicstus)
3273 (prolog-in-object))
3274 (while (and
3275 notdone
3276 ;; Search for a head or a fact
3277 (re-search-backward
3278 ;; If in object, then find method start.
3279 ;; "^[ \t]+[a-z$].*\\(:-\\|&\\|:: {\\|,\\)"
3280 "^[ \t]+[a-z$].*\\(:-\\|&\\|:: {\\)" ; The comma causes
3281 ; problems since we cannot assume
3282 ; that the line starts at column 0,
3283 ; thus we don't know if the line
3284 ; is a head or a subgoal
3285 (point-min) t))
3286 (if (>= (prolog-paren-balance) 0) ; To no match on " a) :-"
3287 ;; Start of method found
3288 (progn
3289 (setq retval (point))
3290 (setq notdone nil)))
3291 ) ; End of while
3293 ;; Not in object
3294 (while (and
3295 notdone
3296 ;; Search for a text at beginning of a line
3297 ;; ######
3298 ;; (re-search-backward "^[a-z$']" nil t))
3299 (let ((case-fold-search nil))
3300 (re-search-backward
3301 ;; (format "^[%s$']" prolog-lower-case-string)
3302 ;; FIXME: Use [:lower:]
3303 (format "^\\([%s$']\\|[:?]-\\)" prolog-lower-case-string)
3304 nil t)))
3305 (let ((bal (prolog-paren-balance)))
3306 (cond
3307 ((> bal 0)
3308 ;; Start of clause found
3309 (progn
3310 (setq retval (point))
3311 (setq notdone nil)))
3312 ((and (= bal 0)
3313 (looking-at
3314 (format ".*\\(\\.\\|%s\\|!,\\)[ \t]*\\(%%.*\\|\\)$"
3315 prolog-head-delimiter)))
3316 ;; Start of clause found if the line ends with a '.' or
3317 ;; a prolog-head-delimiter
3318 (progn
3319 (setq retval (point))
3320 (setq notdone nil))
3322 (t nil) ; Do nothing
3323 ))))
3325 retval)))
3327 (defun prolog-clause-end (&optional not-allow-methods)
3328 "Return the position at the end of the current clause.
3329 If NOTALLOWMETHODS is non-nil then do not match on methods in
3330 objects (relevent only if 'prolog-system' is set to 'sicstus)."
3331 (save-excursion
3332 (beginning-of-line) ; Necessary since we use "^...." for the search.
3333 (if (re-search-forward
3334 (if (and (not not-allow-methods)
3335 (eq prolog-system 'sicstus)
3336 (prolog-in-object))
3337 (format
3338 "^\\(%s\\|%s\\|[^\n\'\"%%]\\)*&[ \t]*\\(\\|%%.*\\)$\\|[ \t]*}"
3339 prolog-quoted-atom-regexp prolog-string-regexp)
3340 (format
3341 "^\\(%s\\|%s\\|[^\n\'\"%%]\\)*\\.[ \t]*\\(\\|%%.*\\)$"
3342 prolog-quoted-atom-regexp prolog-string-regexp))
3343 nil t)
3344 (if (and (prolog-in-string-or-comment)
3345 (not (eobp)))
3346 (progn
3347 (forward-char)
3348 (prolog-clause-end))
3349 (point))
3350 (point))))
3352 (defun prolog-clause-info ()
3353 "Return a (name arity) list for the current clause."
3354 (save-excursion
3355 (goto-char (prolog-clause-start))
3356 (let* ((op (point))
3357 (predname
3358 (if (looking-at prolog-atom-char-regexp)
3359 (progn
3360 (skip-chars-forward "^ (\\.")
3361 (buffer-substring op (point)))
3362 ""))
3363 (arity 0))
3364 ;; Retrieve the arity.
3365 (if (looking-at prolog-left-paren)
3366 (let ((endp (save-excursion
3367 (prolog-forward-list) (point))))
3368 (setq arity 1)
3369 (forward-char 1) ; Skip the opening paren.
3370 (while (progn
3371 (skip-chars-forward "^[({,'\"")
3372 (< (point) endp))
3373 (if (looking-at ",")
3374 (progn
3375 (setq arity (1+ arity))
3376 (forward-char 1) ; Skip the comma.
3378 ;; We found a string, list or something else we want
3379 ;; to skip over. Always use prolog-tokenize,
3380 ;; parse-partial-sexp does not have a 'skipover mode.
3381 (goto-char (nth 5 (prolog-tokenize (point) endp 'skipover))))
3383 (list predname arity))))
3385 (defun prolog-in-object ()
3386 "Return object name if the point is inside a SICStus object definition."
3387 ;; Return object name if the last line that starts with a character
3388 ;; that is neither white space nor a comment start
3389 (save-excursion
3390 (if (save-excursion
3391 (beginning-of-line)
3392 (looking-at "\\([^\n ]+\\)[ \t]*::[ \t]*{"))
3393 ;; We were in the head of the object
3394 (match-string 1)
3395 ;; We were not in the head
3396 (if (and (re-search-backward "^[a-z$'}]" nil t)
3397 (looking-at "\\([^\n ]+\\)[ \t]*::[ \t]*{"))
3398 (match-string 1)
3399 nil))))
3401 (defun prolog-forward-list ()
3402 "Move the point to the matching right parenthesis."
3403 (interactive)
3404 (if prolog-use-prolog-tokenizer-flag
3405 (let ((state (prolog-tokenize (point) (point-max) 'zerodepth)))
3406 (goto-char (nth 5 state)))
3407 (forward-list)))
3409 ;; NB: This could be done more efficiently!
3410 (defun prolog-backward-list ()
3411 "Move the point to the matching left parenthesis."
3412 (interactive)
3413 (if prolog-use-prolog-tokenizer-flag
3414 (let ((bal 0)
3415 (paren-regexp (concat prolog-left-paren "\\|" prolog-right-paren))
3416 (notdone t))
3417 ;; FIXME: Doesn't this incorrectly count 0'( and 0') ?
3418 (while (and notdone (re-search-backward paren-regexp nil t))
3419 (cond
3420 ((looking-at prolog-left-paren)
3421 (if (not (prolog-in-string-or-comment))
3422 (setq bal (1+ bal)))
3423 (if (= bal 0)
3424 (setq notdone nil)))
3425 ((looking-at prolog-right-paren)
3426 (if (not (prolog-in-string-or-comment))
3427 (setq bal (1- bal))))
3429 (backward-list)))
3431 (defun prolog-beginning-of-clause ()
3432 "Move to the beginning of current clause.
3433 If already at the beginning of clause, move to previous clause."
3434 (interactive)
3435 (let ((point (point))
3436 (new-point (prolog-clause-start)))
3437 (if (and (>= new-point point)
3438 (> point 1))
3439 (progn
3440 (goto-char (1- point))
3441 (goto-char (prolog-clause-start)))
3442 (goto-char new-point)
3443 (skip-chars-forward " \t"))))
3445 ;; (defun prolog-previous-clause ()
3446 ;; "Move to the beginning of the previous clause."
3447 ;; (interactive)
3448 ;; (forward-char -1)
3449 ;; (prolog-beginning-of-clause))
3451 (defun prolog-end-of-clause ()
3452 "Move to the end of clause.
3453 If already at the end of clause, move to next clause."
3454 (interactive)
3455 (let ((point (point))
3456 (new-point (prolog-clause-end)))
3457 (if (and (<= new-point point)
3458 (not (eq new-point (point-max))))
3459 (progn
3460 (goto-char (1+ point))
3461 (goto-char (prolog-clause-end)))
3462 (goto-char new-point))))
3464 ;; (defun prolog-next-clause ()
3465 ;; "Move to the beginning of the next clause."
3466 ;; (interactive)
3467 ;; (prolog-end-of-clause)
3468 ;; (forward-char)
3469 ;; (prolog-end-of-clause)
3470 ;; (prolog-beginning-of-clause))
3472 (defun prolog-beginning-of-predicate ()
3473 "Go to the nearest beginning of predicate before current point.
3474 Return the final point or nil if no such a beginning was found."
3475 (interactive)
3476 (let ((op (point))
3477 (pos (prolog-pred-start)))
3478 (if pos
3479 (if (= op pos)
3480 (if (not (bobp))
3481 (progn
3482 (goto-char pos)
3483 (backward-char 1)
3484 (setq pos (prolog-pred-start))
3485 (if pos
3486 (progn
3487 (goto-char pos)
3488 (point)))))
3489 (goto-char pos)
3490 (point)))))
3492 (defun prolog-end-of-predicate ()
3493 "Go to the end of the current predicate."
3494 (interactive)
3495 (let ((op (point)))
3496 (goto-char (prolog-pred-end))
3497 (if (= op (point))
3498 (progn
3499 (forward-line 1)
3500 (prolog-end-of-predicate)))))
3502 (defun prolog-insert-predspec ()
3503 "Insert the predspec for the current predicate."
3504 (interactive)
3505 (let* ((pinfo (prolog-clause-info))
3506 (predname (nth 0 pinfo))
3507 (arity (nth 1 pinfo)))
3508 (insert (format "%s/%d" predname arity))))
3510 (defun prolog-view-predspec ()
3511 "Insert the predspec for the current predicate."
3512 (interactive)
3513 (let* ((pinfo (prolog-clause-info))
3514 (predname (nth 0 pinfo))
3515 (arity (nth 1 pinfo)))
3516 (message (format "%s/%d" predname arity))))
3518 (defun prolog-insert-predicate-template ()
3519 "Insert the template for the current clause."
3520 (interactive)
3521 (let* ((n 1)
3522 oldp
3523 (pinfo (prolog-clause-info))
3524 (predname (nth 0 pinfo))
3525 (arity (nth 1 pinfo)))
3526 (insert predname)
3527 (if (> arity 0)
3528 (progn
3529 (insert "(")
3530 (when prolog-electric-dot-full-predicate-template
3531 (setq oldp (point))
3532 (while (< n arity)
3533 (insert ",")
3534 (setq n (1+ n)))
3535 (insert ")")
3536 (goto-char oldp))
3540 (defun prolog-insert-next-clause ()
3541 "Insert newline and the name of the current clause."
3542 (interactive)
3543 (insert "\n")
3544 (prolog-insert-predicate-template))
3546 (defun prolog-insert-module-modeline ()
3547 "Insert a modeline for module specification.
3548 This line should be first in the buffer.
3549 The module name should be written manually just before the semi-colon."
3550 (interactive)
3551 (insert "%%% -*- Module: ; -*-\n")
3552 (backward-char 6))
3554 (defalias 'prolog-uncomment-region
3555 (if (fboundp 'uncomment-region) #'uncomment-region
3556 (lambda (beg end)
3557 "Uncomment the region between BEG and END."
3558 (interactive "r")
3559 (comment-region beg end -1))))
3561 (defun prolog-goto-comment-column (&optional nocreate)
3562 "Move comments on the current line to the correct position.
3563 If NOCREATE is nil (or omitted) and there is no comment on the line, then
3564 a new comment is created."
3565 (interactive)
3566 (beginning-of-line)
3567 (if (or (not nocreate)
3568 (and
3569 (re-search-forward
3570 (format "^\\(\\(%s\\|%s\\|[^\n\'\"%%]\\)*\\)%% *"
3571 prolog-quoted-atom-regexp prolog-string-regexp)
3572 (line-end-position) 'limit)
3573 (progn
3574 (goto-char (match-beginning 0))
3575 (not (eq (prolog-in-string-or-comment) 'txt)))))
3576 (indent-for-comment)))
3578 (defun prolog-indent-predicate ()
3579 "*Indent the current predicate."
3580 (interactive)
3581 (indent-region (prolog-pred-start) (prolog-pred-end) nil))
3583 (defun prolog-indent-buffer ()
3584 "*Indent the entire buffer."
3585 (interactive)
3586 (indent-region (point-min) (point-max) nil))
3588 (defun prolog-mark-clause ()
3589 "Put mark at the end of this clause and move point to the beginning."
3590 (interactive)
3591 (let ((pos (point)))
3592 (goto-char (prolog-clause-end))
3593 (forward-line 1)
3594 (beginning-of-line)
3595 (set-mark (point))
3596 (goto-char pos)
3597 (goto-char (prolog-clause-start))))
3599 (defun prolog-mark-predicate ()
3600 "Put mark at the end of this predicate and move point to the beginning."
3601 (interactive)
3602 (goto-char (prolog-pred-end))
3603 (let ((pos (point)))
3604 (forward-line 1)
3605 (beginning-of-line)
3606 (set-mark (point))
3607 (goto-char pos)
3608 (goto-char (prolog-pred-start))))
3610 ;; Stolen from `cc-mode.el':
3611 (defun prolog-electric-delete (arg)
3612 "Delete preceding character or whitespace.
3613 If `prolog-hungry-delete-key-flag' is non-nil, then all preceding whitespace is
3614 consumed. If however an ARG is supplied, or `prolog-hungry-delete-key-flag' is
3615 nil, or point is inside a literal then the function in the variable
3616 `backward-delete-char' is called."
3617 (interactive "P")
3618 (if (or (not prolog-hungry-delete-key-flag)
3620 (prolog-in-string-or-comment))
3621 (funcall 'backward-delete-char (prefix-numeric-value arg))
3622 (let ((here (point)))
3623 (skip-chars-backward " \t\n")
3624 (if (/= (point) here)
3625 (delete-region (point) here)
3626 (funcall 'backward-delete-char 1)
3627 ))))
3629 ;; For XEmacs compatibility (suggested by Per Mildner)
3630 (put 'prolog-electric-delete 'pending-delete 'supersede)
3632 (defun prolog-electric-if-then-else (arg)
3633 "If `prolog-electric-if-then-else-flag' is non-nil, indent if-then-else constructs.
3634 Bound to the >, ; and ( keys."
3635 (interactive "P")
3636 (self-insert-command (prefix-numeric-value arg))
3637 (if prolog-electric-if-then-else-flag (prolog-insert-spaces-after-paren)))
3639 (defun prolog-electric-colon (arg)
3640 "If `prolog-electric-colon-flag' is non-nil, insert the electric `:' construct.
3641 That is, insert space (if appropriate), `:-' and newline if colon is pressed
3642 at the end of a line that starts in the first column (i.e., clause
3643 heads)."
3644 (interactive "P")
3645 (if (and prolog-electric-colon-flag
3646 (null arg)
3647 (eolp)
3648 ;(not (string-match "^\\s " (thing-at-point 'line))))
3649 (not (string-match "^\\(\\s \\|%\\)" (thing-at-point 'line))))
3650 (progn
3651 (unless (save-excursion (backward-char 1) (looking-at "\\s "))
3652 (insert " "))
3653 (insert ":-\n")
3654 (prolog-indent-line))
3655 (self-insert-command (prefix-numeric-value arg))))
3657 (defun prolog-electric-dash (arg)
3658 "If `prolog-electric-dash-flag' is non-nil, insert the electric `-' construct.
3659 that is, insert space (if appropriate), `-->' and newline if dash is pressed
3660 at the end of a line that starts in the first column (i.e., DCG
3661 heads)."
3662 (interactive "P")
3663 (if (and prolog-electric-dash-flag
3664 (null arg)
3665 (eolp)
3666 ;(not (string-match "^\\s " (thing-at-point 'line))))
3667 (not (string-match "^\\(\\s \\|%\\)" (thing-at-point 'line))))
3668 (progn
3669 (unless (save-excursion (backward-char 1) (looking-at "\\s "))
3670 (insert " "))
3671 (insert "-->\n")
3672 (prolog-indent-line))
3673 (self-insert-command (prefix-numeric-value arg))))
3675 (defun prolog-electric-dot (arg)
3676 "Insert dot and newline or a head of a new clause.
3678 If `prolog-electric-dot-flag' is nil, then simply insert dot.
3679 Otherwise::
3680 When invoked at the end of nonempty line, insert dot and newline.
3681 When invoked at the end of an empty line, insert a recursive call to
3682 the current predicate.
3683 When invoked at the beginning of line, insert a head of a new clause
3684 of the current predicate.
3686 When called with prefix argument ARG, insert just dot."
3687 (interactive "P")
3688 ;; Check for situations when the electricity should not be active
3689 (if (or (not prolog-electric-dot-flag)
3691 (prolog-in-string-or-comment)
3692 ;; Do not be electric in a floating point number or an operator
3693 (not
3695 ;; (re-search-backward
3696 ;; ######
3697 ;; "\\(^\\|[])}a-zA-Z_!'0-9]+\\)[ \t]*\\=" nil t)))
3698 (save-excursion
3699 (re-search-backward
3700 ;; "\\(^\\|[])}_!'0-9]+\\)[ \t]*\\=" nil t)))
3701 "\\(^\\|[])}_!'0-9]+\\)[ \t]*\\="
3702 nil t))
3703 (save-excursion
3704 (re-search-backward
3705 ;; "\\(^\\|[])}a-zA-Z]+\\)[ \t]*\\=" nil t)))
3706 (format "\\(^\\|[])}%s]+\\)[ \t]*\\="
3707 prolog-lower-case-string) ;FIXME: [:lower:]
3708 nil t))
3709 (save-excursion
3710 (re-search-backward
3711 ;; "\\(^\\|[])}a-zA-Z]+\\)[ \t]*\\=" nil t)))
3712 (format "\\(^\\|[])}%s]+\\)[ \t]*\\="
3713 prolog-upper-case-string) ;FIXME: [:upper:]
3714 nil t))
3717 ;; Do not be electric if inside a parenthesis pair.
3718 (not (= (prolog-region-paren-balance (prolog-clause-start) (point))
3721 (funcall 'self-insert-command (prefix-numeric-value arg))
3722 (cond
3723 ;; Beginning of line
3724 ((bolp)
3725 (prolog-insert-predicate-template))
3726 ;; At an empty line with at least one whitespace
3727 ((save-excursion
3728 (beginning-of-line)
3729 (looking-at "[ \t]+$"))
3730 (prolog-insert-predicate-template)
3731 (when prolog-electric-dot-full-predicate-template
3732 (save-excursion
3733 (end-of-line)
3734 (insert ".\n"))))
3735 ;; Default
3737 (insert ".\n"))
3740 (defun prolog-electric-underscore ()
3741 "Replace variable with an underscore.
3742 If `prolog-electric-underscore-flag' is non-nil and the point is
3743 on a variable then replace the variable with underscore and skip
3744 the following comma and whitespace, if any.
3745 If the point is not on a variable then insert underscore."
3746 (interactive)
3747 (if prolog-electric-underscore-flag
3748 (let (;start
3749 (case-fold-search nil)
3750 (oldp (point)))
3751 ;; ######
3752 ;;(skip-chars-backward "a-zA-Z_")
3753 (skip-chars-backward
3754 (format "%s%s_"
3755 ;; FIXME: Why not "a-zA-Z"?
3756 prolog-lower-case-string
3757 prolog-upper-case-string))
3759 ;(setq start (point))
3760 (if (and (not (prolog-in-string-or-comment))
3761 ;; ######
3762 ;; (looking-at "\\<[_A-Z][a-zA-Z_0-9]*\\>"))
3763 (looking-at (format "\\<[_%s][%s%s_0-9]*\\>"
3764 ;; FIXME: Use [:upper:] and friends.
3765 prolog-upper-case-string
3766 prolog-lower-case-string
3767 prolog-upper-case-string)))
3768 (progn
3769 (replace-match "_")
3770 (skip-chars-forward ", \t\n"))
3771 (goto-char oldp)
3772 (self-insert-command 1))
3774 (self-insert-command 1))
3778 (defun prolog-find-term (functor arity &optional prefix)
3779 "Go to the position at the start of the next occurrence of a term.
3780 The term is specified with FUNCTOR and ARITY. The optional argument
3781 PREFIX is the prefix of the search regexp."
3782 (let* (;; If prefix is not set then use the default "\\<"
3783 (prefix (if (not prefix)
3784 "\\<"
3785 prefix))
3786 (regexp (concat prefix functor))
3787 (i 1))
3789 ;; Build regexp for the search if the arity is > 0
3790 (if (= arity 0)
3791 ;; Add that the functor must be at the end of a word. This
3792 ;; does not work if the arity is > 0 since the closing )
3793 ;; is not a word constituent.
3794 (setq regexp (concat regexp "\\>"))
3795 ;; Arity is > 0, add parens and commas
3796 (setq regexp (concat regexp "("))
3797 (while (< i arity)
3798 (setq regexp (concat regexp ".+,"))
3799 (setq i (1+ i)))
3800 (setq regexp (concat regexp ".+)")))
3802 ;; Search, and return position
3803 (if (re-search-forward regexp nil t)
3804 (goto-char (match-beginning 0))
3805 (error "Term not found"))
3808 (defun prolog-variables-to-anonymous (beg end)
3809 "Replace all variables within a region BEG to END by anonymous variables."
3810 (interactive "r")
3811 (save-excursion
3812 (let ((case-fold-search nil))
3813 (goto-char end)
3814 (while (re-search-backward "\\<[A-Z_][a-zA-Z_0-9]*\\>" beg t)
3815 (progn
3816 (replace-match "_")
3817 (backward-char)))
3821 (defun prolog-set-atom-regexps ()
3822 "Set the `prolog-atom-char-regexp' and `prolog-atom-regexp' variables.
3823 Must be called after `prolog-build-case-strings'."
3824 (setq prolog-atom-char-regexp
3825 (format "[%s%s0-9_$]"
3826 ;; FIXME: why not a-zA-Z?
3827 prolog-lower-case-string
3828 prolog-upper-case-string))
3829 (setq prolog-atom-regexp
3830 (format "[%s$]%s*"
3831 prolog-lower-case-string
3832 prolog-atom-char-regexp))
3835 (defun prolog-build-case-strings ()
3836 "Set `prolog-upper-case-string' and `prolog-lower-case-string'.
3837 Uses the current case-table for extracting the relevant information."
3838 (let ((up_string "")
3839 (low_string ""))
3840 ;; Use `map-char-table' if it is defined. Otherwise enumerate all
3841 ;; numbers between 0 and 255. `map-char-table' is probably safer.
3843 ;; `map-char-table' causes problems under Emacs 23.0.0.1, the
3844 ;; while loop seems to do its job well (Ryszard Szopa)
3846 ;;(if (and (not (featurep 'xemacs))
3847 ;; (fboundp 'map-char-table))
3848 ;; (map-char-table
3849 ;; (lambda (key value)
3850 ;; (cond
3851 ;; ((and
3852 ;; (eq (prolog-int-to-char key) (downcase key))
3853 ;; (eq (prolog-int-to-char key) (upcase key)))
3854 ;; ;; Do nothing if upper and lower case are the same
3855 ;; )
3856 ;; ((eq (prolog-int-to-char key) (downcase key))
3857 ;; ;; The char is lower case
3858 ;; (setq low_string (format "%s%c" low_string key)))
3859 ;; ((eq (prolog-int-to-char key) (upcase key))
3860 ;; ;; The char is upper case
3861 ;; (setq up_string (format "%s%c" up_string key)))
3862 ;; ))
3863 ;; (current-case-table))
3864 ;; `map-char-table' was undefined.
3865 (let ((key 0))
3866 (while (< key 256)
3867 (cond
3868 ((and
3869 (eq (prolog-int-to-char key) (downcase key))
3870 (eq (prolog-int-to-char key) (upcase key)))
3871 ;; Do nothing if upper and lower case are the same
3873 ((eq (prolog-int-to-char key) (downcase key))
3874 ;; The char is lower case
3875 (setq low_string (format "%s%c" low_string key)))
3876 ((eq (prolog-int-to-char key) (upcase key))
3877 ;; The char is upper case
3878 (setq up_string (format "%s%c" up_string key)))
3880 (setq key (1+ key))))
3881 ;; )
3882 ;; The strings are single-byte strings
3883 (setq prolog-upper-case-string (prolog-dash-letters up_string))
3884 (setq prolog-lower-case-string (prolog-dash-letters low_string))
3887 ;(defun prolog-regexp-dash-continuous-chars (chars)
3888 ; (let ((ints (mapcar #'prolog-char-to-int (string-to-list chars)))
3889 ; (beg 0)
3890 ; (end 0))
3891 ; (if (null ints)
3892 ; chars
3893 ; (while (and (< (+ beg 1) (length chars))
3894 ; (not (or (= (+ (nth beg ints) 1) (nth (+ beg 1) ints))
3895 ; (= (nth beg ints) (nth (+ beg 1) ints)))))
3896 ; (setq beg (+ beg 1)))
3897 ; (setq beg (+ beg 1)
3898 ; end beg)
3899 ; (while (and (< (+ end 1) (length chars))
3900 ; (or (= (+ (nth end ints) 1) (nth (+ end 1) ints))
3901 ; (= (nth end ints) (nth (+ end 1) ints))))
3902 ; (setq end (+ end 1)))
3903 ; (if (equal (substring chars end) "")
3904 ; (substring chars 0 beg)
3905 ; (concat (substring chars 0 beg) "-"
3906 ; (prolog-regexp-dash-continuous-chars (substring chars end))))
3907 ; )))
3909 (defun prolog-ints-intervals (ints)
3910 "Return a list of intervals (from . to) covering INTS."
3911 (when ints
3912 (setq ints (sort ints '<))
3913 (let ((prev (car ints))
3914 (interval-start (car ints))
3915 intervals)
3916 (while ints
3917 (let ((next (car ints)))
3918 (when (> next (1+ prev)) ; start of new interval
3919 (setq intervals (cons (cons interval-start prev) intervals))
3920 (setq interval-start next))
3921 (setq prev next)
3922 (setq ints (cdr ints))))
3923 (setq intervals (cons (cons interval-start prev) intervals))
3924 (reverse intervals))))
3926 (defun prolog-dash-letters (string)
3927 "Return a condensed regexp covering all letters in STRING."
3928 (let ((intervals (prolog-ints-intervals (mapcar #'prolog-char-to-int
3929 (string-to-list string))))
3930 codes)
3931 (while intervals
3932 (let* ((i (car intervals))
3933 (from (car i))
3934 (to (cdr i))
3935 (c (cond ((= from to) `(,from))
3936 ((= (1+ from) to) `(,from ,to))
3937 (t `(,from ?- ,to)))))
3938 (setq codes (cons c codes)))
3939 (setq intervals (cdr intervals)))
3940 (apply 'concat (reverse codes))))
3942 ;(defun prolog-condense-character-sets (regexp)
3943 ; "Condense adjacent characters in character sets of REGEXP."
3944 ; (let ((next -1))
3945 ; (while (setq next (string-match "\\[\\(.*?\\)\\]" regexp (1+ next)))
3946 ; (setq regexp (replace-match (prolog-dash-letters (match-string 1 regexp))
3947 ; t t regexp 1))))
3948 ; regexp)
3950 ;; GNU Emacs compatibility: GNU Emacs does not differentiate between
3951 ;; ints and chars, or at least these two are interchangeable.
3952 (defalias 'prolog-int-to-char
3953 (if (fboundp 'int-to-char) #'int-to-char #'identity))
3955 (defalias 'prolog-char-to-int
3956 (if (fboundp 'char-to-int) #'char-to-int #'identity))
3958 ;;-------------------------------------------------------------------
3959 ;; Menu stuff (both for the editing buffer and for the inferior
3960 ;; prolog buffer)
3961 ;;-------------------------------------------------------------------
3963 (unless (fboundp 'region-exists-p)
3964 (defun region-exists-p ()
3965 "Non-nil iff the mark is set. Lobotomized version for Emacsen that do not provide their own."
3966 (mark)))
3969 ;; GNU Emacs ignores `easy-menu-add' so the order in which the menus
3970 ;; are defined _is_ important!
3972 (easy-menu-define
3973 prolog-menu-help (list prolog-mode-map prolog-inferior-mode-map)
3974 "Help menu for the Prolog mode."
3975 ;; FIXME: Does it really deserve a whole menu to itself?
3976 `(,(if (featurep 'xemacs) "Help"
3977 ;; Not sure it's worth the trouble. --Stef
3978 ;; (add-to-list 'menu-bar-final-items
3979 ;; (easy-menu-intern "Prolog-Help"))
3980 "Prolog-help")
3981 ["On predicate" prolog-help-on-predicate prolog-help-function-i]
3982 ["Apropos" prolog-help-apropos (eq prolog-system 'swi)]
3983 "---"
3984 ["Describe mode" describe-mode t]))
3986 (easy-menu-define
3987 prolog-edit-menu-runtime prolog-mode-map
3988 "Runtime Prolog commands available from the editing buffer"
3989 ;; FIXME: Don't use a whole menu for just "Run Mercury". --Stef
3990 `("System"
3991 ;; Runtime menu name.
3992 ,@(unless (featurep 'xemacs)
3993 '(:label (cond ((eq prolog-system 'eclipse) "ECLiPSe")
3994 ((eq prolog-system 'mercury) "Mercury")
3995 (t "System"))))
3997 ;; Consult items, NIL for mercury.
3998 ["Consult file" prolog-consult-file
3999 :included (not (eq prolog-system 'mercury))]
4000 ["Consult buffer" prolog-consult-buffer
4001 :included (not (eq prolog-system 'mercury))]
4002 ["Consult region" prolog-consult-region :active (region-exists-p)
4003 :included (not (eq prolog-system 'mercury))]
4004 ["Consult predicate" prolog-consult-predicate
4005 :included (not (eq prolog-system 'mercury))]
4007 ;; Compile items, NIL for everything but SICSTUS.
4008 ,(if (featurep 'xemacs) "---"
4009 ["---" nil :included (eq prolog-system 'sicstus)])
4010 ["Compile file" prolog-compile-file
4011 :included (eq prolog-system 'sicstus)]
4012 ["Compile buffer" prolog-compile-buffer
4013 :included (eq prolog-system 'sicstus)]
4014 ["Compile region" prolog-compile-region :active (region-exists-p)
4015 :included (eq prolog-system 'sicstus)]
4016 ["Compile predicate" prolog-compile-predicate
4017 :included (eq prolog-system 'sicstus)]
4019 ;; Debug items, NIL for Mercury.
4020 ,(if (featurep 'xemacs) "---"
4021 ["---" nil :included (not (eq prolog-system 'mercury))])
4022 ;; FIXME: Could we use toggle or radio buttons? --Stef
4023 ["Debug" prolog-debug-on :included (not (eq prolog-system 'mercury))]
4024 ["Debug off" prolog-debug-off
4025 ;; In SICStus, these are pairwise disjunctive,
4026 ;; so it's enough with a single "off"-command
4027 :included (not (memq prolog-system '(mercury sicstus)))]
4028 ["Trace" prolog-trace-on :included (not (eq prolog-system 'mercury))]
4029 ["Trace off" prolog-trace-off
4030 :included (not (memq prolog-system '(mercury sicstus)))]
4031 ["Zip" prolog-zip-on :included (and (eq prolog-system 'sicstus)
4032 (prolog-atleast-version '(3 . 7)))]
4033 ["All debug off" prolog-debug-off
4034 :included (eq prolog-system 'sicstus)]
4035 ["Source level debugging"
4036 prolog-toggle-sicstus-sd
4037 :included (and (eq prolog-system 'sicstus)
4038 (prolog-atleast-version '(3 . 7)))
4039 :style toggle
4040 :selected prolog-use-sicstus-sd]
4042 "---"
4043 ["Run" run-prolog
4044 :suffix (cond ((eq prolog-system 'eclipse) "ECLiPSe")
4045 ((eq prolog-system 'mercury) "Mercury")
4046 (t "Prolog"))]))
4048 (easy-menu-define
4049 prolog-edit-menu-insert-move prolog-mode-map
4050 "Commands for Prolog code manipulation."
4051 '("Prolog"
4052 ["Comment region" comment-region (region-exists-p)]
4053 ["Uncomment region" prolog-uncomment-region (region-exists-p)]
4054 ["Add comment/move to comment" indent-for-comment t]
4055 ["Convert variables in region to '_'" prolog-variables-to-anonymous
4056 :active (region-exists-p) :included (not (eq prolog-system 'mercury))]
4057 "---"
4058 ["Insert predicate template" prolog-insert-predicate-template t]
4059 ["Insert next clause head" prolog-insert-next-clause t]
4060 ["Insert predicate spec" prolog-insert-predspec t]
4061 ["Insert module modeline" prolog-insert-module-modeline t]
4062 "---"
4063 ["Beginning of clause" prolog-beginning-of-clause t]
4064 ["End of clause" prolog-end-of-clause t]
4065 ["Beginning of predicate" prolog-beginning-of-predicate t]
4066 ["End of predicate" prolog-end-of-predicate t]
4067 "---"
4068 ["Indent line" prolog-indent-line t]
4069 ["Indent region" indent-region (region-exists-p)]
4070 ["Indent predicate" prolog-indent-predicate t]
4071 ["Indent buffer" prolog-indent-buffer t]
4072 ["Align region" align (region-exists-p)]
4073 "---"
4074 ["Mark clause" prolog-mark-clause t]
4075 ["Mark predicate" prolog-mark-predicate t]
4076 ["Mark paragraph" mark-paragraph t]
4077 ;;"---"
4078 ;;["Fontify buffer" font-lock-fontify-buffer t]
4081 (defun prolog-menu ()
4082 "Add the menus for the Prolog editing buffers."
4084 (easy-menu-add prolog-edit-menu-insert-move)
4085 (easy-menu-add prolog-edit-menu-runtime)
4087 ;; Add predicate index menu
4088 (set (make-local-variable 'imenu-create-index-function)
4089 'imenu-default-create-index-function)
4090 ;;Milan (this has problems with object methods...) ###### Does it? (Stefan)
4091 (setq imenu-prev-index-position-function 'prolog-beginning-of-predicate)
4092 (setq imenu-extract-index-name-function 'prolog-get-predspec)
4094 (if (and prolog-imenu-flag
4095 (< (count-lines (point-min) (point-max)) prolog-imenu-max-lines))
4096 (imenu-add-to-menubar "Predicates"))
4098 (easy-menu-add prolog-menu-help))
4100 (easy-menu-define
4101 prolog-inferior-menu-all prolog-inferior-mode-map
4102 "Menu for the inferior Prolog buffer."
4103 `("Prolog"
4104 ;; Runtime menu name.
4105 ,@(unless (featurep 'xemacs)
4106 '(:label (cond ((eq prolog-system 'eclipse) "ECLiPSe")
4107 ((eq prolog-system 'mercury) "Mercury")
4108 (t "Prolog"))))
4110 ;; Debug items, NIL for Mercury.
4111 ,(if (featurep 'xemacs) "---"
4112 ["---" nil :included (not (eq prolog-system 'mercury))])
4113 ;; FIXME: Could we use toggle or radio buttons? --Stef
4114 ["Debug" prolog-debug-on :included (not (eq prolog-system 'mercury))]
4115 ["Debug off" prolog-debug-off
4116 ;; In SICStus, these are pairwise disjunctive,
4117 ;; so it's enough with a single "off"-command
4118 :included (not (memq prolog-system '(mercury sicstus)))]
4119 ["Trace" prolog-trace-on :included (not (eq prolog-system 'mercury))]
4120 ["Trace off" prolog-trace-off
4121 :included (not (memq prolog-system '(mercury sicstus)))]
4122 ["Zip" prolog-zip-on :included (and (eq prolog-system 'sicstus)
4123 (prolog-atleast-version '(3 . 7)))]
4124 ["All debug off" prolog-debug-off
4125 :included (eq prolog-system 'sicstus)]
4126 ["Source level debugging"
4127 prolog-toggle-sicstus-sd
4128 :included (and (eq prolog-system 'sicstus)
4129 (prolog-atleast-version '(3 . 7)))
4130 :style toggle
4131 :selected prolog-use-sicstus-sd]
4133 ;; Runtime.
4134 "---"
4135 ["Interrupt Prolog" comint-interrupt-subjob t]
4136 ["Quit Prolog" comint-quit-subjob t]
4137 ["Kill Prolog" comint-kill-subjob t]))
4140 (defun prolog-inferior-menu ()
4141 "Create the menus for the Prolog inferior buffer.
4142 This menu is dynamically created because one may change systems during
4143 the life of an Emacs session."
4144 (easy-menu-add prolog-inferior-menu-all)
4145 (easy-menu-add prolog-menu-help))
4147 (defun prolog-mode-version ()
4148 "Echo the current version of Prolog mode in the minibuffer."
4149 (interactive)
4150 (message "Using Prolog mode version %s" prolog-mode-version))
4152 (provide 'prolog)
4154 ;;; prolog.el ends here